diff options
206 files changed, 2803 insertions, 23255 deletions
@@ -19,7 +19,7 @@ m4/lt~obsolete.m4 autom4te.cache # downloaded files -gmock +/gmock # in-tree configure-generated files Makefile @@ -58,8 +58,6 @@ python/*.egg python/.eggs/ python/.tox python/build/ -python/google/protobuf/compiler/ -python/google/protobuf/util/ src/js_embed src/protoc @@ -180,3 +178,11 @@ ruby/Gemfile.lock ruby/compatibility_tests/v3.0.0/protoc ruby/compatibility_tests/v3.0.0/tests/generated_code_pb.rb ruby/compatibility_tests/v3.0.0/tests/test_import_pb.rb + +# IntelliJ CLion Config files and build output +cmake/.idea +cmake/cmake-build-debug/ + +# Common build subdirectories. +./.build/ +./_build/ diff --git a/.gitmodules b/.gitmodules index 55a47cea..bcd125a4 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +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 @@ -19,15 +19,14 @@ config_setting( # Protobuf Runtime Library ################################################################################ -WIN_COPTS = [ +MSVC_COPTS = [ "/DHAVE_PTHREAD", "/wd4018", # -Wno-sign-compare "/wd4514", # -Wno-unused-function ] COPTS = select({ - ":windows" : WIN_COPTS, - ":windows_msvc" : WIN_COPTS, + ":msvc" : MSVC_COPTS, "//conditions:default": [ "-DHAVE_PTHREAD", "-Wall", @@ -41,13 +40,8 @@ COPTS = select({ }) config_setting( - name = "windows", - values = { "cpu": "x64_windows" }, -) - -config_setting( - name = "windows_msvc", - values = { "cpu": "x64_windows_msvc" }, + name = "msvc", + values = { "compiler": "msvc-cl" }, ) config_setting( @@ -57,11 +51,10 @@ config_setting( }, ) -# Android and Windows builds do not need to link in a separate pthread library. +# Android and MSVC builds do not need to link in a separate pthread library. LINK_OPTS = select({ ":android": [], - ":windows": [], - ":windows_msvc": [], + ":msvc": [], "//conditions:default": ["-lpthread", "-lm"], }) @@ -89,13 +82,10 @@ cc_library( "src/google/protobuf/io/zero_copy_stream_impl_lite.cc", "src/google/protobuf/message_lite.cc", "src/google/protobuf/repeated_field.cc", - "src/google/protobuf/stubs/atomicops_internals_x86_gcc.cc", - "src/google/protobuf/stubs/atomicops_internals_x86_msvc.cc", "src/google/protobuf/stubs/bytestream.cc", "src/google/protobuf/stubs/common.cc", "src/google/protobuf/stubs/int128.cc", "src/google/protobuf/stubs/io_win32.cc", - "src/google/protobuf/stubs/once.cc", "src/google/protobuf/stubs/status.cc", "src/google/protobuf/stubs/statusor.cc", "src/google/protobuf/stubs/stringpiece.cc", @@ -351,17 +341,6 @@ cc_library( "src/google/protobuf/compiler/java/java_shared_code_generator.cc", "src/google/protobuf/compiler/java/java_string_field.cc", "src/google/protobuf/compiler/java/java_string_field_lite.cc", - "src/google/protobuf/compiler/javanano/javanano_enum.cc", - "src/google/protobuf/compiler/javanano/javanano_enum_field.cc", - "src/google/protobuf/compiler/javanano/javanano_extension.cc", - "src/google/protobuf/compiler/javanano/javanano_field.cc", - "src/google/protobuf/compiler/javanano/javanano_file.cc", - "src/google/protobuf/compiler/javanano/javanano_generator.cc", - "src/google/protobuf/compiler/javanano/javanano_helpers.cc", - "src/google/protobuf/compiler/javanano/javanano_map_field.cc", - "src/google/protobuf/compiler/javanano/javanano_message.cc", - "src/google/protobuf/compiler/javanano/javanano_message_field.cc", - "src/google/protobuf/compiler/javanano/javanano_primitive_field.cc", "src/google/protobuf/compiler/js/js_generator.cc", "src/google/protobuf/compiler/js/well_known_types_embed.cc", "src/google/protobuf/compiler/objectivec/objectivec_enum.cc", @@ -478,6 +457,7 @@ COMMON_TEST_SRCS = [ "src/google/protobuf/arena_test_util.cc", "src/google/protobuf/map_test_util.cc", "src/google/protobuf/test_util.cc", + "src/google/protobuf/test_util.inc", "src/google/protobuf/testing/file.cc", "src/google/protobuf/testing/googletest.cc", ] @@ -520,6 +500,7 @@ cc_test( "src/google/protobuf/compiler/cpp/cpp_move_unittest.cc", "src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc", "src/google/protobuf/compiler/cpp/cpp_unittest.cc", + "src/google/protobuf/compiler/cpp/cpp_unittest.inc", "src/google/protobuf/compiler/cpp/metadata_test.cc", "src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc", "src/google/protobuf/compiler/csharp/csharp_generator_unittest.cc", @@ -544,6 +525,7 @@ cc_test( "src/google/protobuf/map_field_test.cc", "src/google/protobuf/map_test.cc", "src/google/protobuf/message_unittest.cc", + "src/google/protobuf/message_unittest.inc", "src/google/protobuf/no_field_presence_test.cc", "src/google/protobuf/preserve_unknown_enum_test.cc", "src/google/protobuf/proto3_arena_lite_unittest.cc", @@ -556,7 +538,6 @@ cc_test( "src/google/protobuf/stubs/common_unittest.cc", "src/google/protobuf/stubs/int128_unittest.cc", "src/google/protobuf/stubs/io_win32_unittest.cc", - "src/google/protobuf/stubs/once_unittest.cc", "src/google/protobuf/stubs/status_test.cc", "src/google/protobuf/stubs/statusor_test.cc", "src/google/protobuf/stubs/stringpiece_unittest.cc", @@ -565,7 +546,6 @@ cc_test( "src/google/protobuf/stubs/strutil_unittest.cc", "src/google/protobuf/stubs/template_util_unittest.cc", "src/google/protobuf/stubs/time_test.cc", - "src/google/protobuf/stubs/type_traits_unittest.cc", "src/google/protobuf/text_format_unittest.cc", "src/google/protobuf/unknown_field_set_unittest.cc", "src/google/protobuf/util/delimited_message_util_test.cc", @@ -1,14 +1,4 @@ -This license applies to all parts of Protocol Buffers except the following: - - - Atomicops support for generic gcc, located in - src/google/protobuf/stubs/atomicops_internals_generic_gcc.h. - This file is copyrighted by Red Hat Inc. - - - Atomicops support for AIX/POWER, located in - src/google/protobuf/stubs/atomicops_internals_power.h. - This file is copyrighted by Bloomberg Finance LP. - -Copyright 2014, Google Inc. All rights reserved. +Copyright 2008 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 diff --git a/Makefile.am b/Makefile.am index 07119d63..da371c67 100644 --- a/Makefile.am +++ b/Makefile.am @@ -8,8 +8,8 @@ AUTOMAKE_OPTIONS = foreign # the right time. SUBDIRS = . src -# Always include gmock in distributions. -DIST_SUBDIRS = $(subdirs) src conformance benchmarks +# Always include third_party directories in distributions. +DIST_SUBDIRS = src conformance benchmarks third_party/googletest # Build gmock before we build protobuf tests. We don't add gmock to SUBDIRS # because then "make check" would also build and run all of gmock's own tests, @@ -18,8 +18,8 @@ DIST_SUBDIRS = $(subdirs) src conformance benchmarks # the installed version of gmock if there is one. check-local: @echo "Making lib/libgmock.a lib/libgmock_main.a in gmock" - @cd gmock && $(MAKE) $(AM_MAKEFLAGS) lib/libgmock.la lib/libgmock_main.la - @cd gmock/gtest && $(MAKE) $(AM_MAKEFLAGS) lib/libgtest.la lib/libgtest_main.la + @cd third_party/googletest/googletest && $(MAKE) $(AM_MAKEFLAGS) lib/libgtest.la lib/libgtest_main.la + @cd third_party/googletest/googlemock && $(MAKE) $(AM_MAKEFLAGS) lib/libgmock.la lib/libgmock_main.la # We would like to clean gmock when "make clean" is invoked. But we have to # be careful because clean-local is also invoked during "make distclean", but @@ -28,9 +28,9 @@ check-local: # cd to the directory again and "make clean" it will fail. So, check that the # Makefile exists before recursing. clean-local: - @if test -e gmock/Makefile; then \ - echo "Making clean in gmock"; \ - cd gmock && $(MAKE) $(AM_MAKEFLAGS) clean; \ + @if test -e third_party/googletest/Makefile; then \ + echo "Making clean in googletest"; \ + cd third_party/googletest && $(MAKE) $(AM_MAKEFLAGS) clean; \ fi; \ if test -e conformance/Makefile; then \ echo "Making clean in conformance"; \ @@ -98,7 +98,6 @@ csharp_EXTRA_DIST= \ csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs \ csharp/src/Google.Protobuf.Test/JsonParserTest.cs \ csharp/src/Google.Protobuf.Test/JsonTokenizerTest.cs \ - csharp/src/Google.Protobuf.Test/Program.cs \ csharp/src/Google.Protobuf.Test/Reflection/CustomOptionsTest.cs \ csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs \ csharp/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs \ @@ -133,6 +132,7 @@ csharp_EXTRA_DIST= \ csharp/src/Google.Protobuf/Collections/ProtobufEqualityComparers.cs \ csharp/src/Google.Protobuf/Collections/ReadOnlyDictionary.cs \ csharp/src/Google.Protobuf/Collections/RepeatedField.cs \ + csharp/src/Google.Protobuf/Compatibility/MethodInfoExtensions.cs \ csharp/src/Google.Protobuf/Compatibility/PropertyInfoExtensions.cs \ csharp/src/Google.Protobuf/Compatibility/StreamExtensions.cs \ csharp/src/Google.Protobuf/Compatibility/TypeExtensions.cs \ @@ -387,45 +387,6 @@ java_EXTRA_DIST= java/util/src/test/java/com/google/protobuf/util/TimeUtilTest.java \ java/util/src/test/proto/com/google/protobuf/util/json_test.proto -javanano_EXTRA_DIST= \ - javanano/src/main/java/com/google/protobuf/nano/CodedOutputByteBufferNano.java \ - javanano/src/main/java/com/google/protobuf/nano/FieldData.java \ - javanano/src/main/java/com/google/protobuf/nano/FieldArray.java \ - javanano/src/main/java/com/google/protobuf/nano/WireFormatNano.java \ - javanano/src/main/java/com/google/protobuf/nano/Extension.java \ - javanano/src/main/java/com/google/protobuf/nano/CodedInputByteBufferNano.java \ - javanano/src/main/java/com/google/protobuf/nano/UnknownFieldData.java \ - javanano/src/main/java/com/google/protobuf/nano/MessageNano.java \ - javanano/src/main/java/com/google/protobuf/nano/InternalNano.java \ - javanano/src/main/java/com/google/protobuf/nano/InvalidProtocolBufferNanoException.java \ - javanano/src/main/java/com/google/protobuf/nano/MapFactories.java \ - javanano/src/main/java/com/google/protobuf/nano/ExtendableMessageNano.java \ - javanano/src/main/java/com/google/protobuf/nano/MessageNanoPrinter.java \ - javanano/src/test/java/com/google/protobuf/nano/unittest_accessors_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/unittest_enum_class_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/unittest_reference_types_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/unittest_extension_repeated_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/unittest_has_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/unittest_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nameclash_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/unittest_single_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/NanoTest.java \ - javanano/src/test/java/com/google/protobuf/nano/unittest_simple_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/unittest_import_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_merge_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/unittest_extension_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_packables_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/unittest_extension_singular_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/unittest_recursive_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/unittest_extension_packed_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/unittest_enum_validity_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/unittest_stringutf8_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/unittest_enum_class_multiple_nano.proto \ - javanano/src/test/java/com/google/protobuf/nano/map_test.proto \ - javanano/README.md \ - javanano/pom.xml - objectivec_EXTRA_DIST= \ objectivec/DevTools/check_version_stamps.sh \ objectivec/DevTools/compile_testing_protos.sh \ @@ -498,11 +459,13 @@ objectivec_EXTRA_DIST= \ objectivec/GPBWireFormat.m \ objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj \ objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata \ + objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist \ objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings \ objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme \ objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme \ objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj \ objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/contents.xcworkspacedata \ + objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist \ objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings \ objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme \ objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme \ @@ -540,6 +503,31 @@ objectivec_EXTRA_DIST= \ objectivec/Tests/GPBArrayTests.m \ objectivec/Tests/GPBCodedInputStreamTests.m \ objectivec/Tests/GPBCodedOuputStreamTests.m \ + objectivec/Tests/GPBCompileTest01.m \ + objectivec/Tests/GPBCompileTest02.m \ + objectivec/Tests/GPBCompileTest03.m \ + objectivec/Tests/GPBCompileTest04.m \ + objectivec/Tests/GPBCompileTest05.m \ + objectivec/Tests/GPBCompileTest06.m \ + objectivec/Tests/GPBCompileTest07.m \ + objectivec/Tests/GPBCompileTest08.m \ + objectivec/Tests/GPBCompileTest09.m \ + objectivec/Tests/GPBCompileTest10.m \ + objectivec/Tests/GPBCompileTest11.m \ + objectivec/Tests/GPBCompileTest12.m \ + objectivec/Tests/GPBCompileTest13.m \ + objectivec/Tests/GPBCompileTest14.m \ + objectivec/Tests/GPBCompileTest15.m \ + objectivec/Tests/GPBCompileTest16.m \ + objectivec/Tests/GPBCompileTest17.m \ + objectivec/Tests/GPBCompileTest18.m \ + objectivec/Tests/GPBCompileTest19.m \ + objectivec/Tests/GPBCompileTest20.m \ + objectivec/Tests/GPBCompileTest21.m \ + objectivec/Tests/GPBCompileTest22.m \ + objectivec/Tests/GPBCompileTest23.m \ + objectivec/Tests/GPBCompileTest24.m \ + objectivec/Tests/GPBCompileTest25.m \ objectivec/Tests/GPBConcurrencyTests.m \ objectivec/Tests/GPBDescriptorTests.m \ objectivec/Tests/GPBDictionaryTests+Bool.m \ @@ -775,6 +763,7 @@ python_EXTRA_DIST= \ python/MANIFEST.in \ python/google/__init__.py \ python/google/protobuf/__init__.py \ + python/google/protobuf/compiler/__init__.py \ python/google/protobuf/descriptor.py \ python/google/protobuf/descriptor_database.py \ python/google/protobuf/descriptor_pool.py \ @@ -870,6 +859,7 @@ python_EXTRA_DIST= \ python/google/protobuf/symbol_database.py \ python/google/protobuf/text_encoding.py \ python/google/protobuf/text_format.py \ + python/google/protobuf/util/__init__.py \ python/release.sh \ python/mox.py \ python/setup.cfg \ @@ -1036,7 +1026,7 @@ js_EXTRA_DIST= \ js/testbinary.proto \ js/testempty.proto -all_EXTRA_DIST=$(csharp_EXTRA_DIST) $(java_EXTRA_DIST) $(javanano_EXTRA_DIST) $(objectivec_EXTRA_DIST) $(php_EXTRA_DIST) $(python_EXTRA_DIST) $(ruby_EXTRA_DIST) $(js_EXTRA_DIST) +all_EXTRA_DIST=$(csharp_EXTRA_DIST) $(java_EXTRA_DIST) $(objectivec_EXTRA_DIST) $(php_EXTRA_DIST) $(python_EXTRA_DIST) $(ruby_EXTRA_DIST) $(js_EXTRA_DIST) EXTRA_DIST = $(@DIST_LANG@_EXTRA_DIST) \ autogen.sh \ @@ -1047,7 +1037,6 @@ EXTRA_DIST = $(@DIST_LANG@_EXTRA_DIST) \ CHANGES.txt \ update_file_lists.sh \ BUILD \ - gmock.BUILD \ WORKSPACE \ cmake/CMakeLists.txt \ cmake/README.md \ diff --git a/Protobuf.podspec b/Protobuf.podspec index 84a37996..24498a27 100644 --- a/Protobuf.podspec +++ b/Protobuf.podspec @@ -5,7 +5,7 @@ # dependent projects use the :git notation to refer to the library. Pod::Spec.new do |s| s.name = 'Protobuf' - s.version = '3.5.1' + s.version = '3.5.2' s.summary = 'Protocol Buffers v.3 runtime library for Objective-C.' s.homepage = 'https://github.com/google/protobuf' s.license = '3-Clause BSD License' @@ -1,8 +1,6 @@ Protocol Buffers - Google's data interchange format =================================================== -[![Build Status](https://travis-ci.org/google/protobuf.svg?branch=master)](https://travis-ci.org/google/protobuf) [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf) [![Build Status](https://grpc-testing.appspot.com/buildStatus/icon?job=protobuf_branch)](https://grpc-testing.appspot.com/job/protobuf_branch) [![Build Status](https://grpc-testing.appspot.com/job/protobuf_branch_32/badge/icon)](https://grpc-testing.appspot.com/job/protobuf_branch_32) [![Build Status](http://ci.bazel.io/buildStatus/icon?job=protobuf)](http://ci.bazel.io/job/protobuf/) - Copyright 2008 Google Inc. https://developers.google.com/protocol-buffers/ @@ -54,19 +52,18 @@ Protobuf supports several different programming languages. For each programming language, you can find instructions in the corresponding source directory about how to install protobuf runtime for that specific language: -| Language | Source | -|--------------------------------------|-------------------------------------------------------------| -| C++ (include C++ runtime and protoc) | [src](src) | -| Java | [java](java) | -| Python | [python](python) | -| Objective-C | [objectivec](objectivec) | -| C# | [csharp](csharp) | -| JavaNano | [javanano](javanano) | -| JavaScript | [js](js) | -| Ruby | [ruby](ruby) | -| Go | [golang/protobuf](https://github.com/golang/protobuf) | -| PHP | [php](php) | -| Dart | [dart-lang/protobuf](https://github.com/dart-lang/protobuf) | +| Language | Source | Ubuntu | MacOS | Windows | +|--------------------------------------|-------------------------------------------------------------|--------|-------|---------| +| C++ (include C++ runtime and protoc) | [src](src) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-cpp_distcheck.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fcpp_distcheck%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fcpp%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-cpp_distcheck.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fcpp_distcheck%2Fcontinuous) | [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf) | +| Java | [java](java) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-java_compatibility.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjava_compatibility%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-java_jdk7.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjava_jdk7%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-java_oracle7.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjava_oracle7%2Fcontinuous) | | | +| Python | [python](python) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python_compatibility.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython_compatibility%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python_cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython_cpp%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-python.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-python_cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython_cpp%2Fcontinuous) | | +| Objective-C | [objectivec](objectivec) | | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_cocoapods_integration.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_cocoapods_integration%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_ios_debug.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_ios_debug%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_ios_release.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_ios_release%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_osx.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_osx%2Fcontinuous) | | +| C# | [csharp](csharp) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-csharp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fcsharp%2Fcontinuous) | | [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf) | +| JavaScript | [js](js) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-javascript.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjavascript%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-javascript.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fjavascript%2Fcontinuous) | | +| Ruby | [ruby](ruby) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-ruby_all.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fruby_all%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-ruby21.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fruby21%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-ruby22.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fruby22%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-jruby.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fjruby%2Fcontinuous) | | +| Go | [golang/protobuf](https://github.com/golang/protobuf) | | | | +| PHP | [php](php) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-php_all.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fphp_all%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-32-bit.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2F32-bit%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-php5.6_mac.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fphp5.6_mac%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-php7.0_mac.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fphp7.0_mac%2Fcontinuous) | | +| Dart | [dart-lang/protobuf](https://github.com/dart-lang/protobuf) | | | | Quick Start ----------- @@ -1,10 +1,9 @@ workspace(name = "com_google_protobuf") -new_git_repository( - name = "googletest", - build_file = "gmock.BUILD", - remote = "https://github.com/google/googletest", - tag = "release-1.8.0", +new_local_repository( + name = "submodule_gmock", + path = "third_party/googletest", + build_file = "third_party/googletest/BUILD.bazel" ) new_http_archive( @@ -21,12 +20,12 @@ bind( bind( name = "gtest", - actual = "@googletest//:gtest", + actual = "@submodule_gmock//:gtest", ) bind( name = "gtest_main", - actual = "@googletest//:gtest_main", + actual = "@submodule_gmock//:gtest_main", ) bind( diff --git a/appveyor.bat b/appveyor.bat index ca88b25c..e59ebccc 100644 --- a/appveyor.bat +++ b/appveyor.bat @@ -26,8 +26,8 @@ dotnet restore dotnet build -c %configuration% || goto error echo Testing C# -dotnet run -c %configuration% -f netcoreapp1.0 -p Google.Protobuf.Test\Google.Protobuf.Test.csproj || goto error -dotnet run -c %configuration% -f net451 -p Google.Protobuf.Test\Google.Protobuf.Test.csproj || goto error +dotnet test -c %configuration% -f netcoreapp1.0 Google.Protobuf.Test\Google.Protobuf.Test.csproj || goto error +dotnet test -c %configuration% -f net451 Google.Protobuf.Test\Google.Protobuf.Test.csproj || goto error goto :EOF diff --git a/appveyor.yml b/appveyor.yml index aab56b04..02e0d313 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -22,15 +22,7 @@ environment: test: off install: - - curl -L -o release-1.7.0.zip https://github.com/google/googlemock/archive/release-1.7.0.zip - - 7z x release-1.7.0.zip - - del /Q release-1.7.0.zip - - rename googlemock-release-1.7.0 gmock - - curl -L -o release-1.7.0.zip "https://github.com/google/googletest/archive/release-1.7.0.zip" - - 7z x release-1.7.0.zip - - del /Q release-1.7.0.zip - - rename googletest-release-1.7.0 gtest - - move gtest gmock + - git submodule update --init --recursive before_build: - if %platform%==Win32 set generator=Visual Studio 14 @@ -17,7 +17,6 @@ if [ ! -z "$@" ]; then done fi - # Check that we're being run from the right directory. if test ! -f src/google/protobuf/stubs/common.h; then cat >&2 << __EOF__ @@ -27,23 +26,6 @@ __EOF__ exit 1 fi -# Check that gmock is present. Usually it is already there since the -# directory is set up as an SVN external. -if test ! -e gmock; then - echo "Google Mock not present. Fetching gmock-1.7.0 from the web..." - curl $curlopts -L -O https://github.com/google/googlemock/archive/release-1.7.0.zip - unzip -q release-1.7.0.zip - rm release-1.7.0.zip - mv googlemock-release-1.7.0 gmock -fi - -if test ! -e gmock/gtest; then - curl $curlopts -L -O https://github.com/google/googletest/archive/release-1.7.0.zip - unzip -q release-1.7.0.zip - rm release-1.7.0.zip - mv googletest-release-1.7.0 gmock/gtest -fi - set -ex # TODO(kenton): Remove the ",no-obsolete" part and fix the resulting warnings. diff --git a/benchmarks/README.md b/benchmarks/README.md index 8460a18a..21cd7352 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -3,7 +3,9 @@ This directory contains benchmarking schemas and data sets that you can use to test a variety of performance scenarios against your -protobuf language runtime. +protobuf language runtime. If you are looking for performance +numbers of officially support languages, see [here]( +https://github.com/google/protobuf/blob/master/docs/Performance.md) ## Prerequisite @@ -17,6 +19,11 @@ We are using [google/benchmark](https://github.com/google/benchmark) as the benchmark tool for testing cpp. This will be automaticly made during build the cpp benchmark. +The cpp protobuf performance can be improved by linking with [tcmalloc library]( +https://gperftools.github.io/gperftools/tcmalloc.html). For using tcmalloc, you +need to build [gpertools](https://github.com/gperftools/gperftools) to generate +libtcmallc.so library. + ### Java We're using maven to build the java benchmarks, which is the same as to build the Java protobuf. There're no other tools need to install. We're using @@ -79,6 +86,12 @@ $ make java $ make cpp ``` +For linking with tcmalloc: + +``` +$ env LD_PRELOAD={directory to libtcmalloc.so} make cpp +``` + ### Python: We have three versions of python protobuf implementation: pure python, cpp diff --git a/cmake/CMakeLists.txt b/cmake/CMakeLists.txt index bf3f8863..fca4da33 100644 --- a/cmake/CMakeLists.txt +++ b/cmake/CMakeLists.txt @@ -15,6 +15,9 @@ endif() # Project project(protobuf C CXX) +# Add c++11 flags for clang +set(CMAKE_CXX_FLAGS "-std=c++11") + # Options option(protobuf_BUILD_TESTS "Build tests" ON) option(protobuf_BUILD_EXAMPLES "Build examples" OFF) diff --git a/cmake/README.md b/cmake/README.md index 305ebb88..26a516c7 100644 --- a/cmake/README.md +++ b/cmake/README.md @@ -41,9 +41,16 @@ Good. Now you are ready to continue. Getting Sources =============== -You can get the latest stable source packages from the -[releases](https://github.com/google/protobuf/releases) page. -Or you can type: +You can get the latest stable source packages from the release page: + + https://github.com/google/protobuf/releases/latest + +For example: if you only need C++, download `protobuf-cpp-[VERSION].tar.gz`; if +you need C++ and Java, download `protobuf-java-[VERSION].tar.gz` (every package +contains C++ source already); if you need C++ and multiple other languages, +download `protobuf-all-[VERSION].tar.gz`. + +Or you can use git to clone from protobuf git repository. C:\Path\to> git clone -b [release_tag] https://github.com/google/protobuf.git @@ -55,26 +62,16 @@ Go to the project folder: C:\Path\to>cd protobuf C:\Path\to\protobuf> -Protobuf unit-tests require gmock to build. If you download protobuf source code -from the *releases* page, the *gmock* directory should already be there. If you checkout -the code via `git clone`, this *gmock* directory won't exist and you will have to -download it manually or skip building protobuf unit-tests. - -You can download gmock as follows: - - C:\Path\to\protobuf>git clone -b release-1.7.0 https://github.com/google/googlemock.git gmock - -Then go to *gmock* folder and download gtest: - - C:\Path\to\protobuf>cd gmock - C:\Path\to\protobuf\gmock>git clone -b release-1.7.0 https://github.com/google/googletest.git gtest +Remember to update any submodules if you are using git clone (you can skip this +step if you are using a release .tar.gz or .zip package): -If you absolutely don't want to build and run protobuf unit-tests, skip -this steps and use protobuf at your own risk. +```console +C:\Path\to> git submodule update --init --recursive +``` Now go to *cmake* folder in protobuf sources: - C:\Path\to\protobuf\gmock>cd ..\cmake + C:\Path\to\protobuf>cd cmake C:\Path\to\protobuf\cmake> Good. Now you are ready to *CMake* configuration. @@ -124,7 +121,7 @@ It will generate *nmake* *Makefile* in current directory. To create *Visual Studio* solution file: C:\Path\to\protobuf\cmake\build>mkdir solution & cd solution - C:\Path\to\protobuf\cmake\build\solution>cmake -G "Visual Studio 12 2013 Win64" ^ + C:\Path\to\protobuf\cmake\build\solution>cmake -G "Visual Studio 14 2015 Win64" ^ -DCMAKE_INSTALL_PREFIX=../../../../install ^ ../.. diff --git a/cmake/extract_includes.bat.in b/cmake/extract_includes.bat.in index 0ab8afeb..d9423f93 100644 --- a/cmake/extract_includes.bat.in +++ b/cmake/extract_includes.bat.in @@ -5,7 +5,6 @@ mkdir include\google\protobuf\compiler mkdir include\google\protobuf\compiler\cpp mkdir include\google\protobuf\compiler\csharp mkdir include\google\protobuf\compiler\java -mkdir include\google\protobuf\compiler\javanano mkdir include\google\protobuf\compiler\js mkdir include\google\protobuf\compiler\objectivec mkdir include\google\protobuf\compiler\php @@ -28,7 +27,6 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\csharp\cshar copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\importer.h" include\google\protobuf\compiler\importer.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\java_generator.h" include\google\protobuf\compiler\java\java_generator.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\java_names.h" include\google\protobuf\compiler\java\java_names.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\javanano\javanano_generator.h" include\google\protobuf\compiler\javanano\javanano_generator.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\js\js_generator.h" include\google\protobuf\compiler\js\js_generator.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\js\well_known_types_embed.h" include\google\protobuf\compiler\js\well_known_types_embed.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\objectivec\objectivec_generator.h" include\google\protobuf\compiler\objectivec\objectivec_generator.h @@ -54,6 +52,7 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_message_tab copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_message_util.h" include\google\protobuf\generated_message_util.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\has_bits.h" include\google\protobuf\has_bits.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\implicit_weak_message.h" include\google\protobuf\implicit_weak_message.h +copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\inlined_string_field.h" include\google\protobuf\inlined_string_field.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\coded_stream.h" include\google\protobuf\io\coded_stream.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\gzip_stream.h" include\google\protobuf\io\gzip_stream.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\printer.h" include\google\protobuf\io\printer.h @@ -96,7 +95,6 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\status.h" inclu copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\stl_util.h" include\google\protobuf\stubs\stl_util.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\stringpiece.h" include\google\protobuf\stubs\stringpiece.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\template_util.h" include\google\protobuf\stubs\template_util.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\type_traits.h" include\google\protobuf\stubs\type_traits.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\text_format.h" include\google\protobuf\text_format.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\timestamp.pb.h" include\google\protobuf\timestamp.pb.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\type.pb.h" include\google\protobuf\type.pb.h diff --git a/cmake/libprotoc.cmake b/cmake/libprotoc.cmake index 5f6d078c..ec6958bc 100644 --- a/cmake/libprotoc.cmake +++ b/cmake/libprotoc.cmake @@ -61,17 +61,6 @@ set(libprotoc_files ${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/javanano/javanano_enum.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_enum_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_extension.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_file.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_generator.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_helpers.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_map_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_message.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_message_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_primitive_field.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 @@ -96,41 +85,29 @@ set(libprotoc_files ) 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/importer.h - ${protobuf_source_dir}/src/google/protobuf/compiler/mock_code_generator.h - ${protobuf_source_dir}/src/google/protobuf/compiler/package_info.h - ${protobuf_source_dir}/src/google/protobuf/compiler/parser.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/subprocess.h - ${protobuf_source_dir}/src/google/protobuf/compiler/zip_writer.h ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_enum.h ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_enum_field.h ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_extension.h ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_field.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_map_field.h ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_message.h ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_message_field.h + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_options.h + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_primitive_field.h ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_service.h ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_string_field.h - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_unittest.h ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_doc_comment.h ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_enum.h ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_enum_field.h ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_field_base.h - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_generator.h ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_helpers.h ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_map_field.h ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_message.h ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_message_field.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/csharp/csharp_primitive_field.h ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_reflection_class.h @@ -149,7 +126,6 @@ set(libprotoc_headers ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_extension_lite.h ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_field.h ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_file.h - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_generator.h ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_generator_factory.h ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_helpers.h ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_lazy_message_field.h @@ -162,7 +138,6 @@ set(libprotoc_headers ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_field.h ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_field_lite.h ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_lite.h - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_names.h ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_name_resolver.h ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_options.h ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_primitive_field.h @@ -171,36 +146,19 @@ set(libprotoc_headers ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_shared_code_generator.h ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_string_field.h ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_string_field_lite.h - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_enum.h - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_enum_field.h - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_extension.h - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_field.h - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_file.h - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_generator.h - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_helpers.h - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_map_field.h - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_message.h - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_message_field.h - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_params.h - ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_primitive_field.h - ${protobuf_source_dir}/src/google/protobuf/compiler/js/js_generator.h - ${protobuf_source_dir}/src/google/protobuf/compiler/js/well_known_types_embed.h ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_enum.h ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_enum_field.h ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_extension.h ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_field.h ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_file.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/objectivec/objectivec_map_field.h ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_message.h ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_message_field.h ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_oneof.h ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.h - ${protobuf_source_dir}/src/google/protobuf/compiler/php/php_generator.h - ${protobuf_source_dir}/src/google/protobuf/compiler/python/python_generator.h - ${protobuf_source_dir}/src/google/protobuf/compiler/ruby/ruby_generator.h - ${protobuf_source_dir}/src/google/protobuf/compiler/plugin.pb.h + ${protobuf_source_dir}/src/google/protobuf/compiler/subprocess.h + ${protobuf_source_dir}/src/google/protobuf/compiler/zip_writer.h ) set(js_well_known_types_sources diff --git a/cmake/tests.cmake b/cmake/tests.cmake index 6ab3071c..ec790e33 100644 --- a/cmake/tests.cmake +++ b/cmake/tests.cmake @@ -1,24 +1,31 @@ -if (NOT EXISTS "${PROJECT_SOURCE_DIR}/../gmock/CMakeLists.txt") - message(FATAL_ERROR "Cannot find gmock directory.") +if (NOT EXISTS "${PROJECT_SOURCE_DIR}/../third_party/googletest/CMakeLists.txt") + message(FATAL_ERROR + "Cannot find third_party/googletest directory that's needed to " + "build tests. If you use git, make sure you have cloned submodules:\n" + " git submodule update --init --recursive\n" + "If instead you want to skip tests, run cmake with:\n" + " cmake -Dprotobuf_BUILD_TESTS=OFF\n") endif() option(protobuf_ABSOLUTE_TEST_PLUGIN_PATH "Using absolute test_plugin path in tests" ON) mark_as_advanced(protobuf_ABSOLUTE_TEST_PLUGIN_PATH) +set(googlemock_source_dir "${protobuf_source_dir}/third_party/googletest/googlemock") +set(googletest_source_dir "${protobuf_source_dir}/third_party/googletest/googletest") include_directories( - ${protobuf_source_dir}/gmock - ${protobuf_source_dir}/gmock/gtest - ${protobuf_source_dir}/gmock/gtest/include - ${protobuf_source_dir}/gmock/include + ${googlemock_source_dir} + ${googletest_source_dir} + ${googletest_source_dir}/include + ${googlemock_source_dir}/include ) add_library(gmock STATIC - ${protobuf_source_dir}/gmock/src/gmock-all.cc - ${protobuf_source_dir}/gmock/gtest/src/gtest-all.cc + "${googlemock_source_dir}/src/gmock-all.cc" + "${googletest_source_dir}/src/gtest-all.cc" ) target_link_libraries(gmock ${CMAKE_THREAD_LIBS_INIT}) -add_library(gmock_main STATIC ${protobuf_source_dir}/gmock/src/gmock_main.cc) +add_library(gmock_main STATIC "${googlemock_source_dir}/src/gmock_main.cc") target_link_libraries(gmock_main gmock) set(lite_test_protos @@ -107,6 +114,7 @@ set(common_test_files ${protobuf_source_dir}/src/google/protobuf/arena_test_util.cc ${protobuf_source_dir}/src/google/protobuf/map_test_util.cc ${protobuf_source_dir}/src/google/protobuf/test_util.cc + ${protobuf_source_dir}/src/google/protobuf/test_util.inc ${protobuf_source_dir}/src/google/protobuf/testing/file.cc ${protobuf_source_dir}/src/google/protobuf/testing/googletest.cc ) @@ -127,6 +135,7 @@ set(tests_files ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_unittest.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_unittest.inc ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/metadata_test.cc ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_generator_unittest.cc @@ -151,12 +160,12 @@ set(tests_files ${protobuf_source_dir}/src/google/protobuf/map_field_test.cc ${protobuf_source_dir}/src/google/protobuf/map_test.cc ${protobuf_source_dir}/src/google/protobuf/message_unittest.cc + ${protobuf_source_dir}/src/google/protobuf/message_unittest.inc ${protobuf_source_dir}/src/google/protobuf/no_field_presence_test.cc ${protobuf_source_dir}/src/google/protobuf/preserve_unknown_enum_test.cc ${protobuf_source_dir}/src/google/protobuf/proto3_arena_lite_unittest.cc ${protobuf_source_dir}/src/google/protobuf/proto3_arena_unittest.cc -# TODO(b/74491957) Make this unittest work -# ${protobuf_source_dir}/src/google/protobuf/proto3_lite_unittest.cc + ${protobuf_source_dir}/src/google/protobuf/proto3_lite_unittest.cc ${protobuf_source_dir}/src/google/protobuf/reflection_ops_unittest.cc ${protobuf_source_dir}/src/google/protobuf/repeated_field_reflection_unittest.cc ${protobuf_source_dir}/src/google/protobuf/repeated_field_unittest.cc diff --git a/configure.ac b/configure.ac index 4e3dc613..6e9ce1f5 100644 --- a/configure.ac +++ b/configure.ac @@ -17,7 +17,7 @@ AC_PREREQ(2.59) # In the SVN trunk, the version should always be the next anticipated release # version with the "-pre" suffix. (We used to use "-SNAPSHOT" but this pushed # the size of one file name in the dist tarfile over the 99-char limit.) -AC_INIT([Protocol Buffers],[3.5.1],[protobuf@googlegroups.com],[protobuf]) +AC_INIT([Protocol Buffers],[3.5.2],[protobuf@googlegroups.com],[protobuf]) AM_MAINTAINER_MODE([enable]) @@ -214,7 +214,7 @@ AX_CXX_COMPILE_STDCXX([11], [noext], [optional]) # too. export CFLAGS export CXXFLAGS -AC_CONFIG_SUBDIRS([gmock]) +AC_CONFIG_SUBDIRS([third_party/googletest]) AC_CONFIG_FILES([Makefile src/Makefile benchmarks/Makefile conformance/Makefile protobuf.pc protobuf-lite.pc]) AC_OUTPUT diff --git a/conformance/failure_list_ruby.txt b/conformance/failure_list_ruby.txt index 1bab1359..b2683372 100644 --- a/conformance/failure_list_ruby.txt +++ b/conformance/failure_list_ruby.txt @@ -120,6 +120,8 @@ Required.Proto3.JsonInput.ValueAcceptInteger.JsonOutput Required.Proto3.JsonInput.ValueAcceptInteger.ProtobufOutput Required.Proto3.JsonInput.ValueAcceptList.JsonOutput Required.Proto3.JsonInput.ValueAcceptList.ProtobufOutput +Required.Proto3.JsonInput.ValueAcceptListWithNull.JsonOutput +Required.Proto3.JsonInput.ValueAcceptListWithNull.ProtobufOutput Required.Proto3.JsonInput.ValueAcceptNull.JsonOutput Required.Proto3.JsonInput.ValueAcceptNull.ProtobufOutput Required.Proto3.JsonInput.ValueAcceptObject.JsonOutput diff --git a/csharp/Google.Protobuf.Tools.nuspec b/csharp/Google.Protobuf.Tools.nuspec index 62eb3b58..4294949f 100644 --- a/csharp/Google.Protobuf.Tools.nuspec +++ b/csharp/Google.Protobuf.Tools.nuspec @@ -5,7 +5,7 @@ <title>Google Protocol Buffers tools</title> <summary>Tools for Protocol Buffers - Google's data interchange format.</summary> <description>See project site for more info.</description> - <version>3.5.1</version> + <version>3.5.2</version> <authors>Google Inc.</authors> <owners>protobuf-packages</owners> <licenseUrl>https://github.com/google/protobuf/blob/master/LICENSE</licenseUrl> diff --git a/csharp/README.md b/csharp/README.md index c1d12419..436248bb 100644 --- a/csharp/README.md +++ b/csharp/README.md @@ -44,10 +44,8 @@ they're only relevant when building the `Google.Protobuf` assembly. Testing ======= -The unit tests use [NUnit 3](https://github.com/nunit/nunit). NUnit doesn't yet -support `dotnet test`, so for now the test project is a console application -using NUnitLite. Simply run `Google.Protobuf.Test.exe` to run the unit tests -directly, or else use `dotnet run`. +The unit tests use [NUnit 3](https://github.com/nunit/nunit). Tests can be +run using the Visual Studio Test Explorer or `dotnet test`. .NET 3.5 ======== diff --git a/csharp/buildall.sh b/csharp/buildall.sh index dd4b463d..50d8906d 100755 --- a/csharp/buildall.sh +++ b/csharp/buildall.sh @@ -14,4 +14,4 @@ echo Running tests. # If we want to test the .NET 4.5 version separately, we could # run Mono explicitly. However, we don't have any differences between # the .NET 4.5 and netstandard1.0 assemblies. -dotnet run -c $CONFIG -f netcoreapp1.0 -p $SRC/Google.Protobuf.Test/Google.Protobuf.Test.csproj +dotnet test -c $CONFIG -f netcoreapp1.0 $SRC/Google.Protobuf.Test/Google.Protobuf.Test.csproj diff --git a/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj b/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj index 06d07b9f..6a430116 100644 --- a/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj +++ b/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj @@ -1,7 +1,6 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <OutputType>Exe</OutputType> <TargetFrameworks>net451;netcoreapp1.0</TargetFrameworks> <AssemblyOriginatorKeyFile>../../keys/Google.Protobuf.snk</AssemblyOriginatorKeyFile> <SignAssembly>true</SignAssembly> @@ -14,8 +13,9 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="NUnit" Version="3.6.1" /> - <PackageReference Include="NUnitLite" Version="3.6.1" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0" /> + <PackageReference Include="NUnit" Version="3.9.0" /> + <PackageReference Include="NUnit3TestAdapter" Version="3.9.0" /> </ItemGroup> <!-- @@ -26,5 +26,5 @@ <PropertyGroup Condition="'$(OS)' != 'Windows_NT'"> <TargetFrameworks>netcoreapp1.0</TargetFrameworks> </PropertyGroup> - + </Project> diff --git a/csharp/src/Google.Protobuf.Test/Program.cs b/csharp/src/Google.Protobuf/Compatibility/MethodInfoExtensions.cs index 954c02b5..7b946cb6 100755..100644 --- a/csharp/src/Google.Protobuf.Test/Program.cs +++ b/csharp/src/Google.Protobuf/Compatibility/MethodInfoExtensions.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#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/ @@ -29,20 +29,19 @@ // (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 NUnitLite; + +#if NET35 +using System; using System.Reflection; -namespace Google.Protobuf.Test +namespace Google.Protobuf.Compatibility { - class Program + // .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 { - public static int Main(string[] args) - { - #if NET35 - return new AutoRun(typeof(Program).Assembly).Execute(args);
- #else - return new AutoRun(typeof(Program).GetTypeInfo().Assembly).Execute(args); - #endif - } + internal static Delegate CreateDelegate(this MethodInfo method, Type type) => + Delegate.CreateDelegate(type, method); } -}
\ No newline at end of file +} +#endif diff --git a/csharp/src/Google.Protobuf/Google.Protobuf.csproj b/csharp/src/Google.Protobuf/Google.Protobuf.csproj index 4df0bda6..6e4e1e2b 100644 --- a/csharp/src/Google.Protobuf/Google.Protobuf.csproj +++ b/csharp/src/Google.Protobuf/Google.Protobuf.csproj @@ -4,7 +4,7 @@ <Description>C# runtime library for Protocol Buffers - Google's data interchange format.</Description> <Copyright>Copyright 2015, Google Inc.</Copyright> <AssemblyTitle>Google Protocol Buffers</AssemblyTitle> - <VersionPrefix>3.5.1</VersionPrefix> + <VersionPrefix>3.5.2</VersionPrefix> <Authors>Google Inc.</Authors> <TargetFrameworks>netstandard1.0;net45</TargetFrameworks> <GenerateDocumentationFile>true</GenerateDocumentationFile> diff --git a/csharp/src/Google.Protobuf/Reflection/OneofAccessor.cs b/csharp/src/Google.Protobuf/Reflection/OneofAccessor.cs index 8714ab18..97596218 100644 --- a/csharp/src/Google.Protobuf/Reflection/OneofAccessor.cs +++ b/csharp/src/Google.Protobuf/Reflection/OneofAccessor.cs @@ -52,7 +52,7 @@ namespace Google.Protobuf.Reflection throw new ArgumentException("Cannot read from property"); } this.descriptor = descriptor; - caseDelegate = ReflectionUtil.CreateFuncIMessageT<int>(caseProperty.GetGetMethod()); + caseDelegate = ReflectionUtil.CreateFuncIMessageInt32(caseProperty.GetGetMethod()); this.descriptor = descriptor; clearDelegate = ReflectionUtil.CreateActionIMessage(clearMethod); diff --git a/csharp/src/Google.Protobuf/Reflection/ReflectionUtil.cs b/csharp/src/Google.Protobuf/Reflection/ReflectionUtil.cs index df820ca3..80d5c774 100644 --- a/csharp/src/Google.Protobuf/Reflection/ReflectionUtil.cs +++ b/csharp/src/Google.Protobuf/Reflection/ReflectionUtil.cs @@ -30,11 +30,14 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion +using Google.Protobuf.Compatibility; using System; -using System.Collections.Generic; -using System.Linq.Expressions; using System.Reflection; +#if NET35 +using Google.Protobuf.Compatibility; +#endif + namespace Google.Protobuf.Reflection { /// <summary> @@ -53,55 +56,149 @@ namespace Google.Protobuf.Reflection internal static readonly Type[] EmptyTypes = new Type[0]; /// <summary> - /// Creates a delegate which will cast the argument to the appropriate method target type, + /// Creates a delegate which will cast the argument to the type that declares the method, /// call the method on it, then convert the result to object. /// </summary> - internal static Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method) - { - ParameterExpression parameter = Expression.Parameter(typeof(IMessage), "p"); - Expression downcast = Expression.Convert(parameter, method.DeclaringType); - Expression call = Expression.Call(downcast, method); - Expression upcast = Expression.Convert(call, typeof(object)); - return Expression.Lambda<Func<IMessage, object>>(upcast, parameter).Compile(); - } + /// <param name="method">The method to create a delegate for, which must be declared in an IMessage + /// implementation.</param> + internal static Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method) => + GetReflectionHelper(method.DeclaringType, method.ReturnType).CreateFuncIMessageObject(method); /// <summary> - /// Creates a delegate which will cast the argument to the appropriate method target type, - /// call the method on it, then convert the result to the specified type. + /// Creates a delegate which will cast the argument to the type that declares the method, + /// call the method on it, then convert the result to the specified type. The method is expected + /// to actually return an enum (because of where we're calling it - for oneof cases). Sometimes that + /// means we need some extra work to perform conversions. /// </summary> - internal static Func<IMessage, T> CreateFuncIMessageT<T>(MethodInfo method) - { - ParameterExpression parameter = Expression.Parameter(typeof(IMessage), "p"); - Expression downcast = Expression.Convert(parameter, method.DeclaringType); - Expression call = Expression.Call(downcast, method); - Expression upcast = Expression.Convert(call, typeof(T)); - return Expression.Lambda<Func<IMessage, T>>(upcast, parameter).Compile(); - } + /// <param name="method">The method to create a delegate for, which must be declared in an IMessage + /// implementation.</param> + internal static Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method) => + GetReflectionHelper(method.DeclaringType, method.ReturnType).CreateFuncIMessageInt32(method); + + /// <summary> + /// Creates a delegate which will execute the given method after casting the first argument to + /// the type that declares the method, and the second argument to the first parameter type of the method. + /// </summary> + /// <param name="method">The method to create a delegate for, which must be declared in an IMessage + /// implementation.</param> + internal static Action<IMessage, object> CreateActionIMessageObject(MethodInfo method) => + GetReflectionHelper(method.DeclaringType, method.GetParameters()[0].ParameterType).CreateActionIMessageObject(method); /// <summary> /// Creates a delegate which will execute the given method after casting the first argument to - /// the target type of the method, and the second argument to the first parameter type of the method. + /// type that declares the method. + /// </summary> + /// <param name="method">The method to create a delegate for, which must be declared in an IMessage + /// implementation.</param> + internal static Action<IMessage> CreateActionIMessage(MethodInfo method) => + GetReflectionHelper(method.DeclaringType, typeof(object)).CreateActionIMessage(method); + + /// <summary> + /// Creates a reflection helper for the given type arguments. Currently these are created on demand + /// rather than cached; this will be "busy" when initially loading a message's descriptor, but after that + /// they can be garbage collected. We could cache them by type if that proves to be important, but creating + /// an object is pretty cheap. /// </summary> - internal static Action<IMessage, object> CreateActionIMessageObject(MethodInfo method) + private static IReflectionHelper GetReflectionHelper(Type t1, Type t2) => + (IReflectionHelper) Activator.CreateInstance(typeof(ReflectionHelper<,>).MakeGenericType(t1, t2)); + + // Non-generic interface allowing us to use an instance of ReflectionHelper<T1, T2> without statically + // knowing the types involved. + private interface IReflectionHelper { - ParameterExpression targetParameter = Expression.Parameter(typeof(IMessage), "target"); - ParameterExpression argParameter = Expression.Parameter(typeof(object), "arg"); - Expression castTarget = Expression.Convert(targetParameter, method.DeclaringType); - Expression castArgument = Expression.Convert(argParameter, method.GetParameters()[0].ParameterType); - Expression call = Expression.Call(castTarget, method, castArgument); - return Expression.Lambda<Action<IMessage, object>>(call, targetParameter, argParameter).Compile(); + Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method); + Action<IMessage> CreateActionIMessage(MethodInfo method); + Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method); + Action<IMessage, object> CreateActionIMessageObject(MethodInfo method); + } + + private class ReflectionHelper<T1, T2> : IReflectionHelper + { + + public Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method) + { + // On pleasant runtimes, we can create a Func<int> from a method returning + // an enum based on an int. That's the fast path. + if (CanConvertEnumFuncToInt32Func) + { + var del = (Func<T1, int>) method.CreateDelegate(typeof(Func<T1, int>)); + return message => del((T1) message); + } + else + { + // On some runtimes (e.g. old Mono) the return type has to be exactly correct, + // so we go via boxing. Reflection is already fairly inefficient, and this is + // only used for one-of case checking, fortunately. + var del = (Func<T1, T2>) method.CreateDelegate(typeof(Func<T1, T2>)); + return message => (int) (object) del((T1) message); + } + } + + public Action<IMessage> CreateActionIMessage(MethodInfo method) + { + var del = (Action<T1>) method.CreateDelegate(typeof(Action<T1>)); + return message => del((T1) message); + } + + public Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method) + { + var del = (Func<T1, T2>) method.CreateDelegate(typeof(Func<T1, T2>)); + return message => del((T1) message); + } + + public Action<IMessage, object> CreateActionIMessageObject(MethodInfo method) + { + var del = (Action<T1, T2>) method.CreateDelegate(typeof(Action<T1, T2>)); + return (message, arg) => del((T1) message, (T2) arg); + } + } + + // Runtime compatibility checking code - see ReflectionHelper<T1, T2>.CreateFuncIMessageInt32 for + // details about why we're doing this. + + // Deliberately not inside the generic type. We only want to check this once. + private static bool CanConvertEnumFuncToInt32Func { get; } = CheckCanConvertEnumFuncToInt32Func(); + + private static bool CheckCanConvertEnumFuncToInt32Func() + { + try + { + PreventLinkerFailures(); + // Try to do the conversion using reflection, so we can see whether it's supported. + MethodInfo method = typeof(ReflectionUtil).GetMethod(nameof(SampleEnumMethod)); + // If this passes, we're in a reasonable runtime. + method.CreateDelegate(typeof(Func<int>)); + return true; + } + catch (ArgumentException) + { + return false; + } } /// <summary> - /// Creates a delegate which will execute the given method after casting the first argument to - /// the target type of the method. + /// This method is effectively pointless, but only called once. It's present (and called) + /// to avoid the Unity linker from removing code that's only called via reflection. /// </summary> - internal static Action<IMessage> CreateActionIMessage(MethodInfo method) + private static void PreventLinkerFailures() { - ParameterExpression targetParameter = Expression.Parameter(typeof(IMessage), "target"); - Expression castTarget = Expression.Convert(targetParameter, method.DeclaringType); - Expression call = Expression.Call(castTarget, method); - return Expression.Lambda<Action<IMessage>>(call, targetParameter).Compile(); - } + // Exercise the method directly. This should avoid any pro-active linkers from stripping + // the method out. + SampleEnum x = SampleEnumMethod(); + if (x != SampleEnum.X) + { + throw new InvalidOperationException("Failure in reflection utilities"); + } + // Make sure the ReflectionHelper parameterless constructor isn't removed... + var helper = new ReflectionHelper<int, int>(); + } + + public enum SampleEnum + { + X + } + + // Public to make the reflection simpler. + public static SampleEnum SampleEnumMethod() => SampleEnum.X; } -}
\ No newline at end of file +} diff --git a/docs/performance.md b/docs/performance.md new file mode 100644 index 00000000..6a5316c8 --- /dev/null +++ b/docs/performance.md @@ -0,0 +1,304 @@ +# Protobuf Perforamcne +This benchmark result is tested on workstation with processor of Intel® Xeon® Processor E5-2630 and 32GB RAM + +This table contains 3 languages' results: + +* **C++** - For C++ there're 3 kinds of parsing ways: + * **new** - This is for using new operator for creating message instance. + * **new arena** - This is for using arena for creating new message instance. + * **reuse** - This is for reusing the same message instance for parsing. +* **Java** - For Java there're 3 kinds of parsing/Serialization ways: + * **byte[]** - This is for parsing from a Byte Array. + * **ByteString** - This is for parsing from a + com.google.protobuf.ByteString. + * **InputStream** - This is for parsing from a InputStream +* **Python** - For Pythong there're 3 kinds of python protobuf for testing: + * **C++-genereated-code** - This is for using cpp generated code of the + proto file as dynamic linked library. + * **C++-reflection** - This is for using cpp reflection, which there's no + generated code, but still using cpp protobuf library as dynamic linked + library. + * **pure-Python** - This is for pure Python version, which don't link with + any cpp protobuf library. + +## Parsing performance + +<table> +<tbody><tr> +<th rowspan="2"> </th> +<th colspan="3" rowspan="1">C++</th> +<th colspan="3" rowspan="1">C++ with tcmalloc</th> +<th colspan="3" rowspan="1">java</th> +<th colspan="3" rowspan="1">python</th> +</tr> +<tr> +<th colspan="1">new</th> +<th colspan="1">new arena</th> +<th colspan="1">reuse</th> +<th colspan="1">new</th> +<th colspan="1">new arena</th> +<th colspan="1">reuse</th> +<th colspan="1">byte[]</th> +<th colspan="1">ByteString</th> +<th colspan="1">InputStream</th> +<th colspan="1">C++-generated-code</th> +<th colspan="1">C++-reflection</th> +<th colspan="1">pure-Python</th> +</tr> +<tr> +<td>google_message1_proto2</td> +<td>368.717MB/s</td> +<td>261.847MB/s</td> +<td>799.403MB/s</td> +<td>645.183MB/s</td> +<td>441.023MB/s</td> +<td>1.122GB/s</td> +<td>425.437MB/s</td> +<td>425.937MB/s</td> +<td>251.018MB/s</td> +<td>82.8314MB/s</td> +<td>47.6763MB/s</td> +<td>3.76299MB/s</td> +</tr> +<tr> +<td>google_message1_proto3</td> +<td>294.517MB/s</td> +<td>229.116MB/s</td> +<td>469.982MB/s</td> +<td>434.510MB/s</td> +<td>394.701MB/s</td> +<td>591.931MB/s</td> +<td>357.597MB/s</td> +<td>378.568MB/s</td> +<td>221.676MB/s</td> +<td>82.0498MB/s</td> +<td>39.9467MB/s</td> +<td>3.77751MB/s</td> +</tr> +<tr> +<td>google_message2</td> +<td>277.242MB/s</td> +<td>347.611MB/s</td> +<td>793.67MB/s</td> +<td>503.721MB/s</td> +<td>596.333MB/s</td> +<td>922.533MB/s</td> +<td>416.778MB/s</td> +<td>419.543MB/s</td> +<td>367.145MB/s</td> +<td>241.46MB/s</td> +<td>71.5723MB/s</td> +<td>2.73538MB/s</td> +</tr> +<tr> +<td>google_message3_1</td> +<td>213.478MB/s</td> +<td>291.58MB/s</td> +<td>543.398MB/s</td> +<td>539.704MB/s</td> +<td>717.300MB/s</td> +<td>927.333MB/s</td> +<td>684.241MB/s</td> +<td>704.47MB/s</td> +<td>648.624MB/s</td> +<td>209.036MB/s</td> +<td>142.356MB/s</td> +<td>15.3324MB/s</td> +</tr> +<tr> +<td>google_message3_2</td> +<td>672.685MB/s</td> +<td>802.767MB/s</td> +<td>1.21505GB/s</td> +<td>985.790MB/s</td> +<td>1.136GB/s</td> +<td>1.367GB/s</td> +<td>1.54439GB/s</td> +<td>1.60603GB/s</td> +<td>1.33443GB/s</td> +<td>573.835MB/s</td> +<td>314.33MB/s</td> +<td>15.0169MB/s</td> +</tr> +<tr> +<td>google_message3_3</td> +<td>207.681MB/s</td> +<td>140.591MB/s</td> +<td>535.181MB/s</td> +<td>369.743MB/s</td> +<td>262.301MB/s</td> +<td>556.644MB/s</td> +<td>279.385MB/s</td> +<td>304.853MB/s</td> +<td>107.575MB/s</td> +<td>32.248MB/s</td> +<td>26.1431MB/s</td> +<td>2.63541MB/s</td> +</tr> +<tr> +<td>google_message3_4</td> +<td>7.96091GB/s</td> +<td>7.10024GB/s</td> +<td>9.3013GB/s</td> +<td>8.518GB/s</td> +<td>8.171GB/s</td> +<td>9.917GB/s</td> +<td>5.78006GB/s</td> +<td>5.85198GB/s</td> +<td>4.62609GB/s</td> +<td>2.49631GB/s</td> +<td>2.35442GB/s</td> +<td>802.061MB/s</td> +</tr> +<tr> +<td>google_message3_5</td> +<td>76.0072MB/s</td> +<td>51.6769MB/s</td> +<td>237.856MB/s</td> +<td>178.495MB/s</td> +<td>111.751MB/s</td> +<td>329.569MB/s</td> +<td>121.038MB/s</td> +<td>132.866MB/s</td> +<td>36.9197MB/s</td> +<td>10.3962MB/s</td> +<td>8.84659MB/s</td> +<td>1.25203MB/s</td> +</tr> +<tr> +<td>google_message4</td> +<td>331.46MB/s</td> +<td>404.862MB/s</td> +<td>427.99MB/s</td> +<td>589.887MB/s</td> +<td>720.367MB/s</td> +<td>705.373MB/s</td> +<td>606.228MB/s</td> +<td>589.13MB/s</td> +<td>530.692MB/s</td> +<td>305.543MB/s</td> +<td>174.834MB/s</td> +<td>7.86485MB/s</td> +</tr> +</tbody></table> + +## Serialization performance + +<table> +<tbody><tr> +<th rowspan="2"> </th> +<th colspan="1" rowspan="2">C++</th> +<th colspan="1" rowspan="2">C++ with tcmalloc</th> +<th colspan="3" rowspan="1">java</th> +<th colspan="3" rowspan="1">python</th> +</tr> +<tr> +<th colspan="1">byte[]</th> +<th colspan="1">ByteString</th> +<th colspan="1">InputStream</th> +<th colspan="1">C++-generated-code</th> +<th colspan="1">C++-reflection</th> +<th colspan="1">pure-Python</th> +</tr> +<tr> +<td>google_message1_proto2</td> +<td>1.39698GB/s</td> +<td>1.701GB/s</td> +<td>1.12915GB/s</td> +<td>1.13589GB/s</td> +<td>758.609MB/s</td> +<td>260.911MB/s</td> +<td>58.4815MB/s</td> +<td>5.77824MB/s</td> +</tr> +<tr> +<td>google_message1_proto3</td> +<td>959.305MB/s</td> +<td>939.404MB/s</td> +<td>1.15372GB/s</td> +<td>1.07824GB/s</td> +<td>802.337MB/s</td> +<td>239.4MB/s</td> +<td>33.6336MB/s</td> +<td>5.80524MB/s</td> +</tr> +<tr> +<td>google_message2</td> +<td>1.27429GB/s</td> +<td>1.402GB/s</td> +<td>1.01039GB/s</td> +<td>1022.99MB/s</td> +<td>798.736MB/s</td> +<td>996.755MB/s</td> +<td>57.9601MB/s</td> +<td>4.09246MB/s</td> +</tr> +<tr> +<td>google_message3_1</td> +<td>1.31916GB/s</td> +<td>2.049GB/s</td> +<td>991.496MB/s</td> +<td>860.332MB/s</td> +<td>662.88MB/s</td> +<td>1.48625GB/s</td> +<td>421.287MB/s</td> +<td>18.002MB/s</td> +</tr> +<tr> +<td>google_message3_2</td> +<td>2.15676GB/s</td> +<td>2.632GB/s</td> +<td>2.14736GB/s</td> +<td>2.08136GB/s</td> +<td>1.55997GB/s</td> +<td>2.39597GB/s</td> +<td>326.777MB/s</td> +<td>16.0527MB/s</td> +</tr> +<tr> +<td>google_message3_3</td> +<td>650.456MB/s</td> +<td>1.040GB/s</td> +<td>593.52MB/s</td> +<td>580.667MB/s</td> +<td>346.839MB/s</td> +<td>123.978MB/s</td> +<td>35.893MB/s</td> +<td>2.32834MB/s</td> +</tr> +<tr> +<td>google_message3_4</td> +<td>8.70154GB/s</td> +<td>9.825GB/s</td> +<td>5.88645GB/s</td> +<td>5.93946GB/s</td> +<td>2.44388GB/s</td> +<td>5.9241GB/s</td> +<td>4.05837GB/s</td> +<td>876.87MB/s</td> +</tr> +<tr> +<td>google_message3_5</td> +<td>246.33MB/s</td> +<td>443.993MB/s</td> +<td>283.278MB/s</td> +<td>259.167MB/s</td> +<td>206.37MB/s</td> +<td>37.0285MB/s</td> +<td>12.2228MB/s</td> +<td>1.1979MB/s</td> +</tr> +<tr> +<td>google_message4</td> +<td>1.56674GB/s</td> +<td>2.19601GB/s</td> +<td>776.907MB/s</td> +<td>770.707MB/s</td> +<td>702.931MB/s</td> +<td>1.49623GB/s</td> +<td>205.116MB/s</td> +<td>8.93428MB/s</td> +</tr> +</tbody></table> + +\* The cpp performance can be improved by using [tcmalloc](https://gperftools.github.io/gperftools/tcmalloc.html), please follow the (instruction)[https://github.com/google/protobuf/blob/master/benchmarks/README.md] to link with tcmalloc to get the faster result. diff --git a/gmock.BUILD b/gmock.BUILD deleted file mode 100644 index b1ae15a9..00000000 --- a/gmock.BUILD +++ /dev/null @@ -1,28 +0,0 @@ -cc_library( - name = "gtest", - srcs = [ - "googletest/src/gtest-all.cc", - "googlemock/src/gmock-all.cc", - ], - hdrs = glob([ - "**/*.h", - "googletest/src/*.cc", - "googlemock/src/*.cc", - ]), - includes = [ - "googlemock", - "googletest", - "googletest/include", - "googlemock/include", - ], - linkopts = ["-pthread"], - visibility = ["//visibility:public"], -) - -cc_library( - name = "gtest_main", - srcs = ["googlemock/src/gmock_main.cc"], - linkopts = ["-pthread"], - visibility = ["//visibility:public"], - deps = [":gtest"], -) diff --git a/java/core/pom.xml b/java/core/pom.xml index 4b65e72e..8139241b 100644 --- a/java/core/pom.xml +++ b/java/core/pom.xml @@ -6,7 +6,7 @@ <parent> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-parent</artifactId> - <version>3.5.1</version> + <version>3.5.2</version> </parent> <artifactId>protobuf-java</artifactId> diff --git a/java/pom.xml b/java/pom.xml index b7c3e485..c42cae11 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -11,7 +11,7 @@ <groupId>com.google.protobuf</groupId> <artifactId>protobuf-parent</artifactId> - <version>3.5.1</version> + <version>3.5.2</version> <packaging>pom</packaging> <name>Protocol Buffers [Parent]</name> diff --git a/java/util/pom.xml b/java/util/pom.xml index 3de624fa..4e55df0d 100644 --- a/java/util/pom.xml +++ b/java/util/pom.xml @@ -6,7 +6,7 @@ <parent> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-parent</artifactId> - <version>3.5.1</version> + <version>3.5.2</version> </parent> <artifactId>protobuf-java-util</artifactId> diff --git a/javanano/README.md b/javanano/README.md deleted file mode 100644 index 6b13ecea..00000000 --- a/javanano/README.md +++ /dev/null @@ -1,401 +0,0 @@ -Protocol Buffers - Google's data interchange format -=================================================== - -[![Build Status](https://travis-ci.org/google/protobuf.svg?branch=master)](https://travis-ci.org/google/protobuf) - -Copyright 2008 Google Inc. - -This directory contains the Java Protocol Buffers Nano runtime library. - -**Nano is no longer supported by protobuf team. We recommend Android users to -use protobuf lite runtime instead.** - -Installation - With Maven -------------------------- - -The Protocol Buffers build is managed using Maven. If you would -rather build without Maven, see below. - -1) Install Apache Maven if you don't have it: - - http://maven.apache.org/ - -2) Build the C++ code, or obtain a binary distribution of protoc. If - you install a binary distribution, make sure that it is the same - version as this package. If in doubt, run: - - $ protoc --version - - You will need to place the protoc executable in ../src. (If you - built it yourself, it should already be there.) - -3) Run the tests: - - $ mvn test - - If some tests fail, this library may not work correctly on your - system. Continue at your own risk. - -4) Install the library into your Maven repository: - - $ mvn install - -5) If you do not use Maven to manage your own build, you can build a - .jar file to use: - - $ mvn package - - The .jar will be placed in the "target" directory. - -Installation - Without Maven ----------------------------- - -If you would rather not install Maven to build the library, you may -follow these instructions instead. Note that these instructions skip -running unit tests. - -1) Build the C++ code, or obtain a binary distribution of protoc. If - you install a binary distribution, make sure that it is the same - version as this package. If in doubt, run: - - $ protoc --version - - If you built the C++ code without installing, the compiler binary - should be located in ../src. - -2) Invoke protoc to build DescriptorProtos.java: - - $ protoc --java_out=src/main/java -I../src \ - ../src/google/protobuf/descriptor.proto - -3) Compile the code in src/main/java using whatever means you prefer. - -4) Install the classes wherever you prefer. - -Nano version ------------- - -JavaNano is a special code generator and runtime library designed specially for -resource-restricted systems, like Android. It is very resource-friendly in both -the amount of code and the runtime overhead. Here is an overview of JavaNano -features compared with the official Java protobuf: - -- No descriptors or message builders. -- All messages are mutable; fields are public Java fields. -- For optional fields only, encapsulation behind setter/getter/hazzer/ - clearer functions is opt-in, which provide proper 'has' state support. -- For proto2, if not opted in, has state (field presence) is not available. - Serialization outputs all fields not equal to their defaults - (see important implications below). - The behavior is consistent with proto3 semantics. -- Required fields (proto2 only) are always serialized. -- Enum constants are integers; protection against invalid values only - when parsing from the wire. -- Enum constants can be generated into container interfaces bearing - the enum's name (so the referencing code is in Java style). -- CodedInputByteBufferNano can only take byte[] (not InputStream). -- Similarly CodedOutputByteBufferNano can only write to byte[]. -- Repeated fields are in arrays, not ArrayList or Vector. Null array - elements are allowed and silently ignored. -- Full support for serializing/deserializing repeated packed fields. -- Support extensions (in proto2). -- Unset messages/groups are null, not an immutable empty default - instance. -- toByteArray(...) and mergeFrom(...) are now static functions of - MessageNano. -- The 'bytes' type translates to the Java type byte[]. - -The generated messages are not thread-safe for writes, but may be -used simultaneously from multiple threads in a read-only manner. -In other words, an appropriate synchronization mechanism (such as -a ReadWriteLock) must be used to ensure that a message, its -ancestors, and descendants are not accessed by any other threads -while the message is being modified. Field reads, getter methods -(but not getExtension(...)), toByteArray(...), writeTo(...), -getCachedSize(), and getSerializedSize() are all considered read-only -operations. - -IMPORTANT: If you have fields with defaults and opt out of accessors - -How fields with defaults are serialized has changed. Because we don't -keep "has" state, any field equal to its default is assumed to be not -set and therefore is not serialized. Consider the situation where we -change the default value of a field. Senders compiled against an older -version of the proto continue to match against the old default, and -don't send values to the receiver even though the receiver assumes the -new default value. Therefore, think carefully about the implications -of changing the default value. Alternatively, turn on accessors and -enjoy the benefit of the explicit has() checks. - -IMPORTANT: If you have "bytes" fields with non-empty defaults - -Because the byte buffer is now of mutable type byte[], the default -static final cannot be exposed through a public field. Each time a -message's constructor or clear() function is called, the default value -(kept in a private byte[]) is cloned. This causes a small memory -penalty. This is not a problem if the field has no default or is an -empty default. - -Nano Generator options ----------------------- - -``` -java_package -> <file-name>|<package-name> -java_outer_classname -> <file-name>|<package-name> -java_multiple_files -> true or false -java_nano_generate_has -> true or false [DEPRECATED] -optional_field_style -> default or accessors -enum_style -> c or java -ignore_services -> true or false -parcelable_messages -> true or false -generate_intdefs -> true or false -``` - -**java_package=\<file-name\>|\<package-name\>** (no default) - - This allows overriding the 'java_package' option value - for the given file from the command line. Use multiple - java_package options to override the option for multiple - files. The final Java package for each file is the value - of this command line option if present, or the value of - the same option defined in the file if present, or the - proto package if present, or the default Java package. - -**java_outer_classname=\<file-name\>|\<outer-classname\>** (no default) - - This allows overriding the 'java_outer_classname' option - for the given file from the command line. Use multiple - java_outer_classname options to override the option for - multiple files. The final Java outer class name for each - file is the value of this command line option if present, - or the value of the same option defined in the file if - present, or the file name converted to CamelCase. This - outer class will nest all classes and integer constants - generated from file-scope messages and enums. - -**java_multiple_files={true,false}** (no default) - - This allows overriding the 'java_multiple_files' option - in all source files and their imported files from the - command line. The final value of this option for each - file is the value defined in this command line option, or - the value of the same option defined in the file if - present, or false. This specifies whether to generate - package-level classes for the file-scope messages in the - same Java package as the outer class (instead of nested - classes in the outer class). File-scope enum constants - are still generated as integer constants in the outer - class. This affects the fully qualified references in the - Java code. NOTE: because the command line option - overrides the value for all files and their imported - files, using this option inconsistently may result in - incorrect references to the imported messages and enum - constants. - -**java_nano_generate_has={true,false}** (default: false) - - DEPRECATED. Use optional_field_style=accessors. - - If true, generates a public boolean variable has\<fieldname\> - accompanying each optional or required field (not present for - repeated fields, groups or messages). It is set to false initially - and upon clear(). If parseFrom(...) reads the field from the wire, - it is set to true. This is a way for clients to inspect the "has" - value upon parse. If it is set to true, writeTo(...) will ALWAYS - output that field (even if field value is equal to its - default). - - IMPORTANT: This option costs an extra 4 bytes per primitive field in - the message. Think carefully about whether you really need this. In - many cases reading the default works and determining whether the - field was received over the wire is irrelevant. - -**optional_field_style={default,accessors,reftypes}** (default: default) - - Defines the style of the generated code for fields. - - * default - - In the default style, optional fields translate into public mutable - Java fields, and the serialization process is as discussed in the - "IMPORTANT" section above. - - * accessors - - When set to 'accessors', each optional field is encapsulated behind - 4 accessors, namely get\<fieldname\>(), set\<fieldname\>(), has\<fieldname\>() - and clear\<fieldname\>() methods, with the standard semantics. The hazzer's - return value determines whether a field is serialized, so this style is - useful when you need to serialize a field with the default value, or check - if a field has been explicitly set to its default value from the wire. - - In the 'accessors' style, required and nested message fields are still - translated to one public mutable Java field each, repeated fields are still - translated to arrays. No accessors are generated for them. - - IMPORTANT: When using the 'accessors' style, ProGuard should always - be enabled with optimization (don't use -dontoptimize) and allowing - access modification (use -allowaccessmodification). This removes the - unused accessors and maybe inline the rest at the call sites, - reducing the final code size. - TODO(maxtroy): find ProGuard config that would work the best. - - * reftypes - - When set to 'reftypes', each proto field is generated as a public Java - field. For primitive types, these fields use the Java reference types - such as java.lang.Integer instead of primitive types such as int. - - In the 'reftypes' style, fields are initialized to null (or empty - arrays for repeated fields), and their default values are not available. - They are serialized over the wire based on equality to null. - - The 'reftypes' mode has some additional cost due to autoboxing and usage - of reference types. In practice, many boxed types are cached, and so don't - result in object creation. However, references do take slightly more memory - than primitives. - - The 'reftypes' mode is useful when you want to be able to serialize fields - with default values, or check if a field has been explicitly set to the - default over the wire without paying the extra method cost of the - 'accessors' mode. - - Note that if you attempt to write null to a required field in the reftypes - mode, serialization of the proto will cause a NullPointerException. This is - an intentional indicator that you must set required fields. - - NOTE - optional_field_style=accessors or reftypes cannot be used together with - java_nano_generate_has=true. If you need the 'has' flag for any - required field (you have no reason to), you can only use - java_nano_generate_has=true. - -**enum_style={c,java}** (default: c) - - Defines where to put the int constants generated from enum members. - - * c - - Use C-style, so the enum constants are available at the scope where - the enum is defined. A file-scope enum's members are referenced like - 'FileOuterClass.ENUM_VALUE'; a message-scope enum's members are - referenced as 'Message.ENUM_VALUE'. The enum name is unavailable. - This complies with the Micro code generator's behavior. - - * java - - Use Java-style, so the enum constants are available under the enum - name and referenced like 'EnumName.ENUM_VALUE' (they are still int - constants). The enum name becomes the name of a public interface, at - the scope where the enum is defined. If the enum is file-scope and - the java_multiple_files option is on, the interface will be defined - in its own file. To reduce code size, this interface should not be - implemented and ProGuard shrinking should be used, so after the Java - compiler inlines all referenced enum constants into the call sites, - the interface remains unused and can be removed by ProGuard. - -**ignore_services={true,false}** (default: false) - - Skips services definitions. - - Nano doesn't support services. By default, if a service is defined - it will generate a compilation error. If this flag is set to true, - services will be silently ignored, instead. - -**parcelable_messages={true,false}** (default: false) - - Android-specific option to generate Parcelable messages. - -**generate_intdefs={true,false}** (default: false) - Android-specific option to generate @IntDef annotations for enums. - - If turned on, an '@IntDef' annotation (a public @interface) will be - generated for each enum, and every integer parameter and return - value in the generated code meant for this enum will be annotated - with it. This interface is generated with the same name and at the - same place as the enum members' container interfaces described - above under 'enum_style=java', regardless of the enum_style option - used. When this is combined with enum_style=java, the interface - will be both the '@IntDef' annotation and the container of the enum - members; otherwise the interface has an empty body. - - Your app must declare a compile-time dependency on the - android-support-annotations library. - - For more information on how these @IntDef annotations help with - compile-time type safety, see: - https://sites.google.com/a/android.com/tools/tech-docs/support-annotations - and - https://developer.android.com/reference/android/support/annotation/IntDef.html - - -To use nano protobufs within the Android repo: ----------------------------------------------- - -- Set 'LOCAL_PROTOC_OPTIMIZE_TYPE := nano' in your local .mk file. - When building a Java library or an app (package) target, the build - system will add the Java nano runtime library to the - LOCAL_STATIC_JAVA_LIBRARIES variable, so you don't need to. -- Set 'LOCAL_PROTO_JAVA_OUTPUT_PARAMS := ...' in your local .mk file - for any command-line options you need. Use commas to join multiple - options. In the nano flavor only, whitespace surrounding the option - names and values are ignored, so you can use backslash-newline or - '+=' to structure your make files nicely. -- The options will be applied to *all* proto files in LOCAL_SRC_FILES - when you build a Java library or package. In case different options - are needed for different proto files, build separate Java libraries - and reference them in your main target. Note: you should make sure - that, for each separate target, all proto files imported from any - proto file in LOCAL_SRC_FILES are included in LOCAL_SRC_FILES. This - is because the generator has to assume that the imported files are - built using the same options, and will generate code that reference - the fields and enums from the imported files using the same code - style. -- Hint: 'include $(CLEAR_VARS)' resets all LOCAL_ variables, including - the two above. - -To use nano protobufs outside of Android repo: ----------------------------------------------- - -- Link with the generated jar file - \<protobuf-root\>java/target/protobuf-java-2.3.0-nano.jar. -- Invoke with --javanano_out, e.g.: -``` -./protoc '--javanano_out=\ - java_package=src/proto/simple-data.proto|my_package,\ - java_outer_classname=src/proto/simple-data.proto|OuterName\ - :.' src/proto/simple-data.proto -``` - -Contributing to nano: ---------------------- - -Please add/edit tests in NanoTest.java. - -Please run the following steps to test: - -- cd external/protobuf -- ./configure -- Run "make -j12 check" and verify all tests pass. -- cd java -- Run "mvn test" and verify all tests pass. -- cd ../../.. -- . build/envsetup.sh -- lunch 1 -- "make -j12 aprotoc libprotobuf-java-2.3.0-nano aprotoc-test-nano-params NanoAndroidTest" and - check for build errors. -- Plug in an Android device or start an emulator. -- adb install -r out/target/product/generic/data/app/NanoAndroidTest.apk -- Run: - "adb shell am instrument -w com.google.protobuf.nano.test/android.test.InstrumentationTestRunner" - and verify all tests pass. -- repo sync -c -j256 -- "make -j12" and check for build errors - -Usage ------ - -The complete documentation for Protocol Buffers is available via the -web at: - - https://developers.google.com/protocol-buffers/ diff --git a/javanano/pom.xml b/javanano/pom.xml deleted file mode 100644 index 0395e8f2..00000000 --- a/javanano/pom.xml +++ /dev/null @@ -1,244 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - <parent> - <groupId>com.google</groupId> - <artifactId>google</artifactId> - <version>1</version> - </parent> - <groupId>com.google.protobuf.nano</groupId> - <artifactId>protobuf-javanano</artifactId> - <version>3.2.0</version> - <packaging>bundle</packaging> - <name>Protocol Buffer JavaNano API</name> - <description> - Protocol Buffers are a way of encoding structured data in an efficient yet - extensible format. - </description> - <inceptionYear>2008</inceptionYear> - <url>https://developers.google.com/protocol-buffers/</url> - <licenses> - <license> - <name>3-Clause BSD License</name> - <url>https://opensource.org/licenses/BSD-3-Clause</url> - <distribution>repo</distribution> - </license> - </licenses> - <scm> - <url>https://github.com/google/protobuf</url> - <connection> - scm:git:https://github.com/google/protobuf.git - </connection> - </scm> - <properties> - <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - </properties> - <dependencies> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <version>4.4</version> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.easymock</groupId> - <artifactId>easymock</artifactId> - <version>2.2</version> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.easymock</groupId> - <artifactId>easymockclassextension</artifactId> - <version>2.2.1</version> - <scope>test</scope> - </dependency> - </dependencies> - <build> - <plugins> - <plugin> - <artifactId>maven-compiler-plugin</artifactId> - <configuration> - <source>1.5</source> - <target>1.5</target> - </configuration> - </plugin> - <plugin> - <artifactId>maven-surefire-plugin</artifactId> - <configuration> - <includes> - <include>**/*Test.java</include> - </includes> - </configuration> - </plugin> - <plugin> - <artifactId>maven-antrun-plugin</artifactId> - <executions> - <execution> - <id>generate-test-sources</id> - <phase>generate-test-sources</phase> - <configuration> - <tasks> - <mkdir dir="target/generated-test-sources" /> - <exec executable="../src/protoc"> - <arg value="--javanano_out=generate_equals=true:target/generated-test-sources" /> - <arg value="--proto_path=src/test/java/com" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_nano.proto" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_simple_nano.proto" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_stringutf8_nano.proto" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_recursive_nano.proto" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_import_nano.proto" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_single_nano.proto" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_multiple_nano.proto" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_multiple_nameclash_nano.proto" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_enum_class_nano.proto" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_repeated_merge_nano.proto" /> - <arg value="src/test/java/com/google/protobuf/nano/map_test.proto" /> - </exec> - <exec executable="../src/protoc"> - <arg value="--javanano_out=store_unknown_fields=true,generate_equals=true,generate_clone=true:target/generated-test-sources" /> - <arg value="--proto_path=src/test/java/com" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_extension_nano.proto" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_extension_singular_nano.proto" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_extension_repeated_nano.proto" /> - </exec> - <exec executable="../src/protoc"> - <arg value="--javanano_out=store_unknown_fields=true,generate_clone=true:target/generated-test-sources" /> - <arg value="--proto_path=src/test/java/com" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_extension_packed_nano.proto" /> - </exec> - <exec executable="../src/protoc"> - <arg value="--javanano_out=java_nano_generate_has=true,generate_equals=true,generate_clone=true:target/generated-test-sources" /> - <arg value="--proto_path=src/test/java/com" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_has_nano.proto" /> - </exec> - <exec executable="../src/protoc"> - <arg value="--javanano_out=optional_field_style=accessors,generate_equals=true:target/generated-test-sources" /> - <arg value="--proto_path=src/test/java/com" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_accessors_nano.proto" /> - </exec> - <exec executable="../src/protoc"> - <arg value="--javanano_out=enum_style=java:target/generated-test-sources" /> - <arg value="--proto_path=src/test/java/com" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_enum_class_nano.proto" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_enum_class_multiple_nano.proto" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_repeated_packables_nano.proto" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_enum_validity_nano.proto" /> - </exec> - <exec executable="../src/protoc"> - <arg value="--javanano_out= - optional_field_style=accessors, - java_outer_classname=google/protobuf/nano/unittest_enum_validity_nano.proto|EnumValidityAccessors - :target/generated-test-sources" /> - <arg value="--proto_path=src/test/java/com" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_enum_validity_nano.proto" /> - </exec> - <exec executable="../src/protoc"> - <arg value="--javanano_out=optional_field_style=reftypes,generate_equals=true:target/generated-test-sources" /> - <arg value="--proto_path=src/test/java/com" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_reference_types_nano.proto" /> - </exec> - <exec executable="../src/protoc"> - <arg value="--javanano_out= - optional_field_style=reftypes_compat_mode, - generate_equals=true, - java_outer_classname=google/protobuf/nano/unittest_reference_types_nano.proto|NanoReferenceTypesCompat - :target/generated-test-sources" /> - <arg value="--proto_path=src/test/java/com" /> - <arg value="src/test/java/com/google/protobuf/nano/unittest_reference_types_nano.proto" /> - </exec> - </tasks> - <testSourceRoot>target/generated-test-sources</testSourceRoot> - </configuration> - <goals> - <goal>run</goal> - </goals> - </execution> - </executions> - </plugin> - <plugin> - <groupId>org.apache.felix</groupId> - <artifactId>maven-bundle-plugin</artifactId> - <extensions>true</extensions> - <configuration> - <instructions> - <Bundle-DocURL>https://developers.google.com/protocol-buffers/</Bundle-DocURL> - <Bundle-SymbolicName>com.google.protobuf.nano</Bundle-SymbolicName> - <Export-Package>com.google.protobuf.nano;version=3.0.0-alpha-7</Export-Package> - </instructions> - </configuration> - </plugin> - </plugins> - </build> - <profiles> - <profile> - <id>release</id> - <distributionManagement> - <snapshotRepository> - <id>sonatype-nexus-staging</id> - <url>https://oss.sonatype.org/content/repositories/snapshots</url> - </snapshotRepository> - <repository> - <id>sonatype-nexus-staging</id> - <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url> - </repository> - </distributionManagement> - <build> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-source-plugin</artifactId> - <version>2.2.1</version> - <executions> - <execution> - <id>attach-sources</id> - <goals> - <goal>jar-no-fork</goal> - </goals> - </execution> - </executions> - </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-javadoc-plugin</artifactId> - <version>2.9.1</version> - <executions> - <execution> - <id>attach-javadocs</id> - <goals> - <goal>jar</goal> - </goals> - </execution> - </executions> - </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-gpg-plugin</artifactId> - <version>1.5</version> - <executions> - <execution> - <id>sign-artifacts</id> - <phase>verify</phase> - <goals> - <goal>sign</goal> - </goals> - </execution> - </executions> - </plugin> - <plugin> - <groupId>org.sonatype.plugins</groupId> - <artifactId>nexus-staging-maven-plugin</artifactId> - <version>1.6.3</version> - <extensions>true</extensions> - <configuration> - <serverId>sonatype-nexus-staging</serverId> - <nexusUrl>https://oss.sonatype.org/</nexusUrl> - <autoReleaseAfterClose>false</autoReleaseAfterClose> - </configuration> - </plugin> - </plugins> - </build> - </profile> - </profiles> -</project> diff --git a/javanano/src/main/java/com/google/protobuf/nano/CodedInputByteBufferNano.java b/javanano/src/main/java/com/google/protobuf/nano/CodedInputByteBufferNano.java deleted file mode 100644 index f3993155..00000000 --- a/javanano/src/main/java/com/google/protobuf/nano/CodedInputByteBufferNano.java +++ /dev/null @@ -1,683 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2013 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.nano; - -import java.io.IOException; - -/** - * Reads and decodes protocol message fields. - * - * This class contains two kinds of methods: methods that read specific - * protocol message constructs and field types (e.g. {@link #readTag()} and - * {@link #readInt32()}) and methods that read low-level values (e.g. - * {@link #readRawVarint32()} and {@link #readRawBytes}). If you are reading - * encoded protocol messages, you should use the former methods, but if you are - * reading some other format of your own design, use the latter. - * - * @author kenton@google.com Kenton Varda - */ -public final class CodedInputByteBufferNano { - /** - * Create a new CodedInputStream wrapping the given byte array. - */ - public static CodedInputByteBufferNano newInstance(final byte[] buf) { - return newInstance(buf, 0, buf.length); - } - - /** - * Create a new CodedInputStream wrapping the given byte array slice. - */ - public static CodedInputByteBufferNano newInstance(final byte[] buf, final int off, - final int len) { - return new CodedInputByteBufferNano(buf, off, len); - } - - // ----------------------------------------------------------------- - - /** - * Attempt to read a field tag, returning zero if we have reached EOF. - * Protocol message parsers use this to read tags, since a protocol message - * may legally end wherever a tag occurs, and zero is not a valid tag number. - */ - public int readTag() throws IOException { - if (isAtEnd()) { - lastTag = 0; - return 0; - } - - lastTag = readRawVarint32(); - if (lastTag == 0) { - // If we actually read zero, that's not a valid tag. - throw InvalidProtocolBufferNanoException.invalidTag(); - } - return lastTag; - } - - /** - * Verifies that the last call to readTag() returned the given tag value. - * This is used to verify that a nested group ended with the correct - * end tag. - * - * @throws InvalidProtocolBufferNanoException {@code value} does not match the - * last tag. - */ - public void checkLastTagWas(final int value) - throws InvalidProtocolBufferNanoException { - if (lastTag != value) { - throw InvalidProtocolBufferNanoException.invalidEndTag(); - } - } - - /** - * Reads and discards a single field, given its tag value. - * - * @return {@code false} if the tag is an endgroup tag, in which case - * nothing is skipped. Otherwise, returns {@code true}. - */ - public boolean skipField(final int tag) throws IOException { - switch (WireFormatNano.getTagWireType(tag)) { - case WireFormatNano.WIRETYPE_VARINT: - readInt32(); - return true; - case WireFormatNano.WIRETYPE_FIXED64: - readRawLittleEndian64(); - return true; - case WireFormatNano.WIRETYPE_LENGTH_DELIMITED: - skipRawBytes(readRawVarint32()); - return true; - case WireFormatNano.WIRETYPE_START_GROUP: - skipMessage(); - checkLastTagWas( - WireFormatNano.makeTag(WireFormatNano.getTagFieldNumber(tag), - WireFormatNano.WIRETYPE_END_GROUP)); - return true; - case WireFormatNano.WIRETYPE_END_GROUP: - return false; - case WireFormatNano.WIRETYPE_FIXED32: - readRawLittleEndian32(); - return true; - default: - throw InvalidProtocolBufferNanoException.invalidWireType(); - } - } - - /** - * Reads and discards an entire message. This will read either until EOF - * or until an endgroup tag, whichever comes first. - */ - public void skipMessage() throws IOException { - while (true) { - final int tag = readTag(); - if (tag == 0 || !skipField(tag)) { - return; - } - } - } - - // ----------------------------------------------------------------- - - /** Read a {@code double} field value from the stream. */ - public double readDouble() throws IOException { - return Double.longBitsToDouble(readRawLittleEndian64()); - } - - /** Read a {@code float} field value from the stream. */ - public float readFloat() throws IOException { - return Float.intBitsToFloat(readRawLittleEndian32()); - } - - /** Read a {@code uint64} field value from the stream. */ - public long readUInt64() throws IOException { - return readRawVarint64(); - } - - /** Read an {@code int64} field value from the stream. */ - public long readInt64() throws IOException { - return readRawVarint64(); - } - - /** Read an {@code int32} field value from the stream. */ - public int readInt32() throws IOException { - return readRawVarint32(); - } - - /** Read a {@code fixed64} field value from the stream. */ - public long readFixed64() throws IOException { - return readRawLittleEndian64(); - } - - /** Read a {@code fixed32} field value from the stream. */ - public int readFixed32() throws IOException { - return readRawLittleEndian32(); - } - - /** Read a {@code bool} field value from the stream. */ - public boolean readBool() throws IOException { - return readRawVarint32() != 0; - } - - /** Read a {@code string} field value from the stream. */ - public String readString() throws IOException { - final int size = readRawVarint32(); - if (size <= (bufferSize - bufferPos) && size > 0) { - // Fast path: We already have the bytes in a contiguous buffer, so - // just copy directly from it. - final String result = new String(buffer, bufferPos, size, InternalNano.UTF_8); - bufferPos += size; - return result; - } else { - // Slow path: Build a byte array first then copy it. - return new String(readRawBytes(size), InternalNano.UTF_8); - } - } - - /** Read a {@code group} field value from the stream. */ - public void readGroup(final MessageNano msg, final int fieldNumber) - throws IOException { - if (recursionDepth >= recursionLimit) { - throw InvalidProtocolBufferNanoException.recursionLimitExceeded(); - } - ++recursionDepth; - msg.mergeFrom(this); - checkLastTagWas( - WireFormatNano.makeTag(fieldNumber, WireFormatNano.WIRETYPE_END_GROUP)); - --recursionDepth; - } - - public void readMessage(final MessageNano msg) - throws IOException { - final int length = readRawVarint32(); - if (recursionDepth >= recursionLimit) { - throw InvalidProtocolBufferNanoException.recursionLimitExceeded(); - } - final int oldLimit = pushLimit(length); - ++recursionDepth; - msg.mergeFrom(this); - checkLastTagWas(0); - --recursionDepth; - popLimit(oldLimit); - } - - /** Read a {@code bytes} field value from the stream. */ - public byte[] readBytes() throws IOException { - final int size = readRawVarint32(); - if (size <= (bufferSize - bufferPos) && size > 0) { - // Fast path: We already have the bytes in a contiguous buffer, so - // just copy directly from it. - final byte[] result = new byte[size]; - System.arraycopy(buffer, bufferPos, result, 0, size); - bufferPos += size; - return result; - } else if (size == 0) { - return WireFormatNano.EMPTY_BYTES; - } else { - // Slow path: Build a byte array first then copy it. - return readRawBytes(size); - } - } - - /** Read a {@code uint32} field value from the stream. */ - public int readUInt32() throws IOException { - return readRawVarint32(); - } - - /** - * Read an enum field value from the stream. Caller is responsible - * for converting the numeric value to an actual enum. - */ - public int readEnum() throws IOException { - return readRawVarint32(); - } - - /** Read an {@code sfixed32} field value from the stream. */ - public int readSFixed32() throws IOException { - return readRawLittleEndian32(); - } - - /** Read an {@code sfixed64} field value from the stream. */ - public long readSFixed64() throws IOException { - return readRawLittleEndian64(); - } - - /** Read an {@code sint32} field value from the stream. */ - public int readSInt32() throws IOException { - return decodeZigZag32(readRawVarint32()); - } - - /** Read an {@code sint64} field value from the stream. */ - public long readSInt64() throws IOException { - return decodeZigZag64(readRawVarint64()); - } - - // ================================================================= - - /** - * Read a raw Varint from the stream. If larger than 32 bits, discard the - * upper bits. - */ - public int readRawVarint32() throws IOException { - byte tmp = readRawByte(); - if (tmp >= 0) { - return tmp; - } - int result = tmp & 0x7f; - if ((tmp = readRawByte()) >= 0) { - result |= tmp << 7; - } else { - result |= (tmp & 0x7f) << 7; - if ((tmp = readRawByte()) >= 0) { - result |= tmp << 14; - } else { - result |= (tmp & 0x7f) << 14; - if ((tmp = readRawByte()) >= 0) { - result |= tmp << 21; - } else { - result |= (tmp & 0x7f) << 21; - result |= (tmp = readRawByte()) << 28; - if (tmp < 0) { - // Discard upper 32 bits. - for (int i = 0; i < 5; i++) { - if (readRawByte() >= 0) { - return result; - } - } - throw InvalidProtocolBufferNanoException.malformedVarint(); - } - } - } - } - return result; - } - - /** Read a raw Varint from the stream. */ - public long readRawVarint64() throws IOException { - int shift = 0; - long result = 0; - while (shift < 64) { - final byte b = readRawByte(); - result |= (long)(b & 0x7F) << shift; - if ((b & 0x80) == 0) { - return result; - } - shift += 7; - } - throw InvalidProtocolBufferNanoException.malformedVarint(); - } - - /** Read a 32-bit little-endian integer from the stream. */ - public int readRawLittleEndian32() throws IOException { - final byte b1 = readRawByte(); - final byte b2 = readRawByte(); - final byte b3 = readRawByte(); - final byte b4 = readRawByte(); - return ((b1 & 0xff) ) | - ((b2 & 0xff) << 8) | - ((b3 & 0xff) << 16) | - ((b4 & 0xff) << 24); - } - - /** Read a 64-bit little-endian integer from the stream. */ - public long readRawLittleEndian64() throws IOException { - final byte b1 = readRawByte(); - final byte b2 = readRawByte(); - final byte b3 = readRawByte(); - final byte b4 = readRawByte(); - final byte b5 = readRawByte(); - final byte b6 = readRawByte(); - final byte b7 = readRawByte(); - final byte b8 = readRawByte(); - return (((long)b1 & 0xff) ) | - (((long)b2 & 0xff) << 8) | - (((long)b3 & 0xff) << 16) | - (((long)b4 & 0xff) << 24) | - (((long)b5 & 0xff) << 32) | - (((long)b6 & 0xff) << 40) | - (((long)b7 & 0xff) << 48) | - (((long)b8 & 0xff) << 56); - } - - /** - * Decode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers - * into values that can be efficiently encoded with varint. (Otherwise, - * negative values must be sign-extended to 64 bits to be varint encoded, - * thus always taking 10 bytes on the wire.) - * - * @param n An unsigned 32-bit integer, stored in a signed int because - * Java has no explicit unsigned support. - * @return A signed 32-bit integer. - */ - public static int decodeZigZag32(final int n) { - return (n >>> 1) ^ -(n & 1); - } - - /** - * Decode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers - * into values that can be efficiently encoded with varint. (Otherwise, - * negative values must be sign-extended to 64 bits to be varint encoded, - * thus always taking 10 bytes on the wire.) - * - * @param n An unsigned 64-bit integer, stored in a signed int because - * Java has no explicit unsigned support. - * @return A signed 64-bit integer. - */ - public static long decodeZigZag64(final long n) { - return (n >>> 1) ^ -(n & 1); - } - - // ----------------------------------------------------------------- - - private final byte[] buffer; - private int bufferStart; - private int bufferSize; - private int bufferSizeAfterLimit; - private int bufferPos; - private int lastTag; - - /** The absolute position of the end of the current message. */ - private int currentLimit = Integer.MAX_VALUE; - - /** See setRecursionLimit() */ - private int recursionDepth; - private int recursionLimit = DEFAULT_RECURSION_LIMIT; - - /** See setSizeLimit() */ - private int sizeLimit = DEFAULT_SIZE_LIMIT; - - private static final int DEFAULT_RECURSION_LIMIT = 64; - private static final int DEFAULT_SIZE_LIMIT = 64 << 20; // 64MB - - private CodedInputByteBufferNano(final byte[] buffer, final int off, final int len) { - this.buffer = buffer; - bufferStart = off; - bufferSize = off + len; - bufferPos = off; - } - - /** - * Set the maximum message recursion depth. In order to prevent malicious - * messages from causing stack overflows, {@code CodedInputStream} limits - * how deeply messages may be nested. The default limit is 64. - * - * @return the old limit. - */ - public int setRecursionLimit(final int limit) { - if (limit < 0) { - throw new IllegalArgumentException( - "Recursion limit cannot be negative: " + limit); - } - final int oldLimit = recursionLimit; - recursionLimit = limit; - return oldLimit; - } - - /** - * Set the maximum message size. In order to prevent malicious - * messages from exhausting memory or causing integer overflows, - * {@code CodedInputStream} limits how large a message may be. - * The default limit is 64MB. You should set this limit as small - * as you can without harming your app's functionality. Note that - * size limits only apply when reading from an {@code InputStream}, not - * when constructed around a raw byte array. - * <p> - * If you want to read several messages from a single CodedInputStream, you - * could call {@link #resetSizeCounter()} after each one to avoid hitting the - * size limit. - * - * @return the old limit. - */ - public int setSizeLimit(final int limit) { - if (limit < 0) { - throw new IllegalArgumentException( - "Size limit cannot be negative: " + limit); - } - final int oldLimit = sizeLimit; - sizeLimit = limit; - return oldLimit; - } - - /** - * Resets the current size counter to zero (see {@link #setSizeLimit(int)}). - */ - public void resetSizeCounter() { - } - - /** - * Sets {@code currentLimit} to (current position) + {@code byteLimit}. This - * is called when descending into a length-delimited embedded message. - * - * @return the old limit. - */ - public int pushLimit(int byteLimit) throws InvalidProtocolBufferNanoException { - if (byteLimit < 0) { - throw InvalidProtocolBufferNanoException.negativeSize(); - } - byteLimit += bufferPos; - final int oldLimit = currentLimit; - if (byteLimit > oldLimit) { - throw InvalidProtocolBufferNanoException.truncatedMessage(); - } - currentLimit = byteLimit; - - recomputeBufferSizeAfterLimit(); - - return oldLimit; - } - - private void recomputeBufferSizeAfterLimit() { - bufferSize += bufferSizeAfterLimit; - final int bufferEnd = bufferSize; - if (bufferEnd > currentLimit) { - // Limit is in current buffer. - bufferSizeAfterLimit = bufferEnd - currentLimit; - bufferSize -= bufferSizeAfterLimit; - } else { - bufferSizeAfterLimit = 0; - } - } - - /** - * Discards the current limit, returning to the previous limit. - * - * @param oldLimit The old limit, as returned by {@code pushLimit}. - */ - public void popLimit(final int oldLimit) { - currentLimit = oldLimit; - recomputeBufferSizeAfterLimit(); - } - - /** - * Returns the number of bytes to be read before the current limit. - * If no limit is set, returns -1. - */ - public int getBytesUntilLimit() { - if (currentLimit == Integer.MAX_VALUE) { - return -1; - } - - final int currentAbsolutePosition = bufferPos; - return currentLimit - currentAbsolutePosition; - } - - /** - * 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 - * if the stream has reached a limit created using {@link #pushLimit(int)}. - */ - public boolean isAtEnd() { - return bufferPos == bufferSize; - } - - /** - * Get current position in buffer relative to beginning offset. - */ - public int getPosition() { - return bufferPos - bufferStart; - } - - /** - * Retrieves a subset of data in the buffer. The returned array is not backed by the original - * buffer array. - * - * @param offset the position (relative to the buffer start position) to start at. - * @param length the number of bytes to retrieve. - */ - public byte[] getData(int offset, int length) { - if (length == 0) { - return WireFormatNano.EMPTY_BYTES; - } - byte[] copy = new byte[length]; - int start = bufferStart + offset; - System.arraycopy(buffer, start, copy, 0, length); - return copy; - } - - /** - * Rewind to previous position. Cannot go forward. - */ - public void rewindToPosition(int position) { - if (position > bufferPos - bufferStart) { - throw new IllegalArgumentException( - "Position " + position + " is beyond current " + (bufferPos - bufferStart)); - } - if (position < 0) { - throw new IllegalArgumentException("Bad position " + position); - } - bufferPos = bufferStart + position; - } - - /** - * Read one byte from the input. - * - * @throws InvalidProtocolBufferNanoException The end of the stream or the current - * limit was reached. - */ - public byte readRawByte() throws IOException { - if (bufferPos == bufferSize) { - throw InvalidProtocolBufferNanoException.truncatedMessage(); - } - return buffer[bufferPos++]; - } - - /** - * Read a fixed size of bytes from the input. - * - * @throws InvalidProtocolBufferNanoException The end of the stream or the current - * limit was reached. - */ - public byte[] readRawBytes(final int size) throws IOException { - if (size < 0) { - throw InvalidProtocolBufferNanoException.negativeSize(); - } - - if (bufferPos + size > currentLimit) { - // Read to the end of the stream anyway. - skipRawBytes(currentLimit - bufferPos); - // Then fail. - throw InvalidProtocolBufferNanoException.truncatedMessage(); - } - - if (size <= bufferSize - bufferPos) { - // We have all the bytes we need already. - final byte[] bytes = new byte[size]; - System.arraycopy(buffer, bufferPos, bytes, 0, size); - bufferPos += size; - return bytes; - } else { - throw InvalidProtocolBufferNanoException.truncatedMessage(); - } - } - - /** - * Reads and discards {@code size} bytes. - * - * @throws InvalidProtocolBufferNanoException The end of the stream or the current - * limit was reached. - */ - public void skipRawBytes(final int size) throws IOException { - if (size < 0) { - throw InvalidProtocolBufferNanoException.negativeSize(); - } - - if (bufferPos + size > currentLimit) { - // Read to the end of the stream anyway. - skipRawBytes(currentLimit - bufferPos); - // Then fail. - throw InvalidProtocolBufferNanoException.truncatedMessage(); - } - - if (size <= bufferSize - bufferPos) { - // We have all the bytes we need already. - bufferPos += size; - } else { - throw InvalidProtocolBufferNanoException.truncatedMessage(); - } - } - - // Read a primitive type. - Object readPrimitiveField(int type) throws IOException { - switch (type) { - case InternalNano.TYPE_DOUBLE: - return readDouble(); - case InternalNano.TYPE_FLOAT: - return readFloat(); - case InternalNano.TYPE_INT64: - return readInt64(); - case InternalNano.TYPE_UINT64: - return readUInt64(); - case InternalNano.TYPE_INT32: - return readInt32(); - case InternalNano.TYPE_FIXED64: - return readFixed64(); - case InternalNano.TYPE_FIXED32: - return readFixed32(); - case InternalNano.TYPE_BOOL: - return readBool(); - case InternalNano.TYPE_STRING: - return readString(); - case InternalNano.TYPE_BYTES: - return readBytes(); - case InternalNano.TYPE_UINT32: - return readUInt32(); - case InternalNano.TYPE_ENUM: - return readEnum(); - case InternalNano.TYPE_SFIXED32: - return readSFixed32(); - case InternalNano.TYPE_SFIXED64: - return readSFixed64(); - case InternalNano.TYPE_SINT32: - return readSInt32(); - case InternalNano.TYPE_SINT64: - return readSInt64(); - default: - throw new IllegalArgumentException("Unknown type " + type); - } - } -} diff --git a/javanano/src/main/java/com/google/protobuf/nano/CodedOutputByteBufferNano.java b/javanano/src/main/java/com/google/protobuf/nano/CodedOutputByteBufferNano.java deleted file mode 100644 index 322ada8e..00000000 --- a/javanano/src/main/java/com/google/protobuf/nano/CodedOutputByteBufferNano.java +++ /dev/null @@ -1,1214 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2013 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.nano; - -import java.io.IOException; -import java.nio.BufferOverflowException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.ReadOnlyBufferException; - -/** - * Encodes and writes protocol message fields. - * - * <p>This class contains two kinds of methods: methods that write specific - * protocol message constructs and field types (e.g. {@link #writeTag} and - * {@link #writeInt32}) and methods that write low-level values (e.g. - * {@link #writeRawVarint32} and {@link #writeRawBytes}). If you are - * writing encoded protocol messages, you should use the former methods, but if - * you are writing some other format of your own design, use the latter. - * - * <p>This class is totally unsynchronized. - * - * @author kneton@google.com Kenton Varda - */ -public final class CodedOutputByteBufferNano { - /* max bytes per java UTF-16 char in UTF-8 */ - private static final int MAX_UTF8_EXPANSION = 3; - private final ByteBuffer buffer; - - private CodedOutputByteBufferNano(final byte[] buffer, final int offset, - final int length) { - this(ByteBuffer.wrap(buffer, offset, length)); - } - - private CodedOutputByteBufferNano(final ByteBuffer buffer) { - this.buffer = buffer; - this.buffer.order(ByteOrder.LITTLE_ENDIAN); - } - - /** - * Create a new {@code CodedOutputStream} that writes directly to the given - * byte array. If more bytes are written than fit in the array, - * {@link OutOfSpaceException} will be thrown. Writing directly to a flat - * array is faster than writing to an {@code OutputStream}. - */ - public static CodedOutputByteBufferNano newInstance(final byte[] flatArray) { - return newInstance(flatArray, 0, flatArray.length); - } - - /** - * Create a new {@code CodedOutputStream} that writes directly to the given - * byte array slice. If more bytes are written than fit in the slice, - * {@link OutOfSpaceException} will be thrown. Writing directly to a flat - * array is faster than writing to an {@code OutputStream}. - */ - public static CodedOutputByteBufferNano newInstance(final byte[] flatArray, - final int offset, - final int length) { - return new CodedOutputByteBufferNano(flatArray, offset, length); - } - - // ----------------------------------------------------------------- - - /** Write a {@code double} field, including tag, to the stream. */ - public void writeDouble(final int fieldNumber, final double value) - throws IOException { - writeTag(fieldNumber, WireFormatNano.WIRETYPE_FIXED64); - writeDoubleNoTag(value); - } - - /** Write a {@code float} field, including tag, to the stream. */ - public void writeFloat(final int fieldNumber, final float value) - throws IOException { - writeTag(fieldNumber, WireFormatNano.WIRETYPE_FIXED32); - writeFloatNoTag(value); - } - - /** Write a {@code uint64} field, including tag, to the stream. */ - public void writeUInt64(final int fieldNumber, final long value) - throws IOException { - writeTag(fieldNumber, WireFormatNano.WIRETYPE_VARINT); - writeUInt64NoTag(value); - } - - /** Write an {@code int64} field, including tag, to the stream. */ - public void writeInt64(final int fieldNumber, final long value) - throws IOException { - writeTag(fieldNumber, WireFormatNano.WIRETYPE_VARINT); - writeInt64NoTag(value); - } - - /** Write an {@code int32} field, including tag, to the stream. */ - public void writeInt32(final int fieldNumber, final int value) - throws IOException { - writeTag(fieldNumber, WireFormatNano.WIRETYPE_VARINT); - writeInt32NoTag(value); - } - - /** Write a {@code fixed64} field, including tag, to the stream. */ - public void writeFixed64(final int fieldNumber, final long value) - throws IOException { - writeTag(fieldNumber, WireFormatNano.WIRETYPE_FIXED64); - writeFixed64NoTag(value); - } - - /** Write a {@code fixed32} field, including tag, to the stream. */ - public void writeFixed32(final int fieldNumber, final int value) - throws IOException { - writeTag(fieldNumber, WireFormatNano.WIRETYPE_FIXED32); - writeFixed32NoTag(value); - } - - /** Write a {@code bool} field, including tag, to the stream. */ - public void writeBool(final int fieldNumber, final boolean value) - throws IOException { - writeTag(fieldNumber, WireFormatNano.WIRETYPE_VARINT); - writeBoolNoTag(value); - } - - /** Write a {@code string} field, including tag, to the stream. */ - public void writeString(final int fieldNumber, final String value) - throws IOException { - writeTag(fieldNumber, WireFormatNano.WIRETYPE_LENGTH_DELIMITED); - writeStringNoTag(value); - } - - /** Write a {@code group} field, including tag, to the stream. */ - public void writeGroup(final int fieldNumber, final MessageNano value) - throws IOException { - writeTag(fieldNumber, WireFormatNano.WIRETYPE_START_GROUP); - writeGroupNoTag(value); - writeTag(fieldNumber, WireFormatNano.WIRETYPE_END_GROUP); - } - - /** Write an embedded message field, including tag, to the stream. */ - public void writeMessage(final int fieldNumber, final MessageNano value) - throws IOException { - writeTag(fieldNumber, WireFormatNano.WIRETYPE_LENGTH_DELIMITED); - writeMessageNoTag(value); - } - - /** Write a {@code bytes} field, including tag, to the stream. */ - public void writeBytes(final int fieldNumber, final byte[] value) - throws IOException { - writeTag(fieldNumber, WireFormatNano.WIRETYPE_LENGTH_DELIMITED); - writeBytesNoTag(value); - } - - /** Write a {@code uint32} field, including tag, to the stream. */ - public void writeUInt32(final int fieldNumber, final int value) - throws IOException { - writeTag(fieldNumber, WireFormatNano.WIRETYPE_VARINT); - writeUInt32NoTag(value); - } - - /** - * Write an enum field, including tag, to the stream. Caller is responsible - * for converting the enum value to its numeric value. - */ - public void writeEnum(final int fieldNumber, final int value) - throws IOException { - writeTag(fieldNumber, WireFormatNano.WIRETYPE_VARINT); - writeEnumNoTag(value); - } - - /** Write an {@code sfixed32} field, including tag, to the stream. */ - public void writeSFixed32(final int fieldNumber, final int value) - throws IOException { - writeTag(fieldNumber, WireFormatNano.WIRETYPE_FIXED32); - writeSFixed32NoTag(value); - } - - /** Write an {@code sfixed64} field, including tag, to the stream. */ - public void writeSFixed64(final int fieldNumber, final long value) - throws IOException { - writeTag(fieldNumber, WireFormatNano.WIRETYPE_FIXED64); - writeSFixed64NoTag(value); - } - - /** Write an {@code sint32} field, including tag, to the stream. */ - public void writeSInt32(final int fieldNumber, final int value) - throws IOException { - writeTag(fieldNumber, WireFormatNano.WIRETYPE_VARINT); - writeSInt32NoTag(value); - } - - /** Write an {@code sint64} field, including tag, to the stream. */ - public void writeSInt64(final int fieldNumber, final long value) - throws IOException { - writeTag(fieldNumber, WireFormatNano.WIRETYPE_VARINT); - writeSInt64NoTag(value); - } - - /** - * Write a MessageSet extension field to the stream. For historical reasons, - * the wire format differs from normal fields. - */ -// public void writeMessageSetExtension(final int fieldNumber, -// final MessageMicro value) -// throws IOException { -// writeTag(WireFormatMicro.MESSAGE_SET_ITEM, WireFormatMicro.WIRETYPE_START_GROUP); -// writeUInt32(WireFormatMicro.MESSAGE_SET_TYPE_ID, fieldNumber); -// writeMessage(WireFormatMicro.MESSAGE_SET_MESSAGE, value); -// writeTag(WireFormatMicro.MESSAGE_SET_ITEM, WireFormatMicro.WIRETYPE_END_GROUP); -// } - - /** - * Write an unparsed MessageSet extension field to the stream. For - * historical reasons, the wire format differs from normal fields. - */ -// public void writeRawMessageSetExtension(final int fieldNumber, -// final ByteStringMicro value) -// throws IOException { -// writeTag(WireFormatMicro.MESSAGE_SET_ITEM, WireFormatMicro.WIRETYPE_START_GROUP); -// writeUInt32(WireFormatMicro.MESSAGE_SET_TYPE_ID, fieldNumber); -// writeBytes(WireFormatMicro.MESSAGE_SET_MESSAGE, value); -// writeTag(WireFormatMicro.MESSAGE_SET_ITEM, WireFormatMicro.WIRETYPE_END_GROUP); -// } - - // ----------------------------------------------------------------- - - /** Write a {@code double} field to the stream. */ - public void writeDoubleNoTag(final double value) throws IOException { - writeRawLittleEndian64(Double.doubleToLongBits(value)); - } - - /** Write a {@code float} field to the stream. */ - public void writeFloatNoTag(final float value) throws IOException { - writeRawLittleEndian32(Float.floatToIntBits(value)); - } - - /** Write a {@code uint64} field to the stream. */ - public void writeUInt64NoTag(final long value) throws IOException { - writeRawVarint64(value); - } - - /** Write an {@code int64} field to the stream. */ - public void writeInt64NoTag(final long value) throws IOException { - writeRawVarint64(value); - } - - /** Write an {@code int32} field to the stream. */ - public void writeInt32NoTag(final int value) throws IOException { - if (value >= 0) { - writeRawVarint32(value); - } else { - // Must sign-extend. - writeRawVarint64(value); - } - } - - /** Write a {@code fixed64} field to the stream. */ - public void writeFixed64NoTag(final long value) throws IOException { - writeRawLittleEndian64(value); - } - - /** Write a {@code fixed32} field to the stream. */ - public void writeFixed32NoTag(final int value) throws IOException { - writeRawLittleEndian32(value); - } - - /** Write a {@code bool} field to the stream. */ - public void writeBoolNoTag(final boolean value) throws IOException { - writeRawByte(value ? 1 : 0); - } - - /** Write a {@code string} field to the stream. */ - public void writeStringNoTag(final String value) throws IOException { - // UTF-8 byte length of the string is at least its UTF-16 code unit length (value.length()), - // and at most 3 times of it. Optimize for the case where we know this length results in a - // constant varint length - saves measuring length of the string. - try { - final int minLengthVarIntSize = computeRawVarint32Size(value.length()); - final int maxLengthVarIntSize = computeRawVarint32Size(value.length() * MAX_UTF8_EXPANSION); - if (minLengthVarIntSize == maxLengthVarIntSize) { - int oldPosition = buffer.position(); - // Buffer.position, when passed a position that is past its limit, throws - // IllegalArgumentException, and this class is documented to throw - // OutOfSpaceException instead. - if (buffer.remaining() < minLengthVarIntSize) { - throw new OutOfSpaceException(oldPosition + minLengthVarIntSize, buffer.limit()); - } - buffer.position(oldPosition + minLengthVarIntSize); - encode(value, buffer); - int newPosition = buffer.position(); - buffer.position(oldPosition); - writeRawVarint32(newPosition - oldPosition - minLengthVarIntSize); - buffer.position(newPosition); - } else { - writeRawVarint32(encodedLength(value)); - encode(value, buffer); - } - } catch (BufferOverflowException e) { - final OutOfSpaceException outOfSpaceException = new OutOfSpaceException(buffer.position(), - buffer.limit()); - outOfSpaceException.initCause(e); - throw outOfSpaceException; - } - } - - // These UTF-8 handling methods are copied from Guava's Utf8 class. - /** - * 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) - */ - private 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 < Character.MIN_SUPPLEMENTARY_CODE_POINT) { - throw new IllegalArgumentException("Unpaired surrogate at index " + i); - } - i++; - } - } - } - return utf8Length; - } - - /** - * Encodes {@code sequence} into UTF-8, in {@code byteBuffer}. For a string, this method is - * equivalent to {@code buffer.put(string.getBytes(UTF_8))}, but is more efficient in both time - * and space. Bytes are written starting at the current position. This method requires paired - * surrogates, and therefore does not support chunking. - * - * <p>To ensure sufficient space in the output buffer, either call {@link #encodedLength} to - * compute the exact amount needed, or leave room for {@code 3 * sequence.length()}, which is the - * largest possible number of bytes that any input can be encoded to. - * - * @throws IllegalArgumentException if {@code sequence} contains ill-formed UTF-16 (unpaired - * surrogates) - * @throws BufferOverflowException if {@code sequence} encoded in UTF-8 does not fit in - * {@code byteBuffer}'s remaining space. - * @throws ReadOnlyBufferException if {@code byteBuffer} is a read-only buffer. - */ - private static void encode(CharSequence sequence, ByteBuffer byteBuffer) { - if (byteBuffer.isReadOnly()) { - throw new ReadOnlyBufferException(); - } else if (byteBuffer.hasArray()) { - try { - int encoded = encode(sequence, - byteBuffer.array(), - byteBuffer.arrayOffset() + byteBuffer.position(), - byteBuffer.remaining()); - byteBuffer.position(encoded - byteBuffer.arrayOffset()); - } catch (ArrayIndexOutOfBoundsException e) { - BufferOverflowException boe = new BufferOverflowException(); - boe.initCause(e); - throw boe; - } - } else { - encodeDirect(sequence, byteBuffer); - } - } - - private static void encodeDirect(CharSequence sequence, ByteBuffer byteBuffer) { - int utf16Length = sequence.length(); - for (int i = 0; i < utf16Length; i++) { - final char c = sequence.charAt(i); - if (c < 0x80) { // ASCII - byteBuffer.put((byte) c); - } else if (c < 0x800) { // 11 bits, two UTF-8 bytes - byteBuffer.put((byte) ((0xF << 6) | (c >>> 6))); - byteBuffer.put((byte) (0x80 | (0x3F & c))); - } else if (c < Character.MIN_SURROGATE || Character.MAX_SURROGATE < c) { - // Maximium single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes - byteBuffer.put((byte) ((0xF << 5) | (c >>> 12))); - byteBuffer.put((byte) (0x80 | (0x3F & (c >>> 6)))); - byteBuffer.put((byte) (0x80 | (0x3F & c))); - } else { - final char low; - if (i + 1 == sequence.length() - || !Character.isSurrogatePair(c, (low = sequence.charAt(++i)))) { - throw new IllegalArgumentException("Unpaired surrogate at index " + (i - 1)); - } - int codePoint = Character.toCodePoint(c, low); - byteBuffer.put((byte) ((0xF << 4) | (codePoint >>> 18))); - byteBuffer.put((byte) (0x80 | (0x3F & (codePoint >>> 12)))); - byteBuffer.put((byte) (0x80 | (0x3F & (codePoint >>> 6)))); - byteBuffer.put((byte) (0x80 | (0x3F & codePoint))); - } - } - } - - private static int encode(CharSequence sequence, byte[] bytes, int offset, int length) { - int utf16Length = sequence.length(); - int j = offset; - int i = 0; - int limit = offset + length; - // Designed to take advantage of - // https://wikis.oracle.com/display/HotSpotInternals/RangeCheckElimination - for (char c; i < utf16Length && i + j < limit && (c = sequence.charAt(i)) < 0x80; i++) { - bytes[j + i] = (byte) c; - } - if (i == utf16Length) { - return j + utf16Length; - } - j += i; - for (char c; i < utf16Length; i++) { - c = sequence.charAt(i); - if (c < 0x80 && j < limit) { - bytes[j++] = (byte) c; - } else if (c < 0x800 && j <= limit - 2) { // 11 bits, two UTF-8 bytes - bytes[j++] = (byte) ((0xF << 6) | (c >>> 6)); - bytes[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 - bytes[j++] = (byte) ((0xF << 5) | (c >>> 12)); - bytes[j++] = (byte) (0x80 | (0x3F & (c >>> 6))); - bytes[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 == sequence.length() - || !Character.isSurrogatePair(c, (low = sequence.charAt(++i)))) { - throw new IllegalArgumentException("Unpaired surrogate at index " + (i - 1)); - } - int codePoint = Character.toCodePoint(c, low); - bytes[j++] = (byte) ((0xF << 4) | (codePoint >>> 18)); - bytes[j++] = (byte) (0x80 | (0x3F & (codePoint >>> 12))); - bytes[j++] = (byte) (0x80 | (0x3F & (codePoint >>> 6))); - bytes[j++] = (byte) (0x80 | (0x3F & codePoint)); - } else { - throw new ArrayIndexOutOfBoundsException("Failed writing " + c + " at index " + j); - } - } - return j; - } - - // End guava UTF-8 methods - - - /** Write a {@code group} field to the stream. */ - public void writeGroupNoTag(final MessageNano value) throws IOException { - value.writeTo(this); - } - - /** Write an embedded message field to the stream. */ - public void writeMessageNoTag(final MessageNano value) throws IOException { - writeRawVarint32(value.getCachedSize()); - value.writeTo(this); - } - - /** Write a {@code bytes} field to the stream. */ - public void writeBytesNoTag(final byte[] value) throws IOException { - writeRawVarint32(value.length); - writeRawBytes(value); - } - - /** Write a {@code uint32} field to the stream. */ - public void writeUInt32NoTag(final int value) throws IOException { - writeRawVarint32(value); - } - - /** - * Write an enum field to the stream. Caller is responsible - * for converting the enum value to its numeric value. - */ - public void writeEnumNoTag(final int value) throws IOException { - writeRawVarint32(value); - } - - /** Write an {@code sfixed32} field to the stream. */ - public void writeSFixed32NoTag(final int value) throws IOException { - writeRawLittleEndian32(value); - } - - /** Write an {@code sfixed64} field to the stream. */ - public void writeSFixed64NoTag(final long value) throws IOException { - writeRawLittleEndian64(value); - } - - /** Write an {@code sint32} field to the stream. */ - public void writeSInt32NoTag(final int value) throws IOException { - writeRawVarint32(encodeZigZag32(value)); - } - - /** Write an {@code sint64} field to the stream. */ - public void writeSInt64NoTag(final long value) throws IOException { - writeRawVarint64(encodeZigZag64(value)); - } - - // ================================================================= - - /** - * Compute the number of bytes that would be needed to encode a - * {@code double} field, including tag. - */ - public static int computeDoubleSize(final int fieldNumber, - final double value) { - return computeTagSize(fieldNumber) + computeDoubleSizeNoTag(value); - } - - /** - * Compute the number of bytes that would be needed to encode a - * {@code float} field, including tag. - */ - public static int computeFloatSize(final int fieldNumber, final float value) { - return computeTagSize(fieldNumber) + computeFloatSizeNoTag(value); - } - - /** - * Compute the number of bytes that would be needed to encode a - * {@code uint64} field, including tag. - */ - public static int computeUInt64Size(final int fieldNumber, final long value) { - return computeTagSize(fieldNumber) + computeUInt64SizeNoTag(value); - } - - /** - * Compute the number of bytes that would be needed to encode an - * {@code int64} field, including tag. - */ - public static int computeInt64Size(final int fieldNumber, final long value) { - return computeTagSize(fieldNumber) + computeInt64SizeNoTag(value); - } - - /** - * Compute the number of bytes that would be needed to encode an - * {@code int32} field, including tag. - */ - public static int computeInt32Size(final int fieldNumber, final int value) { - return computeTagSize(fieldNumber) + computeInt32SizeNoTag(value); - } - - /** - * Compute the number of bytes that would be needed to encode a - * {@code fixed64} field, including tag. - */ - public static int computeFixed64Size(final int fieldNumber, - final long value) { - return computeTagSize(fieldNumber) + computeFixed64SizeNoTag(value); - } - - /** - * Compute the number of bytes that would be needed to encode a - * {@code fixed32} field, including tag. - */ - public static int computeFixed32Size(final int fieldNumber, - final int value) { - return computeTagSize(fieldNumber) + computeFixed32SizeNoTag(value); - } - - /** - * Compute the number of bytes that would be needed to encode a - * {@code bool} field, including tag. - */ - public static int computeBoolSize(final int fieldNumber, - final boolean value) { - return computeTagSize(fieldNumber) + computeBoolSizeNoTag(value); - } - - /** - * Compute the number of bytes that would be needed to encode a - * {@code string} field, including tag. - */ - public static int computeStringSize(final int fieldNumber, - final String value) { - return computeTagSize(fieldNumber) + computeStringSizeNoTag(value); - } - - /** - * Compute the number of bytes that would be needed to encode a - * {@code group} field, including tag. - */ - public static int computeGroupSize(final int fieldNumber, - final MessageNano value) { - return computeTagSize(fieldNumber) * 2 + computeGroupSizeNoTag(value); - } - - /** - * Compute the number of bytes that would be needed to encode an - * embedded message field, including tag. - */ - public static int computeMessageSize(final int fieldNumber, - final MessageNano value) { - return computeTagSize(fieldNumber) + computeMessageSizeNoTag(value); - } - - /** - * Compute the number of bytes that would be needed to encode a - * {@code bytes} field, including tag. - */ - public static int computeBytesSize(final int fieldNumber, - final byte[] value) { - return computeTagSize(fieldNumber) + computeBytesSizeNoTag(value); - } - - /** - * Compute the number of bytes that would be needed to encode a - * {@code uint32} field, including tag. - */ - public static int computeUInt32Size(final int fieldNumber, final int value) { - return computeTagSize(fieldNumber) + computeUInt32SizeNoTag(value); - } - - /** - * Compute the number of bytes that would be needed to encode an - * enum field, including tag. Caller is responsible for converting the - * enum value to its numeric value. - */ - public static int computeEnumSize(final int fieldNumber, final int value) { - return computeTagSize(fieldNumber) + computeEnumSizeNoTag(value); - } - - /** - * Compute the number of bytes that would be needed to encode an - * {@code sfixed32} field, including tag. - */ - public static int computeSFixed32Size(final int fieldNumber, - final int value) { - return computeTagSize(fieldNumber) + computeSFixed32SizeNoTag(value); - } - - /** - * Compute the number of bytes that would be needed to encode an - * {@code sfixed64} field, including tag. - */ - public static int computeSFixed64Size(final int fieldNumber, - final long value) { - return computeTagSize(fieldNumber) + computeSFixed64SizeNoTag(value); - } - - /** - * Compute the number of bytes that would be needed to encode an - * {@code sint32} field, including tag. - */ - public static int computeSInt32Size(final int fieldNumber, final int value) { - return computeTagSize(fieldNumber) + computeSInt32SizeNoTag(value); - } - - /** - * Compute the number of bytes that would be needed to encode an - * {@code sint64} field, including tag. - */ - public static int computeSInt64Size(final int fieldNumber, final long value) { - return computeTagSize(fieldNumber) + computeSInt64SizeNoTag(value); - } - - /** - * Compute the number of bytes that would be needed to encode a - * MessageSet extension to the stream. For historical reasons, - * the wire format differs from normal fields. - */ -// public static int computeMessageSetExtensionSize( -// final int fieldNumber, final MessageMicro value) { -// return computeTagSize(WireFormatMicro.MESSAGE_SET_ITEM) * 2 + -// computeUInt32Size(WireFormatMicro.MESSAGE_SET_TYPE_ID, fieldNumber) + -// computeMessageSize(WireFormatMicro.MESSAGE_SET_MESSAGE, value); -// } - - /** - * Compute the number of bytes that would be needed to encode an - * unparsed MessageSet extension field to the stream. For - * historical reasons, the wire format differs from normal fields. - */ -// public static int computeRawMessageSetExtensionSize( -// final int fieldNumber, final ByteStringMicro value) { -// return computeTagSize(WireFormatMicro.MESSAGE_SET_ITEM) * 2 + -// computeUInt32Size(WireFormatMicro.MESSAGE_SET_TYPE_ID, fieldNumber) + -// computeBytesSize(WireFormatMicro.MESSAGE_SET_MESSAGE, value); -// } - - // ----------------------------------------------------------------- - - /** - * Compute the number of bytes that would be needed to encode a - * {@code double} field, including tag. - */ - public static int computeDoubleSizeNoTag(final double value) { - return LITTLE_ENDIAN_64_SIZE; - } - - /** - * Compute the number of bytes that would be needed to encode a - * {@code float} field, including tag. - */ - public static int computeFloatSizeNoTag(final float value) { - return LITTLE_ENDIAN_32_SIZE; - } - - /** - * Compute the number of bytes that would be needed to encode a - * {@code uint64} field, including tag. - */ - public static int computeUInt64SizeNoTag(final long value) { - return computeRawVarint64Size(value); - } - - /** - * Compute the number of bytes that would be needed to encode an - * {@code int64} field, including tag. - */ - public static int computeInt64SizeNoTag(final long value) { - return computeRawVarint64Size(value); - } - - /** - * Compute the number of bytes that would be needed to encode an - * {@code int32} field, including tag. - */ - public static int computeInt32SizeNoTag(final int value) { - if (value >= 0) { - return computeRawVarint32Size(value); - } else { - // Must sign-extend. - return 10; - } - } - - /** - * Compute the number of bytes that would be needed to encode a - * {@code fixed64} field. - */ - public static int computeFixed64SizeNoTag(final long value) { - return LITTLE_ENDIAN_64_SIZE; - } - - /** - * Compute the number of bytes that would be needed to encode a - * {@code fixed32} field. - */ - public static int computeFixed32SizeNoTag(final int value) { - return LITTLE_ENDIAN_32_SIZE; - } - - /** - * Compute the number of bytes that would be needed to encode a - * {@code bool} field. - */ - public static int computeBoolSizeNoTag(final boolean value) { - return 1; - } - - /** - * Compute the number of bytes that would be needed to encode a - * {@code string} field. - */ - public static int computeStringSizeNoTag(final String value) { - final int length = encodedLength(value); - return computeRawVarint32Size(length) + length; - } - - /** - * Compute the number of bytes that would be needed to encode a - * {@code group} field. - */ - public static int computeGroupSizeNoTag(final MessageNano value) { - return value.getSerializedSize(); - } - - /** - * Compute the number of bytes that would be needed to encode an embedded - * message field. - */ - public static int computeMessageSizeNoTag(final MessageNano value) { - final int size = value.getSerializedSize(); - return computeRawVarint32Size(size) + size; - } - - /** - * Compute the number of bytes that would be needed to encode a - * {@code bytes} field. - */ - public static int computeBytesSizeNoTag(final byte[] value) { - return computeRawVarint32Size(value.length) + value.length; - } - - /** - * Compute the number of bytes that would be needed to encode a - * {@code uint32} field. - */ - public static int computeUInt32SizeNoTag(final int value) { - return computeRawVarint32Size(value); - } - - /** - * Compute the number of bytes that would be needed to encode an enum field. - * Caller is responsible for converting the enum value to its numeric value. - */ - public static int computeEnumSizeNoTag(final int value) { - return computeRawVarint32Size(value); - } - - /** - * Compute the number of bytes that would be needed to encode an - * {@code sfixed32} field. - */ - public static int computeSFixed32SizeNoTag(final int value) { - return LITTLE_ENDIAN_32_SIZE; - } - - /** - * Compute the number of bytes that would be needed to encode an - * {@code sfixed64} field. - */ - public static int computeSFixed64SizeNoTag(final long value) { - return LITTLE_ENDIAN_64_SIZE; - } - - /** - * Compute the number of bytes that would be needed to encode an - * {@code sint32} field. - */ - public static int computeSInt32SizeNoTag(final int value) { - return computeRawVarint32Size(encodeZigZag32(value)); - } - - /** - * Compute the number of bytes that would be needed to encode an - * {@code sint64} field. - */ - public static int computeSInt64SizeNoTag(final long value) { - return computeRawVarint64Size(encodeZigZag64(value)); - } - - // ================================================================= - - /** - * If writing to a flat array, return the space left in the array. - * Otherwise, throws {@code UnsupportedOperationException}. - */ - public int spaceLeft() { - return buffer.remaining(); - } - - /** - * Verifies that {@link #spaceLeft()} returns zero. It's common to create - * a byte array that is exactly big enough to hold a message, then write to - * it with a {@code CodedOutputStream}. Calling {@code checkNoSpaceLeft()} - * after writing verifies that the message was actually as big as expected, - * which can help catch bugs. - */ - public void checkNoSpaceLeft() { - if (spaceLeft() != 0) { - throw new IllegalStateException( - "Did not write as much data as expected."); - } - } - - /** - * Returns the position within the internal buffer. - */ - public int position() { - return buffer.position(); - } - - /** - * Resets the position within the internal buffer to zero. - * - * @see #position - * @see #spaceLeft - */ - public void reset() { - buffer.clear(); - } - - /** - * If you create a CodedOutputStream around a simple flat array, you must - * not attempt to write more bytes than the array has space. Otherwise, - * this exception will be thrown. - */ - public static class OutOfSpaceException extends IOException { - private static final long serialVersionUID = -6947486886997889499L; - - OutOfSpaceException(int position, int limit) { - super("CodedOutputStream was writing to a flat byte array and ran " + - "out of space (pos " + position + " limit " + limit + ")."); - } - } - - /** Write a single byte. */ - public void writeRawByte(final byte value) throws IOException { - if (!buffer.hasRemaining()) { - // We're writing to a single buffer. - throw new OutOfSpaceException(buffer.position(), buffer.limit()); - } - - buffer.put(value); - } - - /** Write a single byte, represented by an integer value. */ - public void writeRawByte(final int value) throws IOException { - writeRawByte((byte) value); - } - - /** Write an array of bytes. */ - public void writeRawBytes(final byte[] value) throws IOException { - writeRawBytes(value, 0, value.length); - } - - /** Write part of an array of bytes. */ - public void writeRawBytes(final byte[] value, int offset, int length) - throws IOException { - if (buffer.remaining() >= length) { - buffer.put(value, offset, length); - } else { - // We're writing to a single buffer. - throw new OutOfSpaceException(buffer.position(), buffer.limit()); - } - } - - /** Encode and write a tag. */ - public void writeTag(final int fieldNumber, final int wireType) - throws IOException { - writeRawVarint32(WireFormatNano.makeTag(fieldNumber, wireType)); - } - - /** Compute the number of bytes that would be needed to encode a tag. */ - public static int computeTagSize(final int fieldNumber) { - return computeRawVarint32Size(WireFormatNano.makeTag(fieldNumber, 0)); - } - - /** - * Encode and write a varint. {@code value} is treated as - * unsigned, so it won't be sign-extended if negative. - */ - public void writeRawVarint32(int value) throws IOException { - while (true) { - if ((value & ~0x7F) == 0) { - writeRawByte(value); - return; - } else { - writeRawByte((value & 0x7F) | 0x80); - value >>>= 7; - } - } - } - - /** - * Compute the number of bytes that would be needed to encode a varint. - * {@code value} is treated as unsigned, so it won't be sign-extended if - * negative. - */ - public static int computeRawVarint32Size(final int value) { - if ((value & (0xffffffff << 7)) == 0) return 1; - if ((value & (0xffffffff << 14)) == 0) return 2; - if ((value & (0xffffffff << 21)) == 0) return 3; - if ((value & (0xffffffff << 28)) == 0) return 4; - return 5; - } - - /** Encode and write a varint. */ - public void writeRawVarint64(long value) throws IOException { - while (true) { - if ((value & ~0x7FL) == 0) { - writeRawByte((int)value); - return; - } else { - writeRawByte(((int)value & 0x7F) | 0x80); - value >>>= 7; - } - } - } - - /** Compute the number of bytes that would be needed to encode a varint. */ - public static int computeRawVarint64Size(final long value) { - if ((value & (0xffffffffffffffffL << 7)) == 0) return 1; - if ((value & (0xffffffffffffffffL << 14)) == 0) return 2; - if ((value & (0xffffffffffffffffL << 21)) == 0) return 3; - if ((value & (0xffffffffffffffffL << 28)) == 0) return 4; - if ((value & (0xffffffffffffffffL << 35)) == 0) return 5; - if ((value & (0xffffffffffffffffL << 42)) == 0) return 6; - if ((value & (0xffffffffffffffffL << 49)) == 0) return 7; - if ((value & (0xffffffffffffffffL << 56)) == 0) return 8; - if ((value & (0xffffffffffffffffL << 63)) == 0) return 9; - return 10; - } - - /** Write a little-endian 32-bit integer. */ - public void writeRawLittleEndian32(final int value) throws IOException { - if (buffer.remaining() < 4) { - throw new OutOfSpaceException(buffer.position(), buffer.limit()); - } - buffer.putInt(value); - } - - public static final int LITTLE_ENDIAN_32_SIZE = 4; - - /** Write a little-endian 64-bit integer. */ - public void writeRawLittleEndian64(final long value) throws IOException { - if (buffer.remaining() < 8) { - throw new OutOfSpaceException(buffer.position(), buffer.limit()); - } - buffer.putLong(value); - } - - public static final int LITTLE_ENDIAN_64_SIZE = 8; - - /** - * Encode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers - * into values that can be efficiently encoded with varint. (Otherwise, - * negative values must be sign-extended to 64 bits to be varint encoded, - * thus always taking 10 bytes on the wire.) - * - * @param n A signed 32-bit integer. - * @return An unsigned 32-bit integer, stored in a signed int because - * Java has no explicit unsigned support. - */ - public static int encodeZigZag32(final int n) { - // Note: the right-shift must be arithmetic - return (n << 1) ^ (n >> 31); - } - - /** - * Encode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers - * into values that can be efficiently encoded with varint. (Otherwise, - * negative values must be sign-extended to 64 bits to be varint encoded, - * thus always taking 10 bytes on the wire.) - * - * @param n A signed 64-bit integer. - * @return An unsigned 64-bit integer, stored in a signed int because - * Java has no explicit unsigned support. - */ - public static long encodeZigZag64(final long n) { - // Note: the right-shift must be arithmetic - return (n << 1) ^ (n >> 63); - } - - static int computeFieldSize(int number, int type, Object object) { - switch (type) { - case InternalNano.TYPE_BOOL: - return computeBoolSize(number, (Boolean) object); - case InternalNano.TYPE_BYTES: - return computeBytesSize(number, (byte[]) object); - case InternalNano.TYPE_STRING: - return computeStringSize(number, (String) object); - case InternalNano.TYPE_FLOAT: - return computeFloatSize(number, (Float) object); - case InternalNano.TYPE_DOUBLE: - return computeDoubleSize(number, (Double) object); - case InternalNano.TYPE_ENUM: - return computeEnumSize(number, (Integer) object); - case InternalNano.TYPE_FIXED32: - return computeFixed32Size(number, (Integer) object); - case InternalNano.TYPE_INT32: - return computeInt32Size(number, (Integer) object); - case InternalNano.TYPE_UINT32: - return computeUInt32Size(number, (Integer) object); - case InternalNano.TYPE_SINT32: - return computeSInt32Size(number, (Integer) object); - case InternalNano.TYPE_SFIXED32: - return computeSFixed32Size(number, (Integer) object); - case InternalNano.TYPE_INT64: - return computeInt64Size(number, (Long) object); - case InternalNano.TYPE_UINT64: - return computeUInt64Size(number, (Long) object); - case InternalNano.TYPE_SINT64: - return computeSInt64Size(number, (Long) object); - case InternalNano.TYPE_FIXED64: - return computeFixed64Size(number, (Long) object); - case InternalNano.TYPE_SFIXED64: - return computeSFixed64Size(number, (Long) object); - case InternalNano.TYPE_MESSAGE: - return computeMessageSize(number, (MessageNano) object); - case InternalNano.TYPE_GROUP: - return computeGroupSize(number, (MessageNano) object); - default: - throw new IllegalArgumentException("Unknown type: " + type); - } - } - - void writeField(int number, int type, Object value) - throws IOException { - switch (type) { - case InternalNano.TYPE_DOUBLE: - Double doubleValue = (Double) value; - writeDouble(number, doubleValue); - break; - case InternalNano.TYPE_FLOAT: - Float floatValue = (Float) value; - writeFloat(number, floatValue); - break; - case InternalNano.TYPE_INT64: - Long int64Value = (Long) value; - writeInt64(number, int64Value); - break; - case InternalNano.TYPE_UINT64: - Long uint64Value = (Long) value; - writeUInt64(number, uint64Value); - break; - case InternalNano.TYPE_INT32: - Integer int32Value = (Integer) value; - writeInt32(number, int32Value); - break; - case InternalNano.TYPE_FIXED64: - Long fixed64Value = (Long) value; - writeFixed64(number, fixed64Value); - break; - case InternalNano.TYPE_FIXED32: - Integer fixed32Value = (Integer) value; - writeFixed32(number, fixed32Value); - break; - case InternalNano.TYPE_BOOL: - Boolean boolValue = (Boolean) value; - writeBool(number, boolValue); - break; - case InternalNano.TYPE_STRING: - String stringValue = (String) value; - writeString(number, stringValue); - break; - case InternalNano.TYPE_BYTES: - byte[] bytesValue = (byte[]) value; - writeBytes(number, bytesValue); - break; - case InternalNano.TYPE_UINT32: - Integer uint32Value = (Integer) value; - writeUInt32(number, uint32Value); - break; - case InternalNano.TYPE_ENUM: - Integer enumValue = (Integer) value; - writeEnum(number, enumValue); - break; - case InternalNano.TYPE_SFIXED32: - Integer sfixed32Value = (Integer) value; - writeSFixed32(number, sfixed32Value); - break; - case InternalNano.TYPE_SFIXED64: - Long sfixed64Value = (Long) value; - writeSFixed64(number, sfixed64Value); - break; - case InternalNano.TYPE_SINT32: - Integer sint32Value = (Integer) value; - writeSInt32(number, sint32Value); - break; - case InternalNano.TYPE_SINT64: - Long sint64Value = (Long) value; - writeSInt64(number, sint64Value); - break; - case InternalNano.TYPE_MESSAGE: - MessageNano messageValue = (MessageNano) value; - writeMessage(number, messageValue); - break; - case InternalNano.TYPE_GROUP: - MessageNano groupValue = (MessageNano) value; - writeGroup(number, groupValue); - break; - default: - throw new IOException("Unknown type: " + type); - } - } - -} diff --git a/javanano/src/main/java/com/google/protobuf/nano/ExtendableMessageNano.java b/javanano/src/main/java/com/google/protobuf/nano/ExtendableMessageNano.java deleted file mode 100644 index 87973d76..00000000 --- a/javanano/src/main/java/com/google/protobuf/nano/ExtendableMessageNano.java +++ /dev/null @@ -1,169 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2013 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.nano; - -import java.io.IOException; - -/** - * Base class of those Protocol Buffer messages that need to store unknown fields, - * such as extensions. - */ -public abstract class ExtendableMessageNano<M extends ExtendableMessageNano<M>> - extends MessageNano { - /** - * A container for fields unknown to the message, including extensions. Extension fields can - * can be accessed through the {@link #getExtension} and {@link #setExtension} methods. - */ - protected FieldArray unknownFieldData; - - @Override - protected int computeSerializedSize() { - int size = 0; - if (unknownFieldData != null) { - for (int i = 0; i < unknownFieldData.size(); i++) { - FieldData field = unknownFieldData.dataAt(i); - size += field.computeSerializedSize(); - } - } - return size; - } - - @Override - public void writeTo(CodedOutputByteBufferNano output) throws IOException { - if (unknownFieldData == null) { - return; - } - for (int i = 0; i < unknownFieldData.size(); i++) { - FieldData field = unknownFieldData.dataAt(i); - field.writeTo(output); - } - } - - /** - * Checks if there is a value stored for the specified extension in this - * message. - */ - public final boolean hasExtension(Extension<M, ?> extension) { - if (unknownFieldData == null) { - return false; - } - FieldData field = unknownFieldData.get(WireFormatNano.getTagFieldNumber(extension.tag)); - return field != null; - } - - /** - * Gets the value stored in the specified extension of this message. - */ - public final <T> T getExtension(Extension<M, T> extension) { - if (unknownFieldData == null) { - return null; - } - FieldData field = unknownFieldData.get(WireFormatNano.getTagFieldNumber(extension.tag)); - return field == null ? null : field.getValue(extension); - } - - /** - * Sets the value of the specified extension of this message. - */ - public final <T> M setExtension(Extension<M, T> extension, T value) { - int fieldNumber = WireFormatNano.getTagFieldNumber(extension.tag); - if (value == null) { - if (unknownFieldData != null) { - unknownFieldData.remove(fieldNumber); - if (unknownFieldData.isEmpty()) { - unknownFieldData = null; - } - } - } else { - FieldData field = null; - if (unknownFieldData == null) { - unknownFieldData = new FieldArray(); - } else { - field = unknownFieldData.get(fieldNumber); - } - if (field == null) { - unknownFieldData.put(fieldNumber, new FieldData(extension, value)); - } else { - field.setValue(extension, value); - } - } - - @SuppressWarnings("unchecked") // Generated code should guarantee type safety - M typedThis = (M) this; - return typedThis; - } - - /** - * Stores the binary data of an unknown field. - * - * <p>Generated messages will call this for unknown fields if the store_unknown_fields - * option is on. - * - * <p>Note that the tag might be a end-group tag (rather than the start of an unknown field) in - * which case we do not want to add an unknown field entry. - * - * @param input the input buffer. - * @param tag the tag of the field. - - * @return {@literal true} unless the tag is an end-group tag. - */ - protected final boolean storeUnknownField(CodedInputByteBufferNano input, int tag) - throws IOException { - int startPos = input.getPosition(); - if (!input.skipField(tag)) { - return false; // This wasn't an unknown field, it's an end-group tag. - } - int fieldNumber = WireFormatNano.getTagFieldNumber(tag); - int endPos = input.getPosition(); - byte[] bytes = input.getData(startPos, endPos - startPos); - UnknownFieldData unknownField = new UnknownFieldData(tag, bytes); - - FieldData field = null; - if (unknownFieldData == null) { - unknownFieldData = new FieldArray(); - } else { - field = unknownFieldData.get(fieldNumber); - } - if (field == null) { - field = new FieldData(); - unknownFieldData.put(fieldNumber, field); - } - field.addUnknownField(unknownField); - return true; - } - - @Override - public M clone() throws CloneNotSupportedException { - M cloned = (M) super.clone(); - InternalNano.cloneUnknownFieldData(this, cloned); - return cloned; - } -} diff --git a/javanano/src/main/java/com/google/protobuf/nano/Extension.java b/javanano/src/main/java/com/google/protobuf/nano/Extension.java deleted file mode 100644 index c458f9b1..00000000 --- a/javanano/src/main/java/com/google/protobuf/nano/Extension.java +++ /dev/null @@ -1,706 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2013 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.nano; - -import java.io.IOException; -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.List; - -/** - * Represents an extension. - * - * @author bduff@google.com (Brian Duff) - * @author maxtroy@google.com (Max Cai) - * @param <M> the type of the extendable message this extension is for. - * @param <T> the Java type of the extension; see {@link #clazz}. - */ -public class Extension<M extends ExtendableMessageNano<M>, T> { - - /* - * Because we typically only define message-typed extensions, the Extension class hierarchy is - * designed as follows, to allow a big amount of code in this file to be removed by ProGuard: - * - * Extension // ready to use for message/group typed extensions - * Δ - * | - * PrimitiveExtension // for primitive/enum typed extensions - */ - - public static final int TYPE_DOUBLE = InternalNano.TYPE_DOUBLE; - public static final int TYPE_FLOAT = InternalNano.TYPE_FLOAT; - public static final int TYPE_INT64 = InternalNano.TYPE_INT64; - public static final int TYPE_UINT64 = InternalNano.TYPE_UINT64; - public static final int TYPE_INT32 = InternalNano.TYPE_INT32; - public static final int TYPE_FIXED64 = InternalNano.TYPE_FIXED64; - public static final int TYPE_FIXED32 = InternalNano.TYPE_FIXED32; - public static final int TYPE_BOOL = InternalNano.TYPE_BOOL; - public static final int TYPE_STRING = InternalNano.TYPE_STRING; - public static final int TYPE_GROUP = InternalNano.TYPE_GROUP; - public static final int TYPE_MESSAGE = InternalNano.TYPE_MESSAGE; - public static final int TYPE_BYTES = InternalNano.TYPE_BYTES; - public static final int TYPE_UINT32 = InternalNano.TYPE_UINT32; - public static final int TYPE_ENUM = InternalNano.TYPE_ENUM; - public static final int TYPE_SFIXED32 = InternalNano.TYPE_SFIXED32; - public static final int TYPE_SFIXED64 = InternalNano.TYPE_SFIXED64; - public static final int TYPE_SINT32 = InternalNano.TYPE_SINT32; - public static final int TYPE_SINT64 = InternalNano.TYPE_SINT64; - - /** - * Creates an {@code Extension} of the given message type and tag number. - * Should be used by the generated code only. - * - * @param type {@link #TYPE_MESSAGE} or {@link #TYPE_GROUP} - * @deprecated use {@link #createMessageTyped(int, Class, long)} instead. - */ - @Deprecated - public static <M extends ExtendableMessageNano<M>, T extends MessageNano> - Extension<M, T> createMessageTyped(int type, Class<T> clazz, int tag) { - return new Extension<M, T>(type, clazz, tag, false); - } - - // Note: these create...() methods take a long for the tag parameter, - // because tags are represented as unsigned ints, and these values exist - // in generated code as long values. However, they can fit in 32-bits, so - // it's safe to cast them to int without loss of precision. - - /** - * Creates an {@code Extension} of the given message type and tag number. - * Should be used by the generated code only. - * - * @param type {@link #TYPE_MESSAGE} or {@link #TYPE_GROUP} - */ - public static <M extends ExtendableMessageNano<M>, T extends MessageNano> - Extension<M, T> createMessageTyped(int type, Class<T> clazz, long tag) { - return new Extension<M, T>(type, clazz, (int) tag, false); - } - - /** - * Creates a repeated {@code Extension} of the given message type and tag number. - * Should be used by the generated code only. - * - * @param type {@link #TYPE_MESSAGE} or {@link #TYPE_GROUP} - */ - public static <M extends ExtendableMessageNano<M>, T extends MessageNano> - Extension<M, T[]> createRepeatedMessageTyped(int type, Class<T[]> clazz, long tag) { - return new Extension<M, T[]>(type, clazz, (int) tag, true); - } - - /** - * Creates an {@code Extension} of the given primitive type and tag number. - * Should be used by the generated code only. - * - * @param type one of {@code TYPE_*}, except {@link #TYPE_MESSAGE} and {@link #TYPE_GROUP} - * @param clazz the boxed Java type of this extension - */ - public static <M extends ExtendableMessageNano<M>, T> - Extension<M, T> createPrimitiveTyped(int type, Class<T> clazz, long tag) { - return new PrimitiveExtension<M, T>(type, clazz, (int) tag, false, 0, 0); - } - - /** - * Creates a repeated {@code Extension} of the given primitive type and tag number. - * Should be used by the generated code only. - * - * @param type one of {@code TYPE_*}, except {@link #TYPE_MESSAGE} and {@link #TYPE_GROUP} - * @param clazz the Java array type of this extension, with an unboxed component type - */ - public static <M extends ExtendableMessageNano<M>, T> - Extension<M, T> createRepeatedPrimitiveTyped( - int type, Class<T> clazz, long tag, long nonPackedTag, long packedTag) { - return new PrimitiveExtension<M, T>(type, clazz, (int) tag, true, - (int) nonPackedTag, (int) packedTag); - } - - /** - * Protocol Buffer type of this extension; one of the {@code TYPE_} constants. - */ - protected final int type; - - /** - * Java type of this extension. For a singular extension, this is the boxed Java type for the - * Protocol Buffer {@link #type}; for a repeated extension, this is an array type whose - * component type is the unboxed Java type for {@link #type}. For example, for a singular - * {@code int32}/{@link #TYPE_INT32} extension, this equals {@code Integer.class}; for a - * repeated {@code int32} extension, this equals {@code int[].class}. - */ - protected final Class<T> clazz; - - /** - * Tag number of this extension. The data should be viewed as an unsigned 32-bit value. - */ - public final int tag; - - /** - * Whether this extension is repeated. - */ - protected final boolean repeated; - - private Extension(int type, Class<T> clazz, int tag, boolean repeated) { - this.type = type; - this.clazz = clazz; - this.tag = tag; - this.repeated = repeated; - } - - /** - * Returns the value of this extension stored in the given list of unknown fields, or - * {@code null} if no unknown fields matches this extension. - * - * @param unknownFields a list of {@link UnknownFieldData}. All of the elements must have a tag - * that matches this Extension's tag. - * - */ - final T getValueFrom(List<UnknownFieldData> unknownFields) { - if (unknownFields == null) { - return null; - } - return repeated ? getRepeatedValueFrom(unknownFields) : getSingularValueFrom(unknownFields); - } - - private T getRepeatedValueFrom(List<UnknownFieldData> unknownFields) { - // For repeated extensions, read all matching unknown fields in their original order. - List<Object> resultList = new ArrayList<Object>(); - for (int i = 0; i < unknownFields.size(); i++) { - UnknownFieldData data = unknownFields.get(i); - if (data.bytes.length != 0) { - readDataInto(data, resultList); - } - } - - int resultSize = resultList.size(); - if (resultSize == 0) { - return null; - } else { - T result = clazz.cast(Array.newInstance(clazz.getComponentType(), resultSize)); - for (int i = 0; i < resultSize; i++) { - Array.set(result, i, resultList.get(i)); - } - return result; - } - } - - private T getSingularValueFrom(List<UnknownFieldData> unknownFields) { - // For singular extensions, get the last piece of data stored under this extension. - if (unknownFields.isEmpty()) { - return null; - } - UnknownFieldData lastData = unknownFields.get(unknownFields.size() - 1); - return clazz.cast(readData(CodedInputByteBufferNano.newInstance(lastData.bytes))); - } - - protected Object readData(CodedInputByteBufferNano input) { - // This implementation is for message/group extensions. - Class<?> messageType = repeated ? clazz.getComponentType() : clazz; - try { - switch (type) { - case TYPE_GROUP: - MessageNano group = (MessageNano) messageType.newInstance(); - input.readGroup(group, WireFormatNano.getTagFieldNumber(tag)); - return group; - case TYPE_MESSAGE: - MessageNano message = (MessageNano) messageType.newInstance(); - input.readMessage(message); - return message; - default: - throw new IllegalArgumentException("Unknown type " + type); - } - } catch (InstantiationException e) { - throw new IllegalArgumentException( - "Error creating instance of class " + messageType, e); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException( - "Error creating instance of class " + messageType, e); - } catch (IOException e) { - throw new IllegalArgumentException("Error reading extension field", e); - } - } - - protected void readDataInto(UnknownFieldData data, List<Object> resultList) { - // This implementation is for message/group extensions. - resultList.add(readData(CodedInputByteBufferNano.newInstance(data.bytes))); - } - - void writeTo(Object value, CodedOutputByteBufferNano output) throws IOException { - if (repeated) { - writeRepeatedData(value, output); - } else { - writeSingularData(value, output); - } - } - - protected void writeSingularData(Object value, CodedOutputByteBufferNano out) { - // This implementation is for message/group extensions. - try { - out.writeRawVarint32(tag); - switch (type) { - case TYPE_GROUP: - MessageNano groupValue = (MessageNano) value; - int fieldNumber = WireFormatNano.getTagFieldNumber(tag); - out.writeGroupNoTag(groupValue); - // The endgroup tag must be included in the data payload. - out.writeTag(fieldNumber, WireFormatNano.WIRETYPE_END_GROUP); - break; - case TYPE_MESSAGE: - MessageNano messageValue = (MessageNano) value; - out.writeMessageNoTag(messageValue); - break; - default: - throw new IllegalArgumentException("Unknown type " + type); - } - } catch (IOException e) { - // Should not happen - throw new IllegalStateException(e); - } - } - - protected void writeRepeatedData(Object array, CodedOutputByteBufferNano output) { - // This implementation is for non-packed extensions. - int arrayLength = Array.getLength(array); - for (int i = 0; i < arrayLength; i++) { - Object element = Array.get(array, i); - if (element != null) { - writeSingularData(element, output); - } - } - } - - int computeSerializedSize(Object value) { - if (repeated) { - return computeRepeatedSerializedSize(value); - } else { - return computeSingularSerializedSize(value); - } - } - - protected int computeRepeatedSerializedSize(Object array) { - // This implementation is for non-packed extensions. - int size = 0; - int arrayLength = Array.getLength(array); - for (int i = 0; i < arrayLength; i++) { - Object element = Array.get(array, i); - if (element != null) { - size += computeSingularSerializedSize(Array.get(array, i)); - } - } - return size; - } - - protected int computeSingularSerializedSize(Object value) { - // This implementation is for message/group extensions. - int fieldNumber = WireFormatNano.getTagFieldNumber(tag); - switch (type) { - case TYPE_GROUP: - MessageNano groupValue = (MessageNano) value; - return CodedOutputByteBufferNano.computeGroupSize(fieldNumber, groupValue); - case TYPE_MESSAGE: - MessageNano messageValue = (MessageNano) value; - return CodedOutputByteBufferNano.computeMessageSize(fieldNumber, messageValue); - default: - throw new IllegalArgumentException("Unknown type " + type); - } - } - - /** - * Represents an extension of a primitive (including enum) type. If there is no primitive - * extensions, this subclass will be removable by ProGuard. - */ - private static class PrimitiveExtension<M extends ExtendableMessageNano<M>, T> - extends Extension<M, T> { - - /** - * Tag of a piece of non-packed data from the wire compatible with this extension. - */ - private final int nonPackedTag; - - /** - * Tag of a piece of packed data from the wire compatible with this extension. - * 0 if the type of this extension is not packable. - */ - private final int packedTag; - - public PrimitiveExtension(int type, Class<T> clazz, int tag, boolean repeated, - int nonPackedTag, int packedTag) { - super(type, clazz, tag, repeated); - this.nonPackedTag = nonPackedTag; - this.packedTag = packedTag; - } - - @Override - protected Object readData(CodedInputByteBufferNano input) { - try { - return input.readPrimitiveField(type); - } catch (IOException e) { - throw new IllegalArgumentException("Error reading extension field", e); - } - } - - @Override - protected void readDataInto(UnknownFieldData data, List<Object> resultList) { - // This implementation is for primitive typed extensions, - // which can read both packed and non-packed data. - if (data.tag == nonPackedTag) { - resultList.add(readData(CodedInputByteBufferNano.newInstance(data.bytes))); - } else { - CodedInputByteBufferNano buffer = - CodedInputByteBufferNano.newInstance(data.bytes); - try { - buffer.pushLimit(buffer.readRawVarint32()); // length limit - } catch (IOException e) { - throw new IllegalArgumentException("Error reading extension field", e); - } - while (!buffer.isAtEnd()) { - resultList.add(readData(buffer)); - } - } - } - - @Override - protected final void writeSingularData(Object value, CodedOutputByteBufferNano output) { - try { - output.writeRawVarint32(tag); - switch (type) { - case TYPE_DOUBLE: - Double doubleValue = (Double) value; - output.writeDoubleNoTag(doubleValue); - break; - case TYPE_FLOAT: - Float floatValue = (Float) value; - output.writeFloatNoTag(floatValue); - break; - case TYPE_INT64: - Long int64Value = (Long) value; - output.writeInt64NoTag(int64Value); - break; - case TYPE_UINT64: - Long uint64Value = (Long) value; - output.writeUInt64NoTag(uint64Value); - break; - case TYPE_INT32: - Integer int32Value = (Integer) value; - output.writeInt32NoTag(int32Value); - break; - case TYPE_FIXED64: - Long fixed64Value = (Long) value; - output.writeFixed64NoTag(fixed64Value); - break; - case TYPE_FIXED32: - Integer fixed32Value = (Integer) value; - output.writeFixed32NoTag(fixed32Value); - break; - case TYPE_BOOL: - Boolean boolValue = (Boolean) value; - output.writeBoolNoTag(boolValue); - break; - case TYPE_STRING: - String stringValue = (String) value; - output.writeStringNoTag(stringValue); - break; - case TYPE_BYTES: - byte[] bytesValue = (byte[]) value; - output.writeBytesNoTag(bytesValue); - break; - case TYPE_UINT32: - Integer uint32Value = (Integer) value; - output.writeUInt32NoTag(uint32Value); - break; - case TYPE_ENUM: - Integer enumValue = (Integer) value; - output.writeEnumNoTag(enumValue); - break; - case TYPE_SFIXED32: - Integer sfixed32Value = (Integer) value; - output.writeSFixed32NoTag(sfixed32Value); - break; - case TYPE_SFIXED64: - Long sfixed64Value = (Long) value; - output.writeSFixed64NoTag(sfixed64Value); - break; - case TYPE_SINT32: - Integer sint32Value = (Integer) value; - output.writeSInt32NoTag(sint32Value); - break; - case TYPE_SINT64: - Long sint64Value = (Long) value; - output.writeSInt64NoTag(sint64Value); - break; - default: - throw new IllegalArgumentException("Unknown type " + type); - } - } catch (IOException e) { - // Should not happen - throw new IllegalStateException(e); - } - } - - @Override - protected void writeRepeatedData(Object array, CodedOutputByteBufferNano output) { - if (tag == nonPackedTag) { - // Use base implementation for non-packed data - super.writeRepeatedData(array, output); - } else if (tag == packedTag) { - // Packed. Note that the array element type is guaranteed to be primitive, so there - // won't be any null elements, so no null check in this block. - int arrayLength = Array.getLength(array); - int dataSize = computePackedDataSize(array); - - try { - output.writeRawVarint32(tag); - output.writeRawVarint32(dataSize); - switch (type) { - case TYPE_BOOL: - for (int i = 0; i < arrayLength; i++) { - output.writeBoolNoTag(Array.getBoolean(array, i)); - } - break; - case TYPE_FIXED32: - for (int i = 0; i < arrayLength; i++) { - output.writeFixed32NoTag(Array.getInt(array, i)); - } - break; - case TYPE_SFIXED32: - for (int i = 0; i < arrayLength; i++) { - output.writeSFixed32NoTag(Array.getInt(array, i)); - } - break; - case TYPE_FLOAT: - for (int i = 0; i < arrayLength; i++) { - output.writeFloatNoTag(Array.getFloat(array, i)); - } - break; - case TYPE_FIXED64: - for (int i = 0; i < arrayLength; i++) { - output.writeFixed64NoTag(Array.getLong(array, i)); - } - break; - case TYPE_SFIXED64: - for (int i = 0; i < arrayLength; i++) { - output.writeSFixed64NoTag(Array.getLong(array, i)); - } - break; - case TYPE_DOUBLE: - for (int i = 0; i < arrayLength; i++) { - output.writeDoubleNoTag(Array.getDouble(array, i)); - } - break; - case TYPE_INT32: - for (int i = 0; i < arrayLength; i++) { - output.writeInt32NoTag(Array.getInt(array, i)); - } - break; - case TYPE_SINT32: - for (int i = 0; i < arrayLength; i++) { - output.writeSInt32NoTag(Array.getInt(array, i)); - } - break; - case TYPE_UINT32: - for (int i = 0; i < arrayLength; i++) { - output.writeUInt32NoTag(Array.getInt(array, i)); - } - break; - case TYPE_INT64: - for (int i = 0; i < arrayLength; i++) { - output.writeInt64NoTag(Array.getLong(array, i)); - } - break; - case TYPE_SINT64: - for (int i = 0; i < arrayLength; i++) { - output.writeSInt64NoTag(Array.getLong(array, i)); - } - break; - case TYPE_UINT64: - for (int i = 0; i < arrayLength; i++) { - output.writeUInt64NoTag(Array.getLong(array, i)); - } - break; - case TYPE_ENUM: - for (int i = 0; i < arrayLength; i++) { - output.writeEnumNoTag(Array.getInt(array, i)); - } - break; - default: - throw new IllegalArgumentException("Unpackable type " + type); - } - } catch (IOException e) { - // Should not happen. - throw new IllegalStateException(e); - } - } else { - throw new IllegalArgumentException("Unexpected repeated extension tag " + tag - + ", unequal to both non-packed variant " + nonPackedTag - + " and packed variant " + packedTag); - } - } - - private int computePackedDataSize(Object array) { - int dataSize = 0; - int arrayLength = Array.getLength(array); - switch (type) { - case TYPE_BOOL: - // Bools are stored as int32 but just as 0 or 1, so 1 byte each. - dataSize = arrayLength; - break; - case TYPE_FIXED32: - case TYPE_SFIXED32: - case TYPE_FLOAT: - dataSize = arrayLength * CodedOutputByteBufferNano.LITTLE_ENDIAN_32_SIZE; - break; - case TYPE_FIXED64: - case TYPE_SFIXED64: - case TYPE_DOUBLE: - dataSize = arrayLength * CodedOutputByteBufferNano.LITTLE_ENDIAN_64_SIZE; - break; - case TYPE_INT32: - for (int i = 0; i < arrayLength; i++) { - dataSize += CodedOutputByteBufferNano.computeInt32SizeNoTag( - Array.getInt(array, i)); - } - break; - case TYPE_SINT32: - for (int i = 0; i < arrayLength; i++) { - dataSize += CodedOutputByteBufferNano.computeSInt32SizeNoTag( - Array.getInt(array, i)); - } - break; - case TYPE_UINT32: - for (int i = 0; i < arrayLength; i++) { - dataSize += CodedOutputByteBufferNano.computeUInt32SizeNoTag( - Array.getInt(array, i)); - } - break; - case TYPE_INT64: - for (int i = 0; i < arrayLength; i++) { - dataSize += CodedOutputByteBufferNano.computeInt64SizeNoTag( - Array.getLong(array, i)); - } - break; - case TYPE_SINT64: - for (int i = 0; i < arrayLength; i++) { - dataSize += CodedOutputByteBufferNano.computeSInt64SizeNoTag( - Array.getLong(array, i)); - } - break; - case TYPE_UINT64: - for (int i = 0; i < arrayLength; i++) { - dataSize += CodedOutputByteBufferNano.computeUInt64SizeNoTag( - Array.getLong(array, i)); - } - break; - case TYPE_ENUM: - for (int i = 0; i < arrayLength; i++) { - dataSize += CodedOutputByteBufferNano.computeEnumSizeNoTag( - Array.getInt(array, i)); - } - break; - default: - throw new IllegalArgumentException("Unexpected non-packable type " + type); - } - return dataSize; - } - - @Override - protected int computeRepeatedSerializedSize(Object array) { - if (tag == nonPackedTag) { - // Use base implementation for non-packed data - return super.computeRepeatedSerializedSize(array); - } else if (tag == packedTag) { - // Packed. - int dataSize = computePackedDataSize(array); - int payloadSize = - dataSize + CodedOutputByteBufferNano.computeRawVarint32Size(dataSize); - return payloadSize + CodedOutputByteBufferNano.computeRawVarint32Size(tag); - } else { - throw new IllegalArgumentException("Unexpected repeated extension tag " + tag - + ", unequal to both non-packed variant " + nonPackedTag - + " and packed variant " + packedTag); - } - } - - @Override - protected final int computeSingularSerializedSize(Object value) { - int fieldNumber = WireFormatNano.getTagFieldNumber(tag); - switch (type) { - case TYPE_DOUBLE: - Double doubleValue = (Double) value; - return CodedOutputByteBufferNano.computeDoubleSize(fieldNumber, doubleValue); - case TYPE_FLOAT: - Float floatValue = (Float) value; - return CodedOutputByteBufferNano.computeFloatSize(fieldNumber, floatValue); - case TYPE_INT64: - Long int64Value = (Long) value; - return CodedOutputByteBufferNano.computeInt64Size(fieldNumber, int64Value); - case TYPE_UINT64: - Long uint64Value = (Long) value; - return CodedOutputByteBufferNano.computeUInt64Size(fieldNumber, uint64Value); - case TYPE_INT32: - Integer int32Value = (Integer) value; - return CodedOutputByteBufferNano.computeInt32Size(fieldNumber, int32Value); - case TYPE_FIXED64: - Long fixed64Value = (Long) value; - return CodedOutputByteBufferNano.computeFixed64Size(fieldNumber, fixed64Value); - case TYPE_FIXED32: - Integer fixed32Value = (Integer) value; - return CodedOutputByteBufferNano.computeFixed32Size(fieldNumber, fixed32Value); - case TYPE_BOOL: - Boolean boolValue = (Boolean) value; - return CodedOutputByteBufferNano.computeBoolSize(fieldNumber, boolValue); - case TYPE_STRING: - String stringValue = (String) value; - return CodedOutputByteBufferNano.computeStringSize(fieldNumber, stringValue); - case TYPE_BYTES: - byte[] bytesValue = (byte[]) value; - return CodedOutputByteBufferNano.computeBytesSize(fieldNumber, bytesValue); - case TYPE_UINT32: - Integer uint32Value = (Integer) value; - return CodedOutputByteBufferNano.computeUInt32Size(fieldNumber, uint32Value); - case TYPE_ENUM: - Integer enumValue = (Integer) value; - return CodedOutputByteBufferNano.computeEnumSize(fieldNumber, enumValue); - case TYPE_SFIXED32: - Integer sfixed32Value = (Integer) value; - return CodedOutputByteBufferNano.computeSFixed32Size(fieldNumber, - sfixed32Value); - case TYPE_SFIXED64: - Long sfixed64Value = (Long) value; - return CodedOutputByteBufferNano.computeSFixed64Size(fieldNumber, - sfixed64Value); - case TYPE_SINT32: - Integer sint32Value = (Integer) value; - return CodedOutputByteBufferNano.computeSInt32Size(fieldNumber, sint32Value); - case TYPE_SINT64: - Long sint64Value = (Long) value; - return CodedOutputByteBufferNano.computeSInt64Size(fieldNumber, sint64Value); - default: - throw new IllegalArgumentException("Unknown type " + type); - } - } - } -} diff --git a/javanano/src/main/java/com/google/protobuf/nano/FieldArray.java b/javanano/src/main/java/com/google/protobuf/nano/FieldArray.java deleted file mode 100644 index b49a97fa..00000000 --- a/javanano/src/main/java/com/google/protobuf/nano/FieldArray.java +++ /dev/null @@ -1,291 +0,0 @@ -// 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.nano; - - -/** - * A custom version of {@code android.util.SparseArray} with the minimal API - * for storing {@link FieldData} objects. - * - * <p>This class is an internal implementation detail of nano and should not - * be called directly by clients. - * - * Based on {@code android.support.v4.util.SpareArrayCompat}. - */ -public final class FieldArray implements Cloneable { - private static final FieldData DELETED = new FieldData(); - private boolean mGarbage = false; - - private int[] mFieldNumbers; - private FieldData[] mData; - private int mSize; - - /** - * Creates a new FieldArray containing no fields. - */ - FieldArray() { - this(10); - } - - /** - * Creates a new FieldArray containing no mappings that will not - * require any additional memory allocation to store the specified - * number of mappings. - */ - FieldArray(int initialCapacity) { - initialCapacity = idealIntArraySize(initialCapacity); - mFieldNumbers = new int[initialCapacity]; - mData = new FieldData[initialCapacity]; - mSize = 0; - } - - /** - * Gets the FieldData mapped from the specified fieldNumber, or <code>null</code> - * if no such mapping has been made. - */ - FieldData get(int fieldNumber) { - int i = binarySearch(fieldNumber); - - if (i < 0 || mData[i] == DELETED) { - return null; - } else { - return mData[i]; - } - } - - /** - * Removes the data from the specified fieldNumber, if there was any. - */ - void remove(int fieldNumber) { - int i = binarySearch(fieldNumber); - - if (i >= 0 && mData[i] != DELETED) { - mData[i] = DELETED; - mGarbage = true; - } - } - - private void gc() { - int n = mSize; - int o = 0; - int[] keys = mFieldNumbers; - FieldData[] values = mData; - - for (int i = 0; i < n; i++) { - FieldData val = values[i]; - - if (val != DELETED) { - if (i != o) { - keys[o] = keys[i]; - values[o] = val; - values[i] = null; - } - - o++; - } - } - - mGarbage = false; - mSize = o; - } - - /** - * Adds a mapping from the specified fieldNumber to the specified data, - * replacing the previous mapping if there was one. - */ - void put(int fieldNumber, FieldData data) { - int i = binarySearch(fieldNumber); - - if (i >= 0) { - mData[i] = data; - } else { - i = ~i; - - if (i < mSize && mData[i] == DELETED) { - mFieldNumbers[i] = fieldNumber; - mData[i] = data; - return; - } - - if (mGarbage && mSize >= mFieldNumbers.length) { - gc(); - - // Search again because indices may have changed. - i = ~ binarySearch(fieldNumber); - } - - if (mSize >= mFieldNumbers.length) { - int n = idealIntArraySize(mSize + 1); - - int[] nkeys = new int[n]; - FieldData[] nvalues = new FieldData[n]; - - System.arraycopy(mFieldNumbers, 0, nkeys, 0, mFieldNumbers.length); - System.arraycopy(mData, 0, nvalues, 0, mData.length); - - mFieldNumbers = nkeys; - mData = nvalues; - } - - if (mSize - i != 0) { - System.arraycopy(mFieldNumbers, i, mFieldNumbers, i + 1, mSize - i); - System.arraycopy(mData, i, mData, i + 1, mSize - i); - } - - mFieldNumbers[i] = fieldNumber; - mData[i] = data; - mSize++; - } - } - - /** - * Returns the number of key-value mappings that this FieldArray - * currently stores. - */ - int size() { - if (mGarbage) { - gc(); - } - - return mSize; - } - - public boolean isEmpty() { - return size() == 0; - } - - /** - * Given an index in the range <code>0...size()-1</code>, returns - * the value from the <code>index</code>th key-value mapping that this - * FieldArray stores. - */ - FieldData dataAt(int index) { - if (mGarbage) { - gc(); - } - - return mData[index]; - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } - if (!(o instanceof FieldArray)) { - return false; - } - - FieldArray other = (FieldArray) o; - if (size() != other.size()) { // size() will call gc() if necessary. - return false; - } - return arrayEquals(mFieldNumbers, other.mFieldNumbers, mSize) && - arrayEquals(mData, other.mData, mSize); - } - - @Override - public int hashCode() { - if (mGarbage) { - gc(); - } - int result = 17; - for (int i = 0; i < mSize; i++) { - result = 31 * result + mFieldNumbers[i]; - result = 31 * result + mData[i].hashCode(); - } - return result; - } - - private int idealIntArraySize(int need) { - return idealByteArraySize(need * 4) / 4; - } - - private int idealByteArraySize(int need) { - for (int i = 4; i < 32; i++) - if (need <= (1 << i) - 12) - return (1 << i) - 12; - - return need; - } - - private int binarySearch(int value) { - int lo = 0; - int hi = mSize - 1; - - while (lo <= hi) { - int mid = (lo + hi) >>> 1; - int midVal = mFieldNumbers[mid]; - - if (midVal < value) { - lo = mid + 1; - } else if (midVal > value) { - hi = mid - 1; - } else { - return mid; // value found - } - } - return ~lo; // value not present - } - - private boolean arrayEquals(int[] a, int[] b, int size) { - for (int i = 0; i < size; i++) { - if (a[i] != b[i]) { - return false; - } - } - return true; - } - - private boolean arrayEquals(FieldData[] a, FieldData[] b, int size) { - for (int i = 0; i < size; i++) { - if (!a[i].equals(b[i])) { - return false; - } - } - return true; - } - - @Override - public final FieldArray clone() { - // Trigger GC so we compact and don't copy DELETED elements. - int size = size(); - FieldArray clone = new FieldArray(size); - System.arraycopy(mFieldNumbers, 0, clone.mFieldNumbers, 0, size); - for (int i = 0; i < size; i++) { - if (mData[i] != null) { - clone.mData[i] = mData[i].clone(); - } - } - clone.mSize = size; - return clone; - } -} diff --git a/javanano/src/main/java/com/google/protobuf/nano/FieldData.java b/javanano/src/main/java/com/google/protobuf/nano/FieldData.java deleted file mode 100644 index ebebabc8..00000000 --- a/javanano/src/main/java/com/google/protobuf/nano/FieldData.java +++ /dev/null @@ -1,240 +0,0 @@ -// 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.nano; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Stores unknown fields. These might be extensions or fields that the generated API doesn't - * know about yet. - */ -class FieldData implements Cloneable { - private Extension<?, ?> cachedExtension; - private Object value; - /** The serialised values for this object. Will be cleared if getValue is called */ - private List<UnknownFieldData> unknownFieldData; - - <T> FieldData(Extension<?, T> extension, T newValue) { - cachedExtension = extension; - value = newValue; - } - - FieldData() { - unknownFieldData = new ArrayList<UnknownFieldData>(); - } - - void addUnknownField(UnknownFieldData unknownField) { - unknownFieldData.add(unknownField); - } - - UnknownFieldData getUnknownField(int index) { - if (unknownFieldData == null) { - return null; - } - if (index < unknownFieldData.size()) { - return unknownFieldData.get(index); - } - return null; - } - - int getUnknownFieldSize() { - if (unknownFieldData == null) { - return 0; - } - return unknownFieldData.size(); - } - - <T> T getValue(Extension<?, T> extension) { - if (value != null){ - if (cachedExtension != extension) { // Extension objects are singletons. - throw new IllegalStateException( - "Tried to getExtension with a differernt Extension."); - } - } else { - cachedExtension = extension; - value = extension.getValueFrom(unknownFieldData); - unknownFieldData = null; - } - return (T) value; - } - - <T> void setValue(Extension<?, T> extension, T newValue) { - cachedExtension = extension; - value = newValue; - unknownFieldData = null; - } - - int computeSerializedSize() { - int size = 0; - if (value != null) { - size = cachedExtension.computeSerializedSize(value); - } else { - for (UnknownFieldData unknownField : unknownFieldData) { - size += unknownField.computeSerializedSize(); - } - } - return size; - } - - void writeTo(CodedOutputByteBufferNano output) throws IOException { - if (value != null) { - cachedExtension.writeTo(value, output); - } else { - for (UnknownFieldData unknownField : unknownFieldData) { - unknownField.writeTo(output); - } - } - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } - if (!(o instanceof FieldData)) { - return false; - } - - FieldData other = (FieldData) o; - if (value != null && other.value != null) { - // If both objects have deserialized values, compare those. - // Since unknown fields are only compared if messages have generated equals methods - // we know this will be a meaningful comparison (not identity) for all values. - if (cachedExtension != other.cachedExtension) { // Extension objects are singletons. - return false; - } - if (!cachedExtension.clazz.isArray()) { - // Can't test (!cachedExtension.repeated) due to 'bytes' -> 'byte[]' - return value.equals(other.value); - } - if (value instanceof byte[]) { - return Arrays.equals((byte[]) value, (byte[]) other.value); - } else if (value instanceof int[]) { - return Arrays.equals((int[]) value, (int[]) other.value); - } else if (value instanceof long[]) { - return Arrays.equals((long[]) value, (long[]) other.value); - } else if (value instanceof float[]) { - return Arrays.equals((float[]) value, (float[]) other.value); - } else if (value instanceof double[]) { - return Arrays.equals((double[]) value, (double[]) other.value); - } else if (value instanceof boolean[]) { - return Arrays.equals((boolean[]) value, (boolean[]) other.value); - } else { - return Arrays.deepEquals((Object[]) value, (Object[]) other.value); - } - } - if (unknownFieldData != null && other.unknownFieldData != null) { - // If both objects have byte arrays compare those directly. - return unknownFieldData.equals(other.unknownFieldData); - } - try { - // As a last resort, serialize and compare the resulting byte arrays. - return Arrays.equals(toByteArray(), other.toByteArray()); - } catch (IOException e) { - // Should not happen. - throw new IllegalStateException(e); - } - } - - @Override - public int hashCode() { - int result = 17; - try { - // The only way to generate a consistent hash is to use the serialized form. - result = 31 * result + Arrays.hashCode(toByteArray()); - } catch (IOException e) { - // Should not happen. - throw new IllegalStateException(e); - } - return result; - } - - private byte[] toByteArray() throws IOException { - byte[] result = new byte[computeSerializedSize()]; - CodedOutputByteBufferNano output = CodedOutputByteBufferNano.newInstance(result); - writeTo(output); - return result; - } - - @Override - public final FieldData clone() { - FieldData clone = new FieldData(); - try { - clone.cachedExtension = cachedExtension; - if (unknownFieldData == null) { - clone.unknownFieldData = null; - } else { - clone.unknownFieldData.addAll(unknownFieldData); - } - - // Whether we need to deep clone value depends on its type. Primitive reference types - // (e.g. Integer, Long etc.) are ok, since they're immutable. We need to clone arrays - // and messages. - if (value == null) { - // No cloning required. - } else if (value instanceof MessageNano) { - clone.value = ((MessageNano) value).clone(); - } else if (value instanceof byte[]) { - clone.value = ((byte[]) value).clone(); - } else if (value instanceof byte[][]) { - byte[][] valueArray = (byte[][]) value; - byte[][] cloneArray = new byte[valueArray.length][]; - clone.value = cloneArray; - for (int i = 0; i < valueArray.length; i++) { - cloneArray[i] = valueArray[i].clone(); - } - } else if (value instanceof boolean[]) { - clone.value = ((boolean[]) value).clone(); - } else if (value instanceof int[]) { - clone.value = ((int[]) value).clone(); - } else if (value instanceof long[]) { - clone.value = ((long[]) value).clone(); - } else if (value instanceof float[]) { - clone.value = ((float[]) value).clone(); - } else if (value instanceof double[]) { - clone.value = ((double[]) value).clone(); - } else if (value instanceof MessageNano[]) { - MessageNano[] valueArray = (MessageNano[]) value; - MessageNano[] cloneArray = new MessageNano[valueArray.length]; - clone.value = cloneArray; - for (int i = 0; i < valueArray.length; i++) { - cloneArray[i] = valueArray[i].clone(); - } - } - return clone; - } catch (CloneNotSupportedException e) { - throw new AssertionError(e); - } - } -} diff --git a/javanano/src/main/java/com/google/protobuf/nano/InternalNano.java b/javanano/src/main/java/com/google/protobuf/nano/InternalNano.java deleted file mode 100644 index 278368a0..00000000 --- a/javanano/src/main/java/com/google/protobuf/nano/InternalNano.java +++ /dev/null @@ -1,547 +0,0 @@ -// 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.nano; - -import com.google.protobuf.nano.MapFactories.MapFactory; - -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.Map; -import java.util.Map.Entry; - -/** - * The classes contained within are used internally by the Protocol Buffer - * library and generated message implementations. They are public only because - * those generated messages do not reside in the {@code protobuf} package. - * Others should not use this class directly. - * - * @author kenton@google.com (Kenton Varda) - */ -public final class InternalNano { - - public static final int TYPE_DOUBLE = 1; - public static final int TYPE_FLOAT = 2; - public static final int TYPE_INT64 = 3; - public static final int TYPE_UINT64 = 4; - public static final int TYPE_INT32 = 5; - public static final int TYPE_FIXED64 = 6; - public static final int TYPE_FIXED32 = 7; - public static final int TYPE_BOOL = 8; - public static final int TYPE_STRING = 9; - public static final int TYPE_GROUP = 10; - public static final int TYPE_MESSAGE = 11; - public static final int TYPE_BYTES = 12; - public static final int TYPE_UINT32 = 13; - public static final int TYPE_ENUM = 14; - public static final int TYPE_SFIXED32 = 15; - public static final int TYPE_SFIXED64 = 16; - public static final int TYPE_SINT32 = 17; - public static final int TYPE_SINT64 = 18; - - static final Charset UTF_8 = Charset.forName("UTF-8"); - static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); - - private InternalNano() {} - - /** - * An object to provide synchronization when lazily initializing static fields - * of {@link MessageNano} subclasses. - * <p> - * To enable earlier versions of ProGuard to inline short methods from a - * generated MessageNano subclass to the call sites, that class must not have - * a class initializer, which will be created if there is any static variable - * initializers. To lazily initialize the static variables in a thread-safe - * manner, the initialization code will synchronize on this object. - */ - public static final Object LAZY_INIT_LOCK = new Object(); - - /** - * Helper called by generated code to construct default values for string - * fields. - * <p> - * The protocol compiler does not actually contain a UTF-8 decoder -- it - * just pushes UTF-8-encoded text around without touching it. The one place - * where this presents a problem is when generating Java string literals. - * Unicode characters in the string literal would normally need to be encoded - * using a Unicode escape sequence, which would require decoding them. - * To get around this, protoc instead embeds the UTF-8 bytes into the - * generated code and leaves it to the runtime library to decode them. - * <p> - * It gets worse, though. If protoc just generated a byte array, like: - * new byte[] {0x12, 0x34, 0x56, 0x78} - * Java actually generates *code* which allocates an array and then fills - * in each value. This is much less efficient than just embedding the bytes - * directly into the bytecode. To get around this, we need another - * work-around. String literals are embedded directly, so protoc actually - * generates a string literal corresponding to the bytes. The easiest way - * to do this is to use the ISO-8859-1 character set, which corresponds to - * the first 256 characters of the Unicode range. Protoc can then use - * good old CEscape to generate the string. - * <p> - * So we have a string literal which represents a set of bytes which - * represents another string. This function -- stringDefaultValue -- - * converts from the generated string to the string we actually want. The - * generated code calls this automatically. - */ - public static String stringDefaultValue(String bytes) { - return new String(bytes.getBytes(ISO_8859_1), InternalNano.UTF_8); - } - - /** - * Helper called by generated code to construct default values for bytes - * fields. - * <p> - * This is a lot like {@link #stringDefaultValue}, but for bytes fields. - * In this case we only need the second of the two hacks -- allowing us to - * embed raw bytes as a string literal with ISO-8859-1 encoding. - */ - public static byte[] bytesDefaultValue(String bytes) { - return bytes.getBytes(ISO_8859_1); - } - - /** - * Helper function to convert a string into UTF-8 while turning the - * UnsupportedEncodingException to a RuntimeException. - */ - public static byte[] copyFromUtf8(final String text) { - return text.getBytes(InternalNano.UTF_8); - } - - /** - * Checks repeated int field equality; null-value and 0-length fields are - * considered equal. - */ - public static boolean equals(int[] field1, int[] field2) { - if (field1 == null || field1.length == 0) { - return field2 == null || field2.length == 0; - } else { - return Arrays.equals(field1, field2); - } - } - - /** - * Checks repeated long field equality; null-value and 0-length fields are - * considered equal. - */ - public static boolean equals(long[] field1, long[] field2) { - if (field1 == null || field1.length == 0) { - return field2 == null || field2.length == 0; - } else { - return Arrays.equals(field1, field2); - } - } - - /** - * Checks repeated float field equality; null-value and 0-length fields are - * considered equal. - */ - public static boolean equals(float[] field1, float[] field2) { - if (field1 == null || field1.length == 0) { - return field2 == null || field2.length == 0; - } else { - return Arrays.equals(field1, field2); - } - } - - /** - * Checks repeated double field equality; null-value and 0-length fields are - * considered equal. - */ - public static boolean equals(double[] field1, double[] field2) { - if (field1 == null || field1.length == 0) { - return field2 == null || field2.length == 0; - } else { - return Arrays.equals(field1, field2); - } - } - - /** - * Checks repeated boolean field equality; null-value and 0-length fields are - * considered equal. - */ - public static boolean equals(boolean[] field1, boolean[] field2) { - if (field1 == null || field1.length == 0) { - return field2 == null || field2.length == 0; - } else { - return Arrays.equals(field1, field2); - } - } - - /** - * Checks repeated bytes field equality. Only non-null elements are tested. - * Returns true if the two fields have the same sequence of non-null - * elements. Null-value fields and fields of any length with only null - * elements are considered equal. - */ - public static boolean equals(byte[][] field1, byte[][] field2) { - int index1 = 0; - int length1 = field1 == null ? 0 : field1.length; - int index2 = 0; - int length2 = field2 == null ? 0 : field2.length; - while (true) { - while (index1 < length1 && field1[index1] == null) { - index1++; - } - while (index2 < length2 && field2[index2] == null) { - index2++; - } - boolean atEndOf1 = index1 >= length1; - boolean atEndOf2 = index2 >= length2; - if (atEndOf1 && atEndOf2) { - // no more non-null elements to test in both arrays - return true; - } else if (atEndOf1 != atEndOf2) { - // one of the arrays have extra non-null elements - return false; - } else if (!Arrays.equals(field1[index1], field2[index2])) { - // element mismatch - return false; - } - index1++; - index2++; - } - } - - /** - * Checks repeated string/message field equality. Only non-null elements are - * tested. Returns true if the two fields have the same sequence of non-null - * elements. Null-value fields and fields of any length with only null - * elements are considered equal. - */ - public static boolean equals(Object[] field1, Object[] field2) { - int index1 = 0; - int length1 = field1 == null ? 0 : field1.length; - int index2 = 0; - int length2 = field2 == null ? 0 : field2.length; - while (true) { - while (index1 < length1 && field1[index1] == null) { - index1++; - } - while (index2 < length2 && field2[index2] == null) { - index2++; - } - boolean atEndOf1 = index1 >= length1; - boolean atEndOf2 = index2 >= length2; - if (atEndOf1 && atEndOf2) { - // no more non-null elements to test in both arrays - return true; - } else if (atEndOf1 != atEndOf2) { - // one of the arrays have extra non-null elements - return false; - } else if (!field1[index1].equals(field2[index2])) { - // element mismatch - return false; - } - index1++; - index2++; - } - } - - /** - * Computes the hash code of a repeated int field. Null-value and 0-length - * fields have the same hash code. - */ - public static int hashCode(int[] field) { - return field == null || field.length == 0 ? 0 : Arrays.hashCode(field); - } - - /** - * Computes the hash code of a repeated long field. Null-value and 0-length - * fields have the same hash code. - */ - public static int hashCode(long[] field) { - return field == null || field.length == 0 ? 0 : Arrays.hashCode(field); - } - - /** - * Computes the hash code of a repeated float field. Null-value and 0-length - * fields have the same hash code. - */ - public static int hashCode(float[] field) { - return field == null || field.length == 0 ? 0 : Arrays.hashCode(field); - } - - /** - * Computes the hash code of a repeated double field. Null-value and 0-length - * fields have the same hash code. - */ - public static int hashCode(double[] field) { - return field == null || field.length == 0 ? 0 : Arrays.hashCode(field); - } - - /** - * Computes the hash code of a repeated boolean field. Null-value and 0-length - * fields have the same hash code. - */ - public static int hashCode(boolean[] field) { - return field == null || field.length == 0 ? 0 : Arrays.hashCode(field); - } - - /** - * Computes the hash code of a repeated bytes field. Only the sequence of all - * non-null elements are used in the computation. Null-value fields and fields - * of any length with only null elements have the same hash code. - */ - public static int hashCode(byte[][] field) { - int result = 0; - for (int i = 0, size = field == null ? 0 : field.length; i < size; i++) { - byte[] element = field[i]; - if (element != null) { - result = 31 * result + Arrays.hashCode(element); - } - } - return result; - } - - /** - * Computes the hash code of a repeated string/message field. Only the - * sequence of all non-null elements are used in the computation. Null-value - * fields and fields of any length with only null elements have the same hash - * code. - */ - public static int hashCode(Object[] field) { - int result = 0; - for (int i = 0, size = field == null ? 0 : field.length; i < size; i++) { - Object element = field[i]; - if (element != null) { - result = 31 * result + element.hashCode(); - } - } - return result; - } - private static Object primitiveDefaultValue(int type) { - switch (type) { - case TYPE_BOOL: - return Boolean.FALSE; - case TYPE_BYTES: - return WireFormatNano.EMPTY_BYTES; - case TYPE_STRING: - return ""; - case TYPE_FLOAT: - return Float.valueOf(0); - case TYPE_DOUBLE: - return Double.valueOf(0); - case TYPE_ENUM: - case TYPE_FIXED32: - case TYPE_INT32: - case TYPE_UINT32: - case TYPE_SINT32: - case TYPE_SFIXED32: - return Integer.valueOf(0); - case TYPE_INT64: - case TYPE_UINT64: - case TYPE_SINT64: - case TYPE_FIXED64: - case TYPE_SFIXED64: - return Long.valueOf(0L); - case TYPE_MESSAGE: - case TYPE_GROUP: - default: - throw new IllegalArgumentException( - "Type: " + type + " is not a primitive type."); - } - } - - /** - * Merges the map entry into the map field. Note this is only supposed to - * be called by generated messages. - * - * @param map the map field; may be null, in which case a map will be - * instantiated using the {@link MapFactories.MapFactory} - * @param input the input byte buffer - * @param keyType key type, as defined in InternalNano.TYPE_* - * @param valueType value type, as defined in InternalNano.TYPE_* - * @param value an new instance of the value, if the value is a TYPE_MESSAGE; - * otherwise this parameter can be null and will be ignored. - * @param keyTag wire tag for the key - * @param valueTag wire tag for the value - * @return the map field - * @throws IOException - */ - @SuppressWarnings("unchecked") - public static final <K, V> Map<K, V> mergeMapEntry( - CodedInputByteBufferNano input, - Map<K, V> map, - MapFactory mapFactory, - int keyType, - int valueType, - V value, - int keyTag, - int valueTag) throws IOException { - map = mapFactory.forMap(map); - final int length = input.readRawVarint32(); - final int oldLimit = input.pushLimit(length); - K key = null; - while (true) { - int tag = input.readTag(); - if (tag == 0) { - break; - } - if (tag == keyTag) { - key = (K) input.readPrimitiveField(keyType); - } else if (tag == valueTag) { - if (valueType == TYPE_MESSAGE) { - input.readMessage((MessageNano) value); - } else { - value = (V) input.readPrimitiveField(valueType); - } - } else { - if (!input.skipField(tag)) { - break; - } - } - } - input.checkLastTagWas(0); - input.popLimit(oldLimit); - - if (key == null) { - // key can only be primitive types. - key = (K) primitiveDefaultValue(keyType); - } - - if (value == null) { - // message type value will be initialized by code-gen. - value = (V) primitiveDefaultValue(valueType); - } - - map.put(key, value); - return map; - } - - public static <K, V> void serializeMapField( - CodedOutputByteBufferNano output, - Map<K, V> map, int number, int keyType, int valueType) - throws IOException { - for (Entry<K, V> entry: map.entrySet()) { - K key = entry.getKey(); - V value = entry.getValue(); - if (key == null || value == null) { - throw new IllegalStateException( - "keys and values in maps cannot be null"); - } - int entrySize = - CodedOutputByteBufferNano.computeFieldSize(1, keyType, key) + - CodedOutputByteBufferNano.computeFieldSize(2, valueType, value); - output.writeTag(number, WireFormatNano.WIRETYPE_LENGTH_DELIMITED); - output.writeRawVarint32(entrySize); - output.writeField(1, keyType, key); - output.writeField(2, valueType, value); - } - } - - public static <K, V> int computeMapFieldSize( - Map<K, V> map, int number, int keyType, int valueType) { - int size = 0; - int tagSize = CodedOutputByteBufferNano.computeTagSize(number); - for (Entry<K, V> entry: map.entrySet()) { - K key = entry.getKey(); - V value = entry.getValue(); - if (key == null || value == null) { - throw new IllegalStateException( - "keys and values in maps cannot be null"); - } - int entrySize = - CodedOutputByteBufferNano.computeFieldSize(1, keyType, key) + - CodedOutputByteBufferNano.computeFieldSize(2, valueType, value); - size += tagSize + entrySize - + CodedOutputByteBufferNano.computeRawVarint32Size(entrySize); - } - return size; - } - - /** - * Checks whether two {@link Map} are equal. We don't use the default equals - * method of {@link Map} because it compares by identity not by content for - * byte arrays. - */ - public static <K, V> boolean equals(Map<K, V> a, Map<K, V> b) { - if (a == b) { - return true; - } - if (a == null) { - return b.size() == 0; - } - if (b == null) { - return a.size() == 0; - } - if (a.size() != b.size()) { - return false; - } - for (Entry<K, V> entry : a.entrySet()) { - if (!b.containsKey(entry.getKey())) { - return false; - } - if (!equalsMapValue(entry.getValue(), b.get(entry.getKey()))) { - return false; - } - } - return true; - } - - private static boolean equalsMapValue(Object a, Object b) { - if (a == null || b == null) { - throw new IllegalStateException( - "keys and values in maps cannot be null"); - } - if (a instanceof byte[] && b instanceof byte[]) { - return Arrays.equals((byte[]) a, (byte[]) b); - } - return a.equals(b); - } - - public static <K, V> int hashCode(Map<K, V> map) { - if (map == null) { - return 0; - } - int result = 0; - for (Entry<K, V> entry : map.entrySet()) { - result += hashCodeForMap(entry.getKey()) - ^ hashCodeForMap(entry.getValue()); - } - return result; - } - - private static int hashCodeForMap(Object o) { - if (o instanceof byte[]) { - return Arrays.hashCode((byte[]) o); - } - return o.hashCode(); - } - - // This avoids having to make FieldArray public. - public static void cloneUnknownFieldData(ExtendableMessageNano original, - ExtendableMessageNano cloned) { - if (original.unknownFieldData != null) { - cloned.unknownFieldData = (FieldArray) original.unknownFieldData.clone(); - } - } -} diff --git a/javanano/src/main/java/com/google/protobuf/nano/InvalidProtocolBufferNanoException.java b/javanano/src/main/java/com/google/protobuf/nano/InvalidProtocolBufferNanoException.java deleted file mode 100644 index 9a83d6d3..00000000 --- a/javanano/src/main/java/com/google/protobuf/nano/InvalidProtocolBufferNanoException.java +++ /dev/null @@ -1,93 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2013 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.nano; - -import java.io.IOException; - -/** - * Thrown when a protocol message being parsed is invalid in some way, - * e.g. it contains a malformed varint or a negative byte length. - * - * @author kenton@google.com Kenton Varda - */ -public class InvalidProtocolBufferNanoException extends IOException { - private static final long serialVersionUID = -1616151763072450476L; - - public InvalidProtocolBufferNanoException(final String description) { - super(description); - } - - static InvalidProtocolBufferNanoException truncatedMessage() { - return new InvalidProtocolBufferNanoException( - "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."); - } - - static InvalidProtocolBufferNanoException negativeSize() { - return new InvalidProtocolBufferNanoException( - "CodedInputStream encountered an embedded string or message " + - "which claimed to have negative size."); - } - - static InvalidProtocolBufferNanoException malformedVarint() { - return new InvalidProtocolBufferNanoException( - "CodedInputStream encountered a malformed varint."); - } - - static InvalidProtocolBufferNanoException invalidTag() { - return new InvalidProtocolBufferNanoException( - "Protocol message contained an invalid tag (zero)."); - } - - static InvalidProtocolBufferNanoException invalidEndTag() { - return new InvalidProtocolBufferNanoException( - "Protocol message end-group tag did not match expected tag."); - } - - static InvalidProtocolBufferNanoException invalidWireType() { - return new InvalidProtocolBufferNanoException( - "Protocol message tag had invalid wire type."); - } - - static InvalidProtocolBufferNanoException recursionLimitExceeded() { - return new InvalidProtocolBufferNanoException( - "Protocol message had too many levels of nesting. May be malicious. " + - "Use CodedInputStream.setRecursionLimit() to increase the depth limit."); - } - - static InvalidProtocolBufferNanoException sizeLimitExceeded() { - return new InvalidProtocolBufferNanoException( - "Protocol message was too large. May be malicious. " + - "Use CodedInputStream.setSizeLimit() to increase the size limit."); - } -} diff --git a/javanano/src/main/java/com/google/protobuf/nano/MapFactories.java b/javanano/src/main/java/com/google/protobuf/nano/MapFactories.java deleted file mode 100644 index 98fa4877..00000000 --- a/javanano/src/main/java/com/google/protobuf/nano/MapFactories.java +++ /dev/null @@ -1,67 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2013 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.nano; - -import java.util.HashMap; -import java.util.Map; - -/** - * Utility class for maps support. - */ -public final class MapFactories { - public static interface MapFactory { - <K, V> Map<K, V> forMap(Map<K, V> oldMap); - } - - // NOTE(liujisi): The factory setter is temporarily marked as package private. - // The way to provide customized implementations of maps for different - // platforms are still under discussion. Mark it as private to avoid exposing - // the API in proto3 alpha release. - /* public */ static void setMapFactory(MapFactory newMapFactory) { - mapFactory = newMapFactory; - } - - public static MapFactory getMapFactory() { - return mapFactory; - } - - private static class DefaultMapFactory implements MapFactory { - public <K, V> Map<K, V> forMap(Map<K, V> oldMap) { - if (oldMap == null) { - return new HashMap<K, V>(); - } - return oldMap; - } - } - private static volatile MapFactory mapFactory = new DefaultMapFactory(); - - private MapFactories() {} -} diff --git a/javanano/src/main/java/com/google/protobuf/nano/MessageNano.java b/javanano/src/main/java/com/google/protobuf/nano/MessageNano.java deleted file mode 100644 index 23475027..00000000 --- a/javanano/src/main/java/com/google/protobuf/nano/MessageNano.java +++ /dev/null @@ -1,198 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2013 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.nano; - -import java.io.IOException; -import java.util.Arrays; - -/** - * Abstract interface implemented by Protocol Message objects. - * - * @author wink@google.com Wink Saville - */ -public abstract class MessageNano { - protected volatile int cachedSize = -1; - - /** - * Get the number of bytes required to encode this message. - * Returns the cached size or calls getSerializedSize which - * sets the cached size. This is used internally when serializing - * so the size is only computed once. If a member is modified - * then this could be stale call getSerializedSize if in doubt. - */ - public int getCachedSize() { - if (cachedSize < 0) { - // getSerializedSize sets cachedSize - getSerializedSize(); - } - return cachedSize; - } - - /** - * Computes the number of bytes required to encode this message. - * The size is cached and the cached result can be retrieved - * using getCachedSize(). - */ - public int getSerializedSize() { - int size = computeSerializedSize(); - cachedSize = size; - return size; - } - - /** - * Computes the number of bytes required to encode this message. This does not update the - * cached size. - */ - protected int computeSerializedSize() { - // This is overridden if the generated message has serialized fields. - return 0; - } - - /** - * Serializes the message and writes it to {@code output}. - * - * @param output the output to receive the serialized form. - * @throws IOException if an error occurred writing to {@code output}. - */ - public void writeTo(CodedOutputByteBufferNano output) throws IOException { - // Does nothing by default. Overridden by subclasses which have data to write. - } - - /** - * Parse {@code input} as a message of this type and merge it with the - * message being built. - */ - public abstract MessageNano mergeFrom(CodedInputByteBufferNano input) throws IOException; - - /** - * Serialize to a byte array. - * @return byte array with the serialized data. - */ - public static final byte[] toByteArray(MessageNano msg) { - final byte[] result = new byte[msg.getSerializedSize()]; - toByteArray(msg, result, 0, result.length); - return result; - } - - /** - * Serialize to a byte array starting at offset through length. The - * method getSerializedSize must have been called prior to calling - * this method so the proper length is know. If an attempt to - * write more than length bytes OutOfSpaceException will be thrown - * and if length bytes are not written then IllegalStateException - * is thrown. - */ - public static final void toByteArray(MessageNano msg, byte[] data, int offset, int length) { - try { - final CodedOutputByteBufferNano output = - CodedOutputByteBufferNano.newInstance(data, offset, length); - msg.writeTo(output); - output.checkNoSpaceLeft(); - } catch (IOException e) { - throw new RuntimeException("Serializing to a byte array threw an IOException " - + "(should never happen).", e); - } - } - - /** - * Parse {@code data} as a message of this type and merge it with the - * message being built. - */ - public static final <T extends MessageNano> T mergeFrom(T msg, final byte[] data) - throws InvalidProtocolBufferNanoException { - return mergeFrom(msg, data, 0, data.length); - } - - /** - * Parse {@code data} as a message of this type and merge it with the - * message being built. - */ - public static final <T extends MessageNano> T mergeFrom(T msg, final byte[] data, - final int off, final int len) throws InvalidProtocolBufferNanoException { - try { - final CodedInputByteBufferNano input = - CodedInputByteBufferNano.newInstance(data, off, len); - msg.mergeFrom(input); - input.checkLastTagWas(0); - return msg; - } catch (InvalidProtocolBufferNanoException e) { - throw e; - } catch (IOException e) { - throw new RuntimeException("Reading from a byte array threw an IOException (should " - + "never happen)."); - } - } - - /** - * Compares two {@code MessageNano}s and returns true if the message's are the same class and - * have serialized form equality (i.e. all of the field values are the same). - */ - public static final boolean messageNanoEquals(MessageNano a, MessageNano b) { - if (a == b) { - return true; - } - if (a == null || b == null) { - return false; - } - if (a.getClass() != b.getClass()) { - return false; - } - final int serializedSize = a.getSerializedSize(); - if (b.getSerializedSize() != serializedSize) { - return false; - } - final byte[] aByteArray = new byte[serializedSize]; - final byte[] bByteArray = new byte[serializedSize]; - toByteArray(a, aByteArray, 0, serializedSize); - toByteArray(b, bByteArray, 0, serializedSize); - return Arrays.equals(aByteArray, bByteArray); - } - - /** - * Returns a string that is (mostly) compatible with ProtoBuffer's TextFormat. Note that groups - * (which are deprecated) are not serialized with the correct field name. - * - * <p>This is implemented using reflection, so it is not especially fast nor is it guaranteed - * to find all fields if you have method removal turned on for proguard. - */ - @Override - public String toString() { - return MessageNanoPrinter.print(this); - } - - /** - * Provides support for cloning. This only works if you specify the generate_clone method. - */ - @Override - public MessageNano clone() throws CloneNotSupportedException { - return (MessageNano) super.clone(); - } -} diff --git a/javanano/src/main/java/com/google/protobuf/nano/MessageNanoPrinter.java b/javanano/src/main/java/com/google/protobuf/nano/MessageNanoPrinter.java deleted file mode 100644 index 5f329f02..00000000 --- a/javanano/src/main/java/com/google/protobuf/nano/MessageNanoPrinter.java +++ /dev/null @@ -1,275 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2013 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.nano; - -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Map; - -/** - * Static helper methods for printing nano protos. - * - * @author flynn@google.com Andrew Flynn - */ -public final class MessageNanoPrinter { - // Do not allow instantiation - private MessageNanoPrinter() {} - - private static final String INDENT = " "; - private static final int MAX_STRING_LEN = 200; - - /** - * Returns an text representation of a MessageNano suitable for debugging. The returned string - * is mostly compatible with Protocol Buffer's TextFormat (as provided by non-nano protocol - * buffers) -- groups (which are deprecated) are output with an underscore name (e.g. foo_bar - * instead of FooBar) and will thus not parse. - * - * <p>Employs Java reflection on the given object and recursively prints primitive fields, - * groups, and messages.</p> - */ - public static <T extends MessageNano> String print(T message) { - if (message == null) { - return ""; - } - - StringBuffer buf = new StringBuffer(); - try { - print(null, message, new StringBuffer(), buf); - } catch (IllegalAccessException e) { - return "Error printing proto: " + e.getMessage(); - } catch (InvocationTargetException e) { - return "Error printing proto: " + e.getMessage(); - } - return buf.toString(); - } - - /** - * Function that will print the given message/field into the StringBuffer. - * Meant to be called recursively. - * - * @param identifier the identifier to use, or {@code null} if this is the root message to - * print. - * @param object the value to print. May in fact be a primitive value or byte array and not a - * message. - * @param indentBuf the indentation each line should begin with. - * @param buf the output buffer. - */ - private static void print(String identifier, Object object, - StringBuffer indentBuf, StringBuffer buf) throws IllegalAccessException, - InvocationTargetException { - if (object == null) { - // This can happen if... - // - we're about to print a message, String, or byte[], but it not present; - // - we're about to print a primitive, but "reftype" optional style is enabled, and - // the field is unset. - // In both cases the appropriate behavior is to output nothing. - } else if (object instanceof MessageNano) { // Nano proto message - int origIndentBufLength = indentBuf.length(); - if (identifier != null) { - buf.append(indentBuf).append(deCamelCaseify(identifier)).append(" <\n"); - indentBuf.append(INDENT); - } - Class<?> clazz = object.getClass(); - - // Proto fields follow one of two formats: - // - // 1) Public, non-static variables that do not begin or end with '_' - // Find and print these using declared public fields - for (Field field : clazz.getFields()) { - int modifiers = field.getModifiers(); - String fieldName = field.getName(); - if ("cachedSize".equals(fieldName)) { - // TODO(bduff): perhaps cachedSize should have a more obscure name. - continue; - } - - if ((modifiers & Modifier.PUBLIC) == Modifier.PUBLIC - && (modifiers & Modifier.STATIC) != Modifier.STATIC - && !fieldName.startsWith("_") - && !fieldName.endsWith("_")) { - Class<?> fieldType = field.getType(); - Object value = field.get(object); - - if (fieldType.isArray()) { - Class<?> arrayType = fieldType.getComponentType(); - - // bytes is special since it's not repeated, but is represented by an array - if (arrayType == byte.class) { - print(fieldName, value, indentBuf, buf); - } else { - int len = value == null ? 0 : Array.getLength(value); - for (int i = 0; i < len; i++) { - Object elem = Array.get(value, i); - print(fieldName, elem, indentBuf, buf); - } - } - } else { - print(fieldName, value, indentBuf, buf); - } - } - } - - // 2) Fields that are accessed via getter methods (when accessors - // mode is turned on) - // Find and print these using getter methods. - for (Method method : clazz.getMethods()) { - String name = method.getName(); - // Check for the setter accessor method since getters and hazzers both have - // non-proto-field name collisions (hashCode() and getSerializedSize()) - if (name.startsWith("set")) { - String subfieldName = name.substring(3); - - Method hazzer = null; - try { - hazzer = clazz.getMethod("has" + subfieldName); - } catch (NoSuchMethodException e) { - continue; - } - // If hazzer doesn't exist or returns false, no need to continue - if (!(Boolean) hazzer.invoke(object)) { - continue; - } - - Method getter = null; - try { - getter = clazz.getMethod("get" + subfieldName); - } catch (NoSuchMethodException e) { - continue; - } - - print(subfieldName, getter.invoke(object), indentBuf, buf); - } - } - if (identifier != null) { - indentBuf.setLength(origIndentBufLength); - buf.append(indentBuf).append(">\n"); - } - } else if (object instanceof Map) { - Map<?,?> map = (Map<?,?>) object; - identifier = deCamelCaseify(identifier); - - for (Map.Entry<?,?> entry : map.entrySet()) { - buf.append(indentBuf).append(identifier).append(" <\n"); - int origIndentBufLength = indentBuf.length(); - indentBuf.append(INDENT); - print("key", entry.getKey(), indentBuf, buf); - print("value", entry.getValue(), indentBuf, buf); - indentBuf.setLength(origIndentBufLength); - buf.append(indentBuf).append(">\n"); - } - } else { - // Non-null primitive value - identifier = deCamelCaseify(identifier); - buf.append(indentBuf).append(identifier).append(": "); - if (object instanceof String) { - String stringMessage = sanitizeString((String) object); - buf.append("\"").append(stringMessage).append("\""); - } else if (object instanceof byte[]) { - appendQuotedBytes((byte[]) object, buf); - } else { - buf.append(object); - } - buf.append("\n"); - } - } - - /** - * Converts an identifier of the format "FieldName" into "field_name". - */ - private static String deCamelCaseify(String identifier) { - StringBuffer out = new StringBuffer(); - for (int i = 0; i < identifier.length(); i++) { - char currentChar = identifier.charAt(i); - if (i == 0) { - out.append(Character.toLowerCase(currentChar)); - } else if (Character.isUpperCase(currentChar)) { - out.append('_').append(Character.toLowerCase(currentChar)); - } else { - out.append(currentChar); - } - } - return out.toString(); - } - - /** - * Shortens and escapes the given string. - */ - private static String sanitizeString(String str) { - if (!str.startsWith("http") && str.length() > MAX_STRING_LEN) { - // Trim non-URL strings. - str = str.substring(0, MAX_STRING_LEN) + "[...]"; - } - return escapeString(str); - } - - /** - * Escape everything except for low ASCII code points. - */ - private static String escapeString(String str) { - int strLen = str.length(); - StringBuilder b = new StringBuilder(strLen); - for (int i = 0; i < strLen; i++) { - char original = str.charAt(i); - if (original >= ' ' && original <= '~' && original != '"' && original != '\'') { - b.append(original); - } else { - b.append(String.format("\\u%04x", (int) original)); - } - } - return b.toString(); - } - - /** - * Appends a quoted byte array to the provided {@code StringBuffer}. - */ - private static void appendQuotedBytes(byte[] bytes, StringBuffer builder) { - if (bytes == null) { - builder.append("\"\""); - return; - } - - builder.append('"'); - for (int i = 0; i < bytes.length; ++i) { - int ch = bytes[i] & 0xff; - if (ch == '\\' || ch == '"') { - builder.append('\\').append((char) ch); - } else if (ch >= 32 && ch < 127) { - builder.append((char) ch); - } else { - builder.append(String.format("\\%03o", ch)); - } - } - builder.append('"'); - } -} diff --git a/javanano/src/main/java/com/google/protobuf/nano/UnknownFieldData.java b/javanano/src/main/java/com/google/protobuf/nano/UnknownFieldData.java deleted file mode 100644 index b1678d1b..00000000 --- a/javanano/src/main/java/com/google/protobuf/nano/UnknownFieldData.java +++ /dev/null @@ -1,88 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2013 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.nano; - -import java.io.IOException; -import java.util.Arrays; - -/** - * Stores unknown fields. These might be extensions or fields that the generated - * API doesn't know about yet. - * - * @author bduff@google.com (Brian Duff) - */ -final class UnknownFieldData { - - final int tag; - /** - * Important: this should be treated as immutable, even though it's possible - * to change the array values. - */ - final byte[] bytes; - - UnknownFieldData(int tag, byte[] bytes) { - this.tag = tag; - this.bytes = bytes; - } - - int computeSerializedSize() { - int size = 0; - size += CodedOutputByteBufferNano.computeRawVarint32Size(tag); - size += bytes.length; - return size; - } - - void writeTo(CodedOutputByteBufferNano output) throws IOException { - output.writeRawVarint32(tag); - output.writeRawBytes(bytes); - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } - if (!(o instanceof UnknownFieldData)) { - return false; - } - - UnknownFieldData other = (UnknownFieldData) o; - return tag == other.tag && Arrays.equals(bytes, other.bytes); - } - - @Override - public int hashCode() { - int result = 17; - result = 31 * result + tag; - result = 31 * result + Arrays.hashCode(bytes); - return result; - } -} diff --git a/javanano/src/main/java/com/google/protobuf/nano/WireFormatNano.java b/javanano/src/main/java/com/google/protobuf/nano/WireFormatNano.java deleted file mode 100644 index bbb6370a..00000000 --- a/javanano/src/main/java/com/google/protobuf/nano/WireFormatNano.java +++ /dev/null @@ -1,124 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2013 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.nano; - -import java.io.IOException; - -/** - * This class is used internally by the Protocol Buffer library and generated - * message implementations. It is public only because those generated messages - * do not reside in the {@code protobuf} package. Others should not use this - * class directly. - * - * This class contains constants and helper functions useful for dealing with - * the Protocol Buffer wire format. - * - * @author kenton@google.com Kenton Varda - */ -public final class WireFormatNano { - // Do not allow instantiation. - private WireFormatNano() {} - - static final int WIRETYPE_VARINT = 0; - static final int WIRETYPE_FIXED64 = 1; - static final int WIRETYPE_LENGTH_DELIMITED = 2; - static final int WIRETYPE_START_GROUP = 3; - static final int WIRETYPE_END_GROUP = 4; - static final int WIRETYPE_FIXED32 = 5; - - static final int TAG_TYPE_BITS = 3; - static final int TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1; - - /** Given a tag value, determines the wire type (the lower 3 bits). */ - static int getTagWireType(final int tag) { - return tag & TAG_TYPE_MASK; - } - - /** Given a tag value, determines the field number (the upper 29 bits). */ - public static int getTagFieldNumber(final int tag) { - return tag >>> TAG_TYPE_BITS; - } - - /** Makes a tag value given a field number and wire type. */ - static int makeTag(final int fieldNumber, final int wireType) { - return (fieldNumber << TAG_TYPE_BITS) | wireType; - } - - public static final int EMPTY_INT_ARRAY[] = {}; - public static final long EMPTY_LONG_ARRAY[] = {}; - public static final float EMPTY_FLOAT_ARRAY[] = {}; - public static final double EMPTY_DOUBLE_ARRAY[] = {}; - public static final boolean EMPTY_BOOLEAN_ARRAY[] = {}; - public static final String EMPTY_STRING_ARRAY[] = {}; - public static final byte[] EMPTY_BYTES_ARRAY[] = {}; - public static final byte[] EMPTY_BYTES = {}; - - /** - * Parses an unknown field. This implementation skips the field. - * - * <p>Generated messages will call this for unknown fields if the store_unknown_fields - * option is off. - * - * @return {@literal true} unless the tag is an end-group tag. - */ - public static boolean parseUnknownField( - final CodedInputByteBufferNano input, - final int tag) throws IOException { - return input.skipField(tag); - } - - /** - * Computes the array length of a repeated field. We assume that in the common case repeated - * fields are contiguously serialized but we still correctly handle interspersed values of a - * repeated field (but with extra allocations). - * - * Rewinds to current input position before returning. - * - * @param input stream input, pointing to the byte after the first tag - * @param tag repeated field tag just read - * @return length of array - * @throws IOException - */ - public static final int getRepeatedFieldArrayLength( - final CodedInputByteBufferNano input, - final int tag) throws IOException { - int arrayLength = 1; - int startPos = input.getPosition(); - input.skipField(tag); - while (input.readTag() == tag) { - input.skipField(tag); - arrayLength++; - } - input.rewindToPosition(startPos); - return arrayLength; - } - -} diff --git a/javanano/src/test/java/com/google/protobuf/nano/NanoTest.java b/javanano/src/test/java/com/google/protobuf/nano/NanoTest.java deleted file mode 100644 index 4d6e7f09..00000000 --- a/javanano/src/test/java/com/google/protobuf/nano/NanoTest.java +++ /dev/null @@ -1,4471 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2013 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.nano; - -import com.google.protobuf.nano.CodedOutputByteBufferNano; -import com.google.protobuf.nano.EnumClassNanos.EnumClassNano; -import com.google.protobuf.nano.EnumClassNanos.EnumClassNano.MessageScopeEnum; -import com.google.protobuf.nano.EnumClassNanos.FileScopeEnum; -import com.google.protobuf.nano.MapTestProto.TestMap; -import com.google.protobuf.nano.MapTestProto.TestMap.MessageValue; -import com.google.protobuf.nano.NanoAccessorsOuterClass.TestNanoAccessors; -import com.google.protobuf.nano.NanoHasOuterClass.TestAllTypesNanoHas; -import com.google.protobuf.nano.NanoOuterClass.TestAllTypesNano; -import com.google.protobuf.nano.UnittestRecursiveNano.RecursiveMessageNano; -import com.google.protobuf.nano.NanoReferenceTypesCompat; -import com.google.protobuf.nano.UnittestSimpleNano.SimpleMessageNano; -import com.google.protobuf.nano.UnittestSingleNano.SingleMessageNano; -import com.google.protobuf.nano.testext.nano.Extensions; -import com.google.protobuf.nano.testext.nano.Extensions.AnotherMessage; -import com.google.protobuf.nano.testext.nano.Extensions.MessageWithGroup; -import com.google.protobuf.nano.testimport.nano.UnittestImportNano; - -import junit.framework.TestCase; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.TreeMap; - -/** - * Test nano runtime. - * - * @author ulas@google.com Ulas Kirazci - */ -public class NanoTest extends TestCase { - @Override - public void setUp() throws Exception { - } - - public void testSimpleMessageNano() throws Exception { - SimpleMessageNano msg = new SimpleMessageNano(); - assertEquals(123, msg.d); - assertEquals(null, msg.nestedMsg); - assertEquals(SimpleMessageNano.BAZ, msg.defaultNestedEnum); - - msg.d = 456; - assertEquals(456, msg.d); - - SimpleMessageNano.NestedMessage nestedMsg = new SimpleMessageNano.NestedMessage(); - nestedMsg.bb = 2; - assertEquals(2, nestedMsg.bb); - msg.nestedMsg = nestedMsg; - assertEquals(2, msg.nestedMsg.bb); - - msg.defaultNestedEnum = SimpleMessageNano.BAR; - assertEquals(SimpleMessageNano.BAR, msg.defaultNestedEnum); - - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 9); - assertEquals(result.length, msgSerializedSize); - - SimpleMessageNano newMsg = SimpleMessageNano.parseFrom(result); - assertEquals(456, newMsg.d); - assertEquals(2, msg.nestedMsg.bb); - assertEquals(SimpleMessageNano.BAR, msg.defaultNestedEnum); - - msg.nestedMsg = null; - assertTrue(msgSerializedSize != msg.getSerializedSize()); - - msg.clear(); - assertEquals(0, msg.getSerializedSize()); - } - - public void testRecursiveMessageNano() throws Exception { - RecursiveMessageNano msg = new RecursiveMessageNano(); - assertTrue(msg.repeatedRecursiveMessageNano.length == 0); - - RecursiveMessageNano msg1 = new RecursiveMessageNano(); - msg1.id = 1; - assertEquals(1, msg1.id); - RecursiveMessageNano msg2 = new RecursiveMessageNano(); - msg2.id = 2; - RecursiveMessageNano msg3 = new RecursiveMessageNano(); - msg3.id = 3; - - RecursiveMessageNano.NestedMessage nestedMsg = new RecursiveMessageNano.NestedMessage(); - nestedMsg.a = msg1; - assertEquals(1, nestedMsg.a.id); - - msg.id = 0; - msg.nestedMessage = nestedMsg; - msg.optionalRecursiveMessageNano = msg2; - msg.repeatedRecursiveMessageNano = new RecursiveMessageNano[] { msg3 }; - - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 16); - assertEquals(result.length, msgSerializedSize); - - RecursiveMessageNano newMsg = RecursiveMessageNano.parseFrom(result); - assertEquals(1, newMsg.repeatedRecursiveMessageNano.length); - - assertEquals(0, newMsg.id); - assertEquals(1, newMsg.nestedMessage.a.id); - assertEquals(2, newMsg.optionalRecursiveMessageNano.id); - assertEquals(3, newMsg.repeatedRecursiveMessageNano[0].id); - } - - public void testMessageNoFields() { - SingleMessageNano msg = new SingleMessageNano(); - assertEquals(0, msg.getSerializedSize()); - assertEquals(0, MessageNano.toByteArray(msg).length); - } - - public void testNanoRequiredInt32() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.id = 123; - assertEquals(123, msg.id); - msg.clear().id = 456; - assertEquals(456, msg.id); - msg.clear(); - - msg.id = 123; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 3); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(123, newMsg.id); - } - - public void testNanoOptionalInt32() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalInt32 = 123; - assertEquals(123, msg.optionalInt32); - msg.clear() - .optionalInt32 = 456; - assertEquals(456, msg.optionalInt32); - msg.clear(); - - msg.optionalInt32 = 123; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 5); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(123, newMsg.optionalInt32); - } - - public void testNanoOptionalInt64() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalInt64 = 123; - assertEquals(123, msg.optionalInt64); - msg.clear() - .optionalInt64 = 456; - assertEquals(456, msg.optionalInt64); - msg.clear(); - assertEquals(0, msg.optionalInt64); - - msg.optionalInt64 = 123; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 5); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(123, newMsg.optionalInt64); - } - - public void testNanoOptionalUint32() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalUint32 = 123; - assertEquals(123, msg.optionalUint32); - msg.clear() - .optionalUint32 = 456; - assertEquals(456, msg.optionalUint32); - msg.clear(); - assertEquals(0, msg.optionalUint32); - - msg.optionalUint32 = 123; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 5); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(123, newMsg.optionalUint32); - } - - public void testNanoOptionalUint64() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalUint64 = 123; - assertEquals(123, msg.optionalUint64); - msg.clear() - .optionalUint64 = 456; - assertEquals(456, msg.optionalUint64); - msg.clear(); - assertEquals(0, msg.optionalUint64); - - msg.optionalUint64 = 123; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 5); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(123, newMsg.optionalUint64); - } - - public void testNanoOptionalSint32() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalSint32 = 123; - assertEquals(123, msg.optionalSint32); - msg.clear() - .optionalSint32 = 456; - assertEquals(456, msg.optionalSint32); - msg.clear(); - assertEquals(0, msg.optionalSint32); - - msg.optionalSint32 = -123; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(-123, newMsg.optionalSint32); - } - - public void testNanoOptionalSint64() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalSint64 = 123; - assertEquals(123, msg.optionalSint64); - msg.clear() - .optionalSint64 = 456; - assertEquals(456, msg.optionalSint64); - msg.clear(); - assertEquals(0, msg.optionalSint64); - - msg.optionalSint64 = -123; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(-123, newMsg.optionalSint64); - } - - public void testNanoOptionalFixed32() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalFixed32 = 123; - assertEquals(123, msg.optionalFixed32); - msg.clear() - .optionalFixed32 = 456; - assertEquals(456, msg.optionalFixed32); - msg.clear(); - assertEquals(0, msg.optionalFixed32); - - msg.optionalFixed32 = 123; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 8); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(123, newMsg.optionalFixed32); - } - - public void testNanoOptionalFixed64() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalFixed64 = 123; - assertEquals(123, msg.optionalFixed64); - msg.clear() - .optionalFixed64 = 456; - assertEquals(456, msg.optionalFixed64); - msg.clear(); - assertEquals(0, msg.optionalFixed64); - - msg.optionalFixed64 = 123; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 12); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(123, newMsg.optionalFixed64); - } - - public void testNanoOptionalSfixed32() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalSfixed32 = 123; - assertEquals(123, msg.optionalSfixed32); - msg.clear() - .optionalSfixed32 = 456; - assertEquals(456, msg.optionalSfixed32); - msg.clear(); - assertEquals(0, msg.optionalSfixed32); - - msg.optionalSfixed32 = 123; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 8); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(123, newMsg.optionalSfixed32); - } - - public void testNanoOptionalSfixed64() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalSfixed64 = 123; - assertEquals(123, msg.optionalSfixed64); - msg.clear() - .optionalSfixed64 = 456; - assertEquals(456, msg.optionalSfixed64); - msg.clear(); - assertEquals(0, msg.optionalSfixed64); - - msg.optionalSfixed64 = -123; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 12); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(-123, newMsg.optionalSfixed64); - } - - public void testNanoOptionalFloat() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalFloat = 123f; - assertTrue(123.0f == msg.optionalFloat); - msg.clear() - .optionalFloat = 456.0f; - assertTrue(456.0f == msg.optionalFloat); - msg.clear(); - assertTrue(0.0f == msg.optionalFloat); - - msg.optionalFloat = -123.456f; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 8); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertTrue(-123.456f == newMsg.optionalFloat); - } - - public void testNanoOptionalDouble() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalDouble = 123; - assertTrue(123.0 == msg.optionalDouble); - msg.clear() - .optionalDouble = 456.0; - assertTrue(456.0 == msg.optionalDouble); - msg.clear(); - assertTrue(0.0 == msg.optionalDouble); - - msg.optionalDouble = -123.456; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 12); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertTrue(-123.456 == newMsg.optionalDouble); - } - - public void testNanoOptionalBool() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalBool = true; - assertTrue(msg.optionalBool); - msg.clear() - .optionalBool = true; - assertTrue(msg.optionalBool); - msg.clear(); - assertFalse(msg.optionalBool); - - msg.optionalBool = true; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 5); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertTrue(newMsg.optionalBool); - } - - public void testNanoOptionalString() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalString = "hello"; - assertEquals("hello", msg.optionalString); - msg.clear(); - assertTrue(msg.optionalString.isEmpty()); - msg.clear() - .optionalString = "hello2"; - assertEquals("hello2", msg.optionalString); - msg.clear(); - assertTrue(msg.optionalString.isEmpty()); - - msg.optionalString = "bye"; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 8); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertTrue(newMsg.optionalString != null); - assertEquals("bye", newMsg.optionalString); - } - - public void testNanoOptionalBytes() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertFalse(msg.optionalBytes.length > 0); - msg.optionalBytes = InternalNano.copyFromUtf8("hello"); - assertTrue(msg.optionalBytes.length > 0); - assertEquals("hello", new String(msg.optionalBytes, InternalNano.UTF_8)); - msg.clear(); - assertFalse(msg.optionalBytes.length > 0); - msg.clear() - .optionalBytes = InternalNano.copyFromUtf8("hello"); - assertTrue(msg.optionalBytes.length > 0); - msg.clear(); - assertFalse(msg.optionalBytes.length > 0); - - msg.optionalBytes = InternalNano.copyFromUtf8("bye"); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 8); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertTrue(newMsg.optionalBytes.length > 0); - assertEquals("bye", new String(newMsg.optionalBytes, InternalNano.UTF_8)); - } - - public void testNanoOptionalGroup() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - TestAllTypesNano.OptionalGroup grp = new TestAllTypesNano.OptionalGroup(); - grp.a = 1; - assertFalse(msg.optionalGroup != null); - msg.optionalGroup = grp; - assertTrue(msg.optionalGroup != null); - assertEquals(1, msg.optionalGroup.a); - msg.clear(); - assertFalse(msg.optionalGroup != null); - msg.clear() - .optionalGroup = new TestAllTypesNano.OptionalGroup(); - msg.optionalGroup.a = 2; - assertTrue(msg.optionalGroup != null); - msg.clear(); - assertFalse(msg.optionalGroup != null); - - msg.optionalGroup = grp; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 10); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertTrue(newMsg.optionalGroup != null); - assertEquals(1, newMsg.optionalGroup.a); - } - - public void testNanoOptionalGroupWithUnknownFieldsEnabled() throws Exception { - MessageWithGroup msg = new MessageWithGroup(); - MessageWithGroup.Group grp = new MessageWithGroup.Group(); - grp.a = 1; - msg.group = grp; - byte [] serialized = MessageNano.toByteArray(msg); - - MessageWithGroup parsed = MessageWithGroup.parseFrom(serialized); - assertEquals(1, parsed.group.a); - - byte [] serialized2 = MessageNano.toByteArray(parsed); - assertEquals(serialized.length, serialized2.length); - MessageWithGroup parsed2 = MessageWithGroup.parseFrom(serialized2); - assertEquals(1, parsed2.group.a); - } - - public void testNanoOptionalNestedMessage() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - TestAllTypesNano.NestedMessage nestedMsg = new TestAllTypesNano.NestedMessage(); - nestedMsg.bb = 1; - assertFalse(msg.optionalNestedMessage != null); - msg.optionalNestedMessage = nestedMsg; - assertTrue(msg.optionalNestedMessage != null); - assertEquals(1, msg.optionalNestedMessage.bb); - msg.clear(); - assertFalse(msg.optionalNestedMessage != null); - msg.clear() - .optionalNestedMessage = new TestAllTypesNano.NestedMessage(); - msg.optionalNestedMessage.bb = 2; - assertTrue(msg.optionalNestedMessage != null); - msg.clear(); - assertFalse(msg.optionalNestedMessage != null); - - msg.optionalNestedMessage = nestedMsg; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 8); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertTrue(newMsg.optionalNestedMessage != null); - assertEquals(1, newMsg.optionalNestedMessage.bb); - } - - public void testNanoOptionalForeignMessage() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - NanoOuterClass.ForeignMessageNano nestedMsg = new NanoOuterClass.ForeignMessageNano(); - nestedMsg.c = 1; - assertFalse(msg.optionalForeignMessage != null); - msg.optionalForeignMessage = nestedMsg; - assertTrue(msg.optionalForeignMessage != null); - assertEquals(1, msg.optionalForeignMessage.c); - msg.clear(); - assertFalse(msg.optionalForeignMessage != null); - msg.clear() - .optionalForeignMessage = new NanoOuterClass.ForeignMessageNano(); - msg.optionalForeignMessage.c = 2; - assertTrue(msg.optionalForeignMessage != null); - msg.clear(); - assertFalse(msg.optionalForeignMessage != null); - - msg.optionalForeignMessage = nestedMsg; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 8); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertTrue(newMsg.optionalForeignMessage != null); - assertEquals(1, newMsg.optionalForeignMessage.c); - } - - public void testNanoOptionalImportMessage() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - UnittestImportNano.ImportMessageNano nestedMsg = new UnittestImportNano.ImportMessageNano(); - nestedMsg.d = 1; - assertFalse(msg.optionalImportMessage != null); - msg.optionalImportMessage = nestedMsg; - assertTrue(msg.optionalImportMessage != null); - assertEquals(1, msg.optionalImportMessage.d); - msg.clear(); - assertFalse(msg.optionalImportMessage != null); - msg.clear() - .optionalImportMessage = new UnittestImportNano.ImportMessageNano(); - msg.optionalImportMessage.d = 2; - assertTrue(msg.optionalImportMessage != null); - msg.clear(); - assertFalse(msg.optionalImportMessage != null); - - msg.optionalImportMessage = nestedMsg; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 8); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertTrue(newMsg.optionalImportMessage != null); - assertEquals(1, newMsg.optionalImportMessage.d); - } - - public void testNanoOptionalNestedEnum() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalNestedEnum = TestAllTypesNano.BAR; - assertEquals(TestAllTypesNano.BAR, msg.optionalNestedEnum); - msg.clear() - .optionalNestedEnum = TestAllTypesNano.BAZ; - assertEquals(TestAllTypesNano.BAZ, msg.optionalNestedEnum); - msg.clear(); - assertEquals(TestAllTypesNano.FOO, msg.optionalNestedEnum); - - msg.optionalNestedEnum = TestAllTypesNano.BAR; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(TestAllTypesNano.BAR, newMsg.optionalNestedEnum); - } - - public void testNanoOptionalForeignEnum() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalForeignEnum = NanoOuterClass.FOREIGN_NANO_BAR; - assertEquals(NanoOuterClass.FOREIGN_NANO_BAR, msg.optionalForeignEnum); - msg.clear() - .optionalForeignEnum = NanoOuterClass.FOREIGN_NANO_BAZ; - assertEquals(NanoOuterClass.FOREIGN_NANO_BAZ, msg.optionalForeignEnum); - msg.clear(); - assertEquals(NanoOuterClass.FOREIGN_NANO_FOO, msg.optionalForeignEnum); - - msg.optionalForeignEnum = NanoOuterClass.FOREIGN_NANO_BAR; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(NanoOuterClass.FOREIGN_NANO_BAR, newMsg.optionalForeignEnum); - } - - public void testNanoOptionalImportEnum() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalImportEnum = UnittestImportNano.IMPORT_NANO_BAR; - assertEquals(UnittestImportNano.IMPORT_NANO_BAR, msg.optionalImportEnum); - msg.clear() - .optionalImportEnum = UnittestImportNano.IMPORT_NANO_BAZ; - assertEquals(UnittestImportNano.IMPORT_NANO_BAZ, msg.optionalImportEnum); - msg.clear(); - assertEquals(UnittestImportNano.IMPORT_NANO_FOO, msg.optionalImportEnum); - - msg.optionalImportEnum = UnittestImportNano.IMPORT_NANO_BAR; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(UnittestImportNano.IMPORT_NANO_BAR, newMsg.optionalImportEnum); - } - - public void testNanoOptionalStringPiece() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalStringPiece = "hello"; - assertEquals("hello", msg.optionalStringPiece); - msg.clear(); - assertTrue(msg.optionalStringPiece.isEmpty()); - msg.clear() - .optionalStringPiece = "hello2"; - assertEquals("hello2", msg.optionalStringPiece); - msg.clear(); - assertTrue(msg.optionalStringPiece.isEmpty()); - - msg.optionalStringPiece = "bye"; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 9); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertTrue(newMsg.optionalStringPiece != null); - assertEquals("bye", newMsg.optionalStringPiece); - } - - public void testNanoOptionalCord() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalCord = "hello"; - assertEquals("hello", msg.optionalCord); - msg.clear(); - assertTrue(msg.optionalCord.isEmpty()); - msg.clear() - .optionalCord = "hello2"; - assertEquals("hello2", msg.optionalCord); - msg.clear(); - assertTrue(msg.optionalCord.isEmpty()); - - msg.optionalCord = "bye"; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 9); - assertEquals(result.length, msgSerializedSize); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertTrue(newMsg.optionalCord != null); - assertEquals("bye", newMsg.optionalCord); - } - - public void testNanoRepeatedInt32() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedInt32.length); - msg.repeatedInt32 = new int[] { 123, 789, 456 }; - assertEquals(789, msg.repeatedInt32[1]); - assertEquals(456, msg.repeatedInt32[2]); - msg.clear(); - assertEquals(0, msg.repeatedInt32.length); - msg.clear() - .repeatedInt32 = new int[] { 456 }; - assertEquals(1, msg.repeatedInt32.length); - assertEquals(456, msg.repeatedInt32[0]); - msg.clear(); - assertEquals(0, msg.repeatedInt32.length); - - // Test 1 entry - msg.clear() - .repeatedInt32 = new int[] { 123 }; - assertEquals(1, msg.repeatedInt32.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedInt32.length); - assertEquals(123, newMsg.repeatedInt32[0]); - - // Test 2 entries - msg.clear() - .repeatedInt32 = new int[] { 123, 456 }; - assertEquals(2, msg.repeatedInt32.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 10); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedInt32.length); - assertEquals(123, newMsg.repeatedInt32[0]); - assertEquals(456, newMsg.repeatedInt32[1]); - } - - public void testNanoRepeatedInt64() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedInt64.length); - msg.repeatedInt64 = new long[] { 123, 789, 456 }; - assertEquals(789, msg.repeatedInt64[1]); - assertEquals(456, msg.repeatedInt64[2]); - msg.clear(); - assertEquals(0, msg.repeatedInt64.length); - msg.clear() - .repeatedInt64 = new long[] { 456 }; - assertEquals(1, msg.repeatedInt64.length); - assertEquals(456, msg.repeatedInt64[0]); - msg.clear(); - assertEquals(0, msg.repeatedInt64.length); - - // Test 1 entry - msg.clear() - .repeatedInt64 = new long[] { 123 }; - assertEquals(1, msg.repeatedInt64.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedInt64.length); - assertEquals(123, newMsg.repeatedInt64[0]); - - // Test 2 entries - msg.clear() - .repeatedInt64 = new long[] { 123, 456 }; - assertEquals(2, msg.repeatedInt64.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 10); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedInt64.length); - assertEquals(123, newMsg.repeatedInt64[0]); - assertEquals(456, newMsg.repeatedInt64[1]); - } - - public void testNanoRepeatedUint32() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedUint32.length); - msg.repeatedUint32 = new int[] { 123, 789, 456 }; - assertEquals(789, msg.repeatedUint32[1]); - assertEquals(456, msg.repeatedUint32[2]); - msg.clear(); - assertEquals(0, msg.repeatedUint32.length); - msg.clear() - .repeatedUint32 = new int[] { 456 }; - assertEquals(1, msg.repeatedUint32.length); - assertEquals(456, msg.repeatedUint32[0]); - msg.clear(); - assertEquals(0, msg.repeatedUint32.length); - - // Test 1 entry - msg.clear() - .repeatedUint32 = new int[] { 123 }; - assertEquals(1, msg.repeatedUint32.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedUint32.length); - assertEquals(123, newMsg.repeatedUint32[0]); - - // Test 2 entries - msg.clear() - .repeatedUint32 = new int[] { 123, 456 }; - assertEquals(2, msg.repeatedUint32.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 10); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedUint32.length); - assertEquals(123, newMsg.repeatedUint32[0]); - assertEquals(456, newMsg.repeatedUint32[1]); - } - - public void testNanoRepeatedUint64() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedUint64.length); - msg.repeatedUint64 = new long[] { 123, 789, 456 }; - assertEquals(789, msg.repeatedUint64[1]); - assertEquals(456, msg.repeatedUint64[2]); - msg.clear(); - assertEquals(0, msg.repeatedUint64.length); - msg.clear() - .repeatedUint64 = new long[] { 456 }; - assertEquals(1, msg.repeatedUint64.length); - assertEquals(456, msg.repeatedUint64[0]); - msg.clear(); - assertEquals(0, msg.repeatedUint64.length); - - // Test 1 entry - msg.clear() - .repeatedUint64 = new long[] { 123 }; - assertEquals(1, msg.repeatedUint64.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedUint64.length); - assertEquals(123, newMsg.repeatedUint64[0]); - - // Test 2 entries - msg.clear() - .repeatedUint64 = new long[] { 123, 456 }; - assertEquals(2, msg.repeatedUint64.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 10); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedUint64.length); - assertEquals(123, newMsg.repeatedUint64[0]); - assertEquals(456, newMsg.repeatedUint64[1]); - } - - public void testNanoRepeatedSint32() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedSint32.length); - msg.repeatedSint32 = new int[] { 123, 789, 456 }; - assertEquals(789, msg.repeatedSint32[1]); - assertEquals(456, msg.repeatedSint32[2]); - msg.clear(); - assertEquals(0, msg.repeatedSint32.length); - msg.clear() - .repeatedSint32 = new int[] { 456 }; - assertEquals(1, msg.repeatedSint32.length); - assertEquals(456, msg.repeatedSint32[0]); - msg.clear(); - assertEquals(0, msg.repeatedSint32.length); - - // Test 1 entry - msg.clear() - .repeatedSint32 = new int[] { 123 }; - assertEquals(1, msg.repeatedSint32.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 7); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedSint32.length); - assertEquals(123, newMsg.repeatedSint32[0]); - - // Test 2 entries - msg.clear() - .repeatedSint32 = new int[] { 123, 456 }; - assertEquals(2, msg.repeatedSint32.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 11); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedSint32.length); - assertEquals(123, newMsg.repeatedSint32[0]); - assertEquals(456, newMsg.repeatedSint32[1]); - } - - public void testNanoRepeatedSint64() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedSint64.length); - msg.repeatedSint64 = new long[] { 123, 789, 456 }; - assertEquals(789, msg.repeatedSint64[1]); - assertEquals(456, msg.repeatedSint64[2]); - msg.clear(); - assertEquals(0, msg.repeatedSint64.length); - msg.clear() - .repeatedSint64 = new long[] { 456 }; - assertEquals(1, msg.repeatedSint64.length); - assertEquals(456, msg.repeatedSint64[0]); - msg.clear(); - assertEquals(0, msg.repeatedSint64.length); - - // Test 1 entry - msg.clear() - .repeatedSint64 = new long[] { 123 }; - assertEquals(1, msg.repeatedSint64.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 7); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedSint64.length); - assertEquals(123, newMsg.repeatedSint64[0]); - - // Test 2 entries - msg.clear() - .repeatedSint64 = new long[] { 123, 456 }; - assertEquals(2, msg.repeatedSint64.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 11); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedSint64.length); - assertEquals(123, newMsg.repeatedSint64[0]); - assertEquals(456, newMsg.repeatedSint64[1]); - } - - public void testNanoRepeatedFixed32() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedFixed32.length); - msg.repeatedFixed32 = new int[] { 123, 789, 456 }; - assertEquals(789, msg.repeatedFixed32[1]); - assertEquals(456, msg.repeatedFixed32[2]); - msg.clear(); - assertEquals(0, msg.repeatedFixed32.length); - msg.clear() - .repeatedFixed32 = new int[] { 456 }; - assertEquals(1, msg.repeatedFixed32.length); - assertEquals(456, msg.repeatedFixed32[0]); - msg.clear(); - assertEquals(0, msg.repeatedFixed32.length); - - // Test 1 entry - msg.clear() - .repeatedFixed32 = new int[] { 123 }; - assertEquals(1, msg.repeatedFixed32.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 9); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedFixed32.length); - assertEquals(123, newMsg.repeatedFixed32[0]); - - // Test 2 entries - msg.clear() - .repeatedFixed32 = new int[] { 123, 456 }; - assertEquals(2, msg.repeatedFixed32.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 15); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedFixed32.length); - assertEquals(123, newMsg.repeatedFixed32[0]); - assertEquals(456, newMsg.repeatedFixed32[1]); - } - - public void testNanoRepeatedFixed64() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedFixed64.length); - msg.repeatedFixed64 = new long[] { 123, 789, 456 }; - assertEquals(789, msg.repeatedFixed64[1]); - assertEquals(456, msg.repeatedFixed64[2]); - msg.clear(); - assertEquals(0, msg.repeatedFixed64.length); - msg.clear() - .repeatedFixed64 = new long[] { 456 }; - assertEquals(1, msg.repeatedFixed64.length); - assertEquals(456, msg.repeatedFixed64[0]); - msg.clear(); - assertEquals(0, msg.repeatedFixed64.length); - - // Test 1 entry - msg.clear() - .repeatedFixed64 = new long[] { 123 }; - assertEquals(1, msg.repeatedFixed64.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 13); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedFixed64.length); - assertEquals(123, newMsg.repeatedFixed64[0]); - - // Test 2 entries - msg.clear() - .repeatedFixed64 = new long[] { 123, 456 }; - assertEquals(2, msg.repeatedFixed64.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 23); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedFixed64.length); - assertEquals(123, newMsg.repeatedFixed64[0]); - assertEquals(456, newMsg.repeatedFixed64[1]); - } - - public void testNanoRepeatedSfixed32() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedSfixed32.length); - msg.repeatedSfixed32 = new int[] { 123, 789, 456 }; - assertEquals(789, msg.repeatedSfixed32[1]); - assertEquals(456, msg.repeatedSfixed32[2]); - msg.clear(); - assertEquals(0, msg.repeatedSfixed32.length); - msg.clear() - .repeatedSfixed32 = new int[] { 456 }; - assertEquals(1, msg.repeatedSfixed32.length); - assertEquals(456, msg.repeatedSfixed32[0]); - msg.clear(); - assertEquals(0, msg.repeatedSfixed32.length); - - // Test 1 entry - msg.clear() - .repeatedSfixed32 = new int[] { 123 }; - assertEquals(1, msg.repeatedSfixed32.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 9); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedSfixed32.length); - assertEquals(123, newMsg.repeatedSfixed32[0]); - - // Test 2 entries - msg.clear() - .repeatedSfixed32 = new int[] { 123, 456 }; - assertEquals(2, msg.repeatedSfixed32.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 15); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedSfixed32.length); - assertEquals(123, newMsg.repeatedSfixed32[0]); - assertEquals(456, newMsg.repeatedSfixed32[1]); - } - - public void testNanoRepeatedSfixed64() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedSfixed64.length); - msg.repeatedSfixed64 = new long[] { 123, 789, 456 }; - assertEquals(789, msg.repeatedSfixed64[1]); - assertEquals(456, msg.repeatedSfixed64[2]); - msg.clear(); - assertEquals(0, msg.repeatedSfixed64.length); - msg.clear() - .repeatedSfixed64 = new long[] { 456 }; - assertEquals(1, msg.repeatedSfixed64.length); - assertEquals(456, msg.repeatedSfixed64[0]); - msg.clear(); - assertEquals(0, msg.repeatedSfixed64.length); - - // Test 1 entry - msg.clear() - .repeatedSfixed64 = new long[] { 123 }; - assertEquals(1, msg.repeatedSfixed64.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 13); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedSfixed64.length); - assertEquals(123, newMsg.repeatedSfixed64[0]); - - // Test 2 entries - msg.clear() - .repeatedSfixed64 = new long[] { 123, 456 }; - assertEquals(2, msg.repeatedSfixed64.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 23); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedSfixed64.length); - assertEquals(123, newMsg.repeatedSfixed64[0]); - assertEquals(456, newMsg.repeatedSfixed64[1]); - } - - public void testNanoRepeatedFloat() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedFloat.length); - msg.repeatedFloat = new float[] { 123f, 789f, 456f }; - assertEquals(789f, msg.repeatedFloat[1]); - assertEquals(456f, msg.repeatedFloat[2]); - msg.clear(); - assertEquals(0, msg.repeatedFloat.length); - msg.clear() - .repeatedFloat = new float[] { 456f }; - assertEquals(1, msg.repeatedFloat.length); - assertEquals(456f, msg.repeatedFloat[0]); - msg.clear(); - assertEquals(0, msg.repeatedFloat.length); - - // Test 1 entry - msg.clear() - .repeatedFloat = new float[] { 123f }; - assertEquals(1, msg.repeatedFloat.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 9); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedFloat.length); - assertEquals(123f, newMsg.repeatedFloat[0]); - - // Test 2 entries - msg.clear() - .repeatedFloat = new float[] { 123f, 456f }; - assertEquals(2, msg.repeatedFloat.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 15); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedFloat.length); - assertEquals(123f, newMsg.repeatedFloat[0]); - assertEquals(456f, newMsg.repeatedFloat[1]); - } - - public void testNanoRepeatedDouble() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedDouble.length); - msg.repeatedDouble = new double[] { 123.0, 789.0, 456.0 }; - assertEquals(789.0, msg.repeatedDouble[1]); - assertEquals(456.0, msg.repeatedDouble[2]); - msg.clear(); - assertEquals(0, msg.repeatedDouble.length); - msg.clear() - .repeatedDouble = new double[] { 456.0 }; - assertEquals(1, msg.repeatedDouble.length); - assertEquals(456.0, msg.repeatedDouble[0]); - msg.clear(); - assertEquals(0, msg.repeatedDouble.length); - - // Test 1 entry - msg.clear() - .repeatedDouble = new double[] { 123.0 }; - assertEquals(1, msg.repeatedDouble.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 13); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedDouble.length); - assertEquals(123.0, newMsg.repeatedDouble[0]); - - // Test 2 entries - msg.clear() - .repeatedDouble = new double[] { 123.0, 456.0 }; - assertEquals(2, msg.repeatedDouble.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 23); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedDouble.length); - assertEquals(123.0, newMsg.repeatedDouble[0]); - assertEquals(456.0, newMsg.repeatedDouble[1]); - } - - public void testNanoRepeatedBool() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedBool.length); - msg.repeatedBool = new boolean[] { false, true, false }; - assertTrue(msg.repeatedBool[1]); - assertFalse(msg.repeatedBool[2]); - msg.clear(); - assertEquals(0, msg.repeatedBool.length); - msg.clear() - .repeatedBool = new boolean[] { true }; - assertEquals(1, msg.repeatedBool.length); - assertTrue(msg.repeatedBool[0]); - msg.clear(); - assertEquals(0, msg.repeatedBool.length); - - // Test 1 entry - msg.clear() - .repeatedBool = new boolean[] { false }; - assertEquals(1, msg.repeatedBool.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedBool.length); - assertFalse(newMsg.repeatedBool[0]); - - // Test 2 entries - msg.clear() - .repeatedBool = new boolean[] { true, false }; - assertEquals(2, msg.repeatedBool.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 9); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedBool.length); - assertTrue(newMsg.repeatedBool[0]); - assertFalse(newMsg.repeatedBool[1]); - } - - public void testNanoRepeatedString() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedString.length); - msg.repeatedString = new String[] { "hello", "bye", "boo" }; - assertEquals("bye", msg.repeatedString[1]); - assertEquals("boo", msg.repeatedString[2]); - msg.clear(); - assertEquals(0, msg.repeatedString.length); - msg.clear() - .repeatedString = new String[] { "boo" }; - assertEquals(1, msg.repeatedString.length); - assertEquals("boo", msg.repeatedString[0]); - msg.clear(); - assertEquals(0, msg.repeatedString.length); - - // Test 1 entry - msg.clear() - .repeatedString = new String[] { "" }; - assertEquals(1, msg.repeatedString.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedString.length); - assertTrue(newMsg.repeatedString[0].isEmpty()); - - // Test 2 entries - msg.clear() - .repeatedString = new String[] { "hello", "world" }; - assertEquals(2, msg.repeatedString.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 19); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedString.length); - assertEquals("hello", newMsg.repeatedString[0]); - assertEquals("world", newMsg.repeatedString[1]); - } - - public void testNanoRepeatedBytes() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedBytes.length); - msg.repeatedBytes = new byte[][] { - InternalNano.copyFromUtf8("hello"), - InternalNano.copyFromUtf8("bye"), - InternalNano.copyFromUtf8("boo") - }; - assertEquals("bye", new String(msg.repeatedBytes[1], InternalNano.UTF_8)); - assertEquals("boo", new String(msg.repeatedBytes[2], InternalNano.UTF_8)); - msg.clear(); - assertEquals(0, msg.repeatedBytes.length); - msg.clear() - .repeatedBytes = new byte[][] { InternalNano.copyFromUtf8("boo") }; - assertEquals(1, msg.repeatedBytes.length); - assertEquals("boo", new String(msg.repeatedBytes[0], InternalNano.UTF_8)); - msg.clear(); - assertEquals(0, msg.repeatedBytes.length); - - // Test 1 entry - msg.clear() - .repeatedBytes = new byte[][] { InternalNano.copyFromUtf8("") }; - assertEquals(1, msg.repeatedBytes.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedBytes.length); - assertTrue(newMsg.repeatedBytes[0].length == 0); - - // Test 2 entries - msg.clear() - .repeatedBytes = new byte[][] { - InternalNano.copyFromUtf8("hello"), - InternalNano.copyFromUtf8("world") - }; - assertEquals(2, msg.repeatedBytes.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 19); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedBytes.length); - assertEquals("hello", new String(newMsg.repeatedBytes[0], InternalNano.UTF_8)); - assertEquals("world", new String(newMsg.repeatedBytes[1], InternalNano.UTF_8)); - } - - public void testNanoRepeatedGroup() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - TestAllTypesNano.RepeatedGroup group0 = - new TestAllTypesNano.RepeatedGroup(); - group0.a = 0; - TestAllTypesNano.RepeatedGroup group1 = - new TestAllTypesNano.RepeatedGroup(); - group1.a = 1; - TestAllTypesNano.RepeatedGroup group2 = - new TestAllTypesNano.RepeatedGroup(); - group2.a = 2; - - msg.repeatedGroup = new TestAllTypesNano.RepeatedGroup[] { group0, group1, group2 }; - assertEquals(3, msg.repeatedGroup.length); - assertEquals(0, msg.repeatedGroup[0].a); - assertEquals(1, msg.repeatedGroup[1].a); - assertEquals(2, msg.repeatedGroup[2].a); - msg.clear(); - assertEquals(0, msg.repeatedGroup.length); - msg.clear() - .repeatedGroup = new TestAllTypesNano.RepeatedGroup[] { group1 }; - assertEquals(1, msg.repeatedGroup.length); - assertEquals(1, msg.repeatedGroup[0].a); - msg.clear(); - assertEquals(0, msg.repeatedGroup.length); - - // Test 1 entry - msg.clear() - .repeatedGroup = new TestAllTypesNano.RepeatedGroup[] { group0 }; - assertEquals(1, msg.repeatedGroup.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 7); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedGroup.length); - assertEquals(0, newMsg.repeatedGroup[0].a); - - // Test 2 entries - msg.clear() - .repeatedGroup = new TestAllTypesNano.RepeatedGroup[] { group0, group1 }; - assertEquals(2, msg.repeatedGroup.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 14); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedGroup.length); - assertEquals(0, newMsg.repeatedGroup[0].a); - assertEquals(1, newMsg.repeatedGroup[1].a); - } - - public void testNanoRepeatedNestedMessage() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - TestAllTypesNano.NestedMessage nestedMsg0 = - new TestAllTypesNano.NestedMessage(); - nestedMsg0.bb = 0; - TestAllTypesNano.NestedMessage nestedMsg1 = - new TestAllTypesNano.NestedMessage(); - nestedMsg1.bb = 1; - TestAllTypesNano.NestedMessage nestedMsg2 = - new TestAllTypesNano.NestedMessage(); - nestedMsg2.bb = 2; - - msg.repeatedNestedMessage = - new TestAllTypesNano.NestedMessage[] { nestedMsg0, nestedMsg1, nestedMsg2 }; - assertEquals(3, msg.repeatedNestedMessage.length); - assertEquals(0, msg.repeatedNestedMessage[0].bb); - assertEquals(1, msg.repeatedNestedMessage[1].bb); - assertEquals(2, msg.repeatedNestedMessage[2].bb); - msg.clear(); - assertEquals(0, msg.repeatedNestedMessage.length); - msg.clear() - .repeatedNestedMessage = new TestAllTypesNano.NestedMessage[] { nestedMsg1 }; - assertEquals(1, msg.repeatedNestedMessage.length); - assertEquals(1, msg.repeatedNestedMessage[0].bb); - msg.clear(); - assertEquals(0, msg.repeatedNestedMessage.length); - - // Test 1 entry - msg.clear() - .repeatedNestedMessage = new TestAllTypesNano.NestedMessage[] { nestedMsg0 }; - assertEquals(1, msg.repeatedNestedMessage.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedNestedMessage.length); - assertEquals(0, newMsg.repeatedNestedMessage[0].bb); - - // Test 2 entries - msg.clear() - .repeatedNestedMessage = new TestAllTypesNano.NestedMessage[] { nestedMsg0, nestedMsg1 }; - assertEquals(2, msg.repeatedNestedMessage.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 11); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedNestedMessage.length); - assertEquals(0, newMsg.repeatedNestedMessage[0].bb); - assertEquals(1, newMsg.repeatedNestedMessage[1].bb); - } - - public void testNanoRepeatedForeignMessage() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - NanoOuterClass.ForeignMessageNano foreignMsg0 = - new NanoOuterClass.ForeignMessageNano(); - foreignMsg0.c = 0; - NanoOuterClass.ForeignMessageNano foreignMsg1 = - new NanoOuterClass.ForeignMessageNano(); - foreignMsg1.c = 1; - NanoOuterClass.ForeignMessageNano foreignMsg2 = - new NanoOuterClass.ForeignMessageNano(); - foreignMsg2.c = 2; - - msg.repeatedForeignMessage = - new NanoOuterClass.ForeignMessageNano[] { foreignMsg0, foreignMsg1, foreignMsg2 }; - assertEquals(3, msg.repeatedForeignMessage.length); - assertEquals(0, msg.repeatedForeignMessage[0].c); - assertEquals(1, msg.repeatedForeignMessage[1].c); - assertEquals(2, msg.repeatedForeignMessage[2].c); - msg.clear(); - assertEquals(0, msg.repeatedForeignMessage.length); - msg.clear() - .repeatedForeignMessage = new NanoOuterClass.ForeignMessageNano[] { foreignMsg1 }; - assertEquals(1, msg.repeatedForeignMessage.length); - assertEquals(1, msg.repeatedForeignMessage[0].c); - msg.clear(); - assertEquals(0, msg.repeatedForeignMessage.length); - - // Test 1 entry - msg.clear() - .repeatedForeignMessage = new NanoOuterClass.ForeignMessageNano[] { foreignMsg0 }; - assertEquals(1, msg.repeatedForeignMessage.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedForeignMessage.length); - assertEquals(0, newMsg.repeatedForeignMessage[0].c); - - // Test 2 entries - msg.clear() - .repeatedForeignMessage = new NanoOuterClass.ForeignMessageNano[] { foreignMsg0, foreignMsg1 }; - assertEquals(2, msg.repeatedForeignMessage.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 11); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedForeignMessage.length); - assertEquals(0, newMsg.repeatedForeignMessage[0].c); - assertEquals(1, newMsg.repeatedForeignMessage[1].c); - } - - public void testNanoRepeatedImportMessage() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - UnittestImportNano.ImportMessageNano foreignMsg0 = - new UnittestImportNano.ImportMessageNano(); - foreignMsg0.d = 0; - UnittestImportNano.ImportMessageNano foreignMsg1 = - new UnittestImportNano.ImportMessageNano(); - foreignMsg1.d = 1; - UnittestImportNano.ImportMessageNano foreignMsg2 = - new UnittestImportNano.ImportMessageNano(); - foreignMsg2.d = 2; - - msg.repeatedImportMessage = - new UnittestImportNano.ImportMessageNano[] { foreignMsg0, foreignMsg1, foreignMsg2 }; - assertEquals(3, msg.repeatedImportMessage.length); - assertEquals(0, msg.repeatedImportMessage[0].d); - assertEquals(1, msg.repeatedImportMessage[1].d); - assertEquals(2, msg.repeatedImportMessage[2].d); - msg.clear(); - assertEquals(0, msg.repeatedImportMessage.length); - msg.clear() - .repeatedImportMessage = new UnittestImportNano.ImportMessageNano[] { foreignMsg1 }; - assertEquals(1, msg.repeatedImportMessage.length); - assertEquals(1, msg.repeatedImportMessage[0].d); - msg.clear(); - assertEquals(0, msg.repeatedImportMessage.length); - - // Test 1 entry - msg.clear() - .repeatedImportMessage = new UnittestImportNano.ImportMessageNano[] { foreignMsg0 }; - assertEquals(1, msg.repeatedImportMessage.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedImportMessage.length); - assertEquals(0, newMsg.repeatedImportMessage[0].d); - - // Test 2 entries - msg.clear() - .repeatedImportMessage = new UnittestImportNano.ImportMessageNano[] { foreignMsg0, foreignMsg1 }; - assertEquals(2, msg.repeatedImportMessage.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 11); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedImportMessage.length); - assertEquals(0, newMsg.repeatedImportMessage[0].d); - assertEquals(1, newMsg.repeatedImportMessage[1].d); - } - - public void testNanoRepeatedNestedEnum() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.repeatedNestedEnum = new int[] { - TestAllTypesNano.FOO, - TestAllTypesNano.BAR, - TestAllTypesNano.BAZ - }; - assertEquals(3, msg.repeatedNestedEnum.length); - assertEquals(TestAllTypesNano.FOO, msg.repeatedNestedEnum[0]); - assertEquals(TestAllTypesNano.BAR, msg.repeatedNestedEnum[1]); - assertEquals(TestAllTypesNano.BAZ, msg.repeatedNestedEnum[2]); - msg.clear(); - assertEquals(0, msg.repeatedNestedEnum.length); - msg.clear() - .repeatedNestedEnum = new int[] { TestAllTypesNano.BAR }; - assertEquals(1, msg.repeatedNestedEnum.length); - assertEquals(TestAllTypesNano.BAR, msg.repeatedNestedEnum[0]); - msg.clear(); - assertEquals(0, msg.repeatedNestedEnum.length); - - // Test 1 entry - msg.clear() - .repeatedNestedEnum = new int[] { TestAllTypesNano.FOO }; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedNestedEnum.length); - assertEquals(TestAllTypesNano.FOO, msg.repeatedNestedEnum[0]); - - // Test 2 entries - msg.clear() - .repeatedNestedEnum = new int[] { TestAllTypesNano.FOO, TestAllTypesNano.BAR }; - assertEquals(2, msg.repeatedNestedEnum.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 9); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedNestedEnum.length); - assertEquals(TestAllTypesNano.FOO, msg.repeatedNestedEnum[0]); - assertEquals(TestAllTypesNano.BAR, msg.repeatedNestedEnum[1]); - } - - public void testNanoRepeatedForeignEnum() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.repeatedForeignEnum = new int[] { - NanoOuterClass.FOREIGN_NANO_FOO, - NanoOuterClass.FOREIGN_NANO_BAR, - NanoOuterClass.FOREIGN_NANO_BAZ - }; - assertEquals(3, msg.repeatedForeignEnum.length); - assertEquals(NanoOuterClass.FOREIGN_NANO_FOO, msg.repeatedForeignEnum[0]); - assertEquals(NanoOuterClass.FOREIGN_NANO_BAR, msg.repeatedForeignEnum[1]); - assertEquals(NanoOuterClass.FOREIGN_NANO_BAZ, msg.repeatedForeignEnum[2]); - msg.clear(); - assertEquals(0, msg.repeatedForeignEnum.length); - msg.clear() - .repeatedForeignEnum = new int[] { NanoOuterClass.FOREIGN_NANO_BAR }; - assertEquals(1, msg.repeatedForeignEnum.length); - assertEquals(NanoOuterClass.FOREIGN_NANO_BAR, msg.repeatedForeignEnum[0]); - msg.clear(); - assertEquals(0, msg.repeatedForeignEnum.length); - - // Test 1 entry - msg.clear() - .repeatedForeignEnum = new int[] { NanoOuterClass.FOREIGN_NANO_FOO }; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedForeignEnum.length); - assertEquals(NanoOuterClass.FOREIGN_NANO_FOO, msg.repeatedForeignEnum[0]); - - // Test 2 entries - msg.clear() - .repeatedForeignEnum = new int[] { - NanoOuterClass.FOREIGN_NANO_FOO, - NanoOuterClass.FOREIGN_NANO_BAR - }; - assertEquals(2, msg.repeatedForeignEnum.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 9); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedForeignEnum.length); - assertEquals(NanoOuterClass.FOREIGN_NANO_FOO, msg.repeatedForeignEnum[0]); - assertEquals(NanoOuterClass.FOREIGN_NANO_BAR, msg.repeatedForeignEnum[1]); - } - - public void testNanoRepeatedImportEnum() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.repeatedImportEnum = new int[] { - UnittestImportNano.IMPORT_NANO_FOO, - UnittestImportNano.IMPORT_NANO_BAR, - UnittestImportNano.IMPORT_NANO_BAZ - }; - assertEquals(3, msg.repeatedImportEnum.length); - assertEquals(UnittestImportNano.IMPORT_NANO_FOO, msg.repeatedImportEnum[0]); - assertEquals(UnittestImportNano.IMPORT_NANO_BAR, msg.repeatedImportEnum[1]); - assertEquals(UnittestImportNano.IMPORT_NANO_BAZ, msg.repeatedImportEnum[2]); - msg.clear(); - assertEquals(0, msg.repeatedImportEnum.length); - msg.clear() - .repeatedImportEnum = new int[] { UnittestImportNano.IMPORT_NANO_BAR }; - assertEquals(1, msg.repeatedImportEnum.length); - assertEquals(UnittestImportNano.IMPORT_NANO_BAR, msg.repeatedImportEnum[0]); - msg.clear(); - assertEquals(0, msg.repeatedImportEnum.length); - - // Test 1 entry - msg.clear() - .repeatedImportEnum = new int[] { UnittestImportNano.IMPORT_NANO_FOO }; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedImportEnum.length); - assertEquals(UnittestImportNano.IMPORT_NANO_FOO, msg.repeatedImportEnum[0]); - - // Test 2 entries - msg.clear() - .repeatedImportEnum = new int[] { - UnittestImportNano.IMPORT_NANO_FOO, - UnittestImportNano.IMPORT_NANO_BAR - }; - assertEquals(2, msg.repeatedImportEnum.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 9); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedImportEnum.length); - assertEquals(UnittestImportNano.IMPORT_NANO_FOO, msg.repeatedImportEnum[0]); - assertEquals(UnittestImportNano.IMPORT_NANO_BAR, msg.repeatedImportEnum[1]); - } - - public void testNanoRepeatedStringPiece() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedStringPiece.length); - msg.repeatedStringPiece = new String[] { "hello", "bye", "boo" }; - assertEquals("bye", msg.repeatedStringPiece[1]); - assertEquals("boo", msg.repeatedStringPiece[2]); - msg.clear(); - assertEquals(0, msg.repeatedStringPiece.length); - msg.clear() - .repeatedStringPiece = new String[] { "boo" }; - assertEquals(1, msg.repeatedStringPiece.length); - assertEquals("boo", msg.repeatedStringPiece[0]); - msg.clear(); - assertEquals(0, msg.repeatedStringPiece.length); - - // Test 1 entry - msg.clear() - .repeatedStringPiece = new String[] { "" }; - assertEquals(1, msg.repeatedStringPiece.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedStringPiece.length); - assertTrue(newMsg.repeatedStringPiece[0].isEmpty()); - - // Test 2 entries - msg.clear() - .repeatedStringPiece = new String[] { "hello", "world" }; - assertEquals(2, msg.repeatedStringPiece.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 19); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedStringPiece.length); - assertEquals("hello", newMsg.repeatedStringPiece[0]); - assertEquals("world", newMsg.repeatedStringPiece[1]); - } - - public void testNanoRepeatedCord() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedCord.length); - msg.repeatedCord = new String[] { "hello", "bye", "boo" }; - assertEquals("bye", msg.repeatedCord[1]); - assertEquals("boo", msg.repeatedCord[2]); - msg.clear(); - assertEquals(0, msg.repeatedCord.length); - msg.clear() - .repeatedCord = new String[] { "boo" }; - assertEquals(1, msg.repeatedCord.length); - assertEquals("boo", msg.repeatedCord[0]); - msg.clear(); - assertEquals(0, msg.repeatedCord.length); - - // Test 1 entry - msg.clear() - .repeatedCord = new String[] { "" }; - assertEquals(1, msg.repeatedCord.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 6); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedCord.length); - assertTrue(newMsg.repeatedCord[0].isEmpty()); - - // Test 2 entries - msg.clear() - .repeatedCord = new String[] { "hello", "world" }; - assertEquals(2, msg.repeatedCord.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 19); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedCord.length); - assertEquals("hello", newMsg.repeatedCord[0]); - assertEquals("world", newMsg.repeatedCord[1]); - } - - public void testNanoRepeatedPackedInt32() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedPackedInt32.length); - msg.repeatedPackedInt32 = new int[] { 123, 789, 456 }; - assertEquals(789, msg.repeatedPackedInt32[1]); - assertEquals(456, msg.repeatedPackedInt32[2]); - msg.clear(); - assertEquals(0, msg.repeatedPackedInt32.length); - msg.clear() - .repeatedPackedInt32 = new int[] { 456 }; - assertEquals(1, msg.repeatedPackedInt32.length); - assertEquals(456, msg.repeatedPackedInt32[0]); - msg.clear(); - assertEquals(0, msg.repeatedPackedInt32.length); - - // Test 1 entry - msg.clear() - .repeatedPackedInt32 = new int[] { 123 }; - assertEquals(1, msg.repeatedPackedInt32.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 7); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedPackedInt32.length); - assertEquals(123, newMsg.repeatedPackedInt32[0]); - - // Test 2 entries - msg.clear() - .repeatedPackedInt32 = new int[] { 123, 456 }; - assertEquals(2, msg.repeatedPackedInt32.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 9); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedPackedInt32.length); - assertEquals(123, newMsg.repeatedPackedInt32[0]); - assertEquals(456, newMsg.repeatedPackedInt32[1]); - } - - public void testNanoRepeatedPackedSfixed64() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - assertEquals(0, msg.repeatedPackedSfixed64.length); - msg.repeatedPackedSfixed64 = new long[] { 123, 789, 456 }; - assertEquals(789, msg.repeatedPackedSfixed64[1]); - assertEquals(456, msg.repeatedPackedSfixed64[2]); - msg.clear(); - assertEquals(0, msg.repeatedPackedSfixed64.length); - msg.clear() - .repeatedPackedSfixed64 = new long[] { 456 }; - assertEquals(1, msg.repeatedPackedSfixed64.length); - assertEquals(456, msg.repeatedPackedSfixed64[0]); - msg.clear(); - assertEquals(0, msg.repeatedPackedSfixed64.length); - - // Test 1 entry - msg.clear() - .repeatedPackedSfixed64 = new long[] { 123 }; - assertEquals(1, msg.repeatedPackedSfixed64.length); - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 14); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedPackedSfixed64.length); - assertEquals(123, newMsg.repeatedPackedSfixed64[0]); - - // Test 2 entries - msg.clear() - .repeatedPackedSfixed64 = new long[] { 123, 456 }; - assertEquals(2, msg.repeatedPackedSfixed64.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 22); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedPackedSfixed64.length); - assertEquals(123, newMsg.repeatedPackedSfixed64[0]); - assertEquals(456, newMsg.repeatedPackedSfixed64[1]); - } - - public void testNanoRepeatedPackedNestedEnum() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.repeatedPackedNestedEnum = new int[] { - TestAllTypesNano.FOO, - TestAllTypesNano.BAR, - TestAllTypesNano.BAZ - }; - assertEquals(3, msg.repeatedPackedNestedEnum.length); - assertEquals(TestAllTypesNano.FOO, msg.repeatedPackedNestedEnum[0]); - assertEquals(TestAllTypesNano.BAR, msg.repeatedPackedNestedEnum[1]); - assertEquals(TestAllTypesNano.BAZ, msg.repeatedPackedNestedEnum[2]); - msg.clear(); - assertEquals(0, msg.repeatedPackedNestedEnum.length); - msg.clear() - .repeatedPackedNestedEnum = new int[] { TestAllTypesNano.BAR }; - assertEquals(1, msg.repeatedPackedNestedEnum.length); - assertEquals(TestAllTypesNano.BAR, msg.repeatedPackedNestedEnum[0]); - msg.clear(); - assertEquals(0, msg.repeatedPackedNestedEnum.length); - - // Test 1 entry - msg.clear() - .repeatedPackedNestedEnum = new int[] { TestAllTypesNano.FOO }; - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 7); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(1, newMsg.repeatedPackedNestedEnum.length); - assertEquals(TestAllTypesNano.FOO, msg.repeatedPackedNestedEnum[0]); - - // Test 2 entries - msg.clear() - .repeatedPackedNestedEnum = new int[] { TestAllTypesNano.FOO, TestAllTypesNano.BAR }; - assertEquals(2, msg.repeatedPackedNestedEnum.length); - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 8); - assertEquals(result.length, msgSerializedSize); - - newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(2, newMsg.repeatedPackedNestedEnum.length); - assertEquals(TestAllTypesNano.FOO, msg.repeatedPackedNestedEnum[0]); - assertEquals(TestAllTypesNano.BAR, msg.repeatedPackedNestedEnum[1]); - } - - public void testNanoRepeatedPackedSerializedSize() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.repeatedPackedInt32 = new int[] { 123, 789, 456 }; - int msgSerializedSize = msg.getSerializedSize(); - byte [] result = MessageNano.toByteArray(msg); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 11); - assertEquals(result.length, msgSerializedSize); - TestAllTypesNano msg2 = new TestAllTypesNano(); - msg2.repeatedPackedInt32 = new int[] { 123, 789, 456 }; - byte [] result2 = new byte[msgSerializedSize]; - MessageNano.toByteArray(msg2, result2, 0, msgSerializedSize); - - // Check equal size and content. - assertEquals(msgSerializedSize, msg2.getSerializedSize()); - assertTrue(Arrays.equals(result, result2)); - } - - public void testNanoRepeatedInt32ReMerge() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.repeatedInt32 = new int[] { 234 }; - byte [] result1 = MessageNano.toByteArray(msg); - - msg.clear().optionalInt32 = 789; - byte [] result2 = MessageNano.toByteArray(msg); - - msg.clear().repeatedInt32 = new int[] { 123, 456 }; - byte [] result3 = MessageNano.toByteArray(msg); - - // Concatenate the three serializations and read as one message. - byte [] result = new byte[result1.length + result2.length + result3.length]; - System.arraycopy(result1, 0, result, 0, result1.length); - System.arraycopy(result2, 0, result, result1.length, result2.length); - System.arraycopy(result3, 0, result, result1.length + result2.length, result3.length); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(789, newMsg.optionalInt32); - assertEquals(3, newMsg.repeatedInt32.length); - assertEquals(234, newMsg.repeatedInt32[0]); - assertEquals(123, newMsg.repeatedInt32[1]); - assertEquals(456, newMsg.repeatedInt32[2]); - } - - public void testNanoRepeatedNestedEnumReMerge() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.repeatedNestedEnum = new int[] { TestAllTypesNano.FOO }; - byte [] result1 = MessageNano.toByteArray(msg); - - msg.clear().optionalInt32 = 789; - byte [] result2 = MessageNano.toByteArray(msg); - - msg.clear().repeatedNestedEnum = new int[] { TestAllTypesNano.BAR, TestAllTypesNano.FOO }; - byte [] result3 = MessageNano.toByteArray(msg); - - // Concatenate the three serializations and read as one message. - byte [] result = new byte[result1.length + result2.length + result3.length]; - System.arraycopy(result1, 0, result, 0, result1.length); - System.arraycopy(result2, 0, result, result1.length, result2.length); - System.arraycopy(result3, 0, result, result1.length + result2.length, result3.length); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(789, newMsg.optionalInt32); - assertEquals(3, newMsg.repeatedNestedEnum.length); - assertEquals(TestAllTypesNano.FOO, newMsg.repeatedNestedEnum[0]); - assertEquals(TestAllTypesNano.BAR, newMsg.repeatedNestedEnum[1]); - assertEquals(TestAllTypesNano.FOO, newMsg.repeatedNestedEnum[2]); - } - - public void testNanoRepeatedNestedMessageReMerge() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - TestAllTypesNano.NestedMessage nestedMsg0 = - new TestAllTypesNano.NestedMessage(); - nestedMsg0.bb = 0; - TestAllTypesNano.NestedMessage nestedMsg1 = - new TestAllTypesNano.NestedMessage(); - nestedMsg1.bb = 1; - TestAllTypesNano.NestedMessage nestedMsg2 = - new TestAllTypesNano.NestedMessage(); - nestedMsg2.bb = 2; - - msg.repeatedNestedMessage = new TestAllTypesNano.NestedMessage[] { nestedMsg0 }; - byte [] result1 = MessageNano.toByteArray(msg); - - msg.clear().optionalInt32 = 789; - byte [] result2 = MessageNano.toByteArray(msg); - - msg.clear().repeatedNestedMessage = - new TestAllTypesNano.NestedMessage[] { nestedMsg1, nestedMsg2 }; - byte [] result3 = MessageNano.toByteArray(msg); - - // Concatenate the three serializations and read as one message. - byte [] result = new byte[result1.length + result2.length + result3.length]; - System.arraycopy(result1, 0, result, 0, result1.length); - System.arraycopy(result2, 0, result, result1.length, result2.length); - System.arraycopy(result3, 0, result, result1.length + result2.length, result3.length); - - TestAllTypesNano newMsg = TestAllTypesNano.parseFrom(result); - assertEquals(789, newMsg.optionalInt32); - assertEquals(3, newMsg.repeatedNestedMessage.length); - assertEquals(nestedMsg0.bb, newMsg.repeatedNestedMessage[0].bb); - assertEquals(nestedMsg1.bb, newMsg.repeatedNestedMessage[1].bb); - assertEquals(nestedMsg2.bb, newMsg.repeatedNestedMessage[2].bb); - } - - /** - * Tests that invalid enum values from the wire are not accepted. - */ - public void testNanoEnumValidity() throws Exception { - final int invalid = 120; - final int alsoInvalid = 121; - - EnumValidity.M m = new EnumValidity.M(); - // Sanity check & baseline of the assertions for the first case below. - assertEquals(EnumValidity.E.default_, m.optionalE); - assertEquals(EnumValidity.E.BAZ, m.defaultE); - - m.optionalE = invalid; - m.defaultE = invalid; - // E contains all valid values - m.repeatedE = new int[] {EnumValidity.E.FOO, EnumValidity.E.BAR}; - m.packedE = new int[] {EnumValidity.E.FOO, EnumValidity.E.BAZ}; - // E2 contains some invalid values - m.repeatedE2 = new int[] {invalid, EnumValidity.E.BAR, alsoInvalid}; - m.packedE2 = new int[] {EnumValidity.E.FOO, invalid, alsoInvalid}; - // E3 contains all invalid values - m.repeatedE3 = new int[] {invalid, invalid}; - m.packedE3 = new int[] {alsoInvalid, alsoInvalid}; - byte[] serialized = MessageNano.toByteArray(m); - // Sanity check that we do have all data in the byte array. - assertEquals(31, serialized.length); - - // Test 1: tests that invalid values aren't included in the deserialized message. - EnumValidity.M deserialized = MessageNano.mergeFrom(new EnumValidity.M(), serialized); - assertEquals(EnumValidity.E.default_, deserialized.optionalE); - assertEquals(EnumValidity.E.BAZ, deserialized.defaultE); - assertTrue(Arrays.equals( - new int[] {EnumValidity.E.FOO, EnumValidity.E.BAR}, deserialized.repeatedE)); - assertTrue(Arrays.equals( - new int[] {EnumValidity.E.FOO, EnumValidity.E.BAZ}, deserialized.packedE)); - assertTrue(Arrays.equals( - new int[] {EnumValidity.E.BAR}, deserialized.repeatedE2)); - assertTrue(Arrays.equals( - new int[] {EnumValidity.E.FOO}, deserialized.packedE2)); - assertEquals(0, deserialized.repeatedE3.length); - assertEquals(0, deserialized.packedE3.length); - - // Test 2: tests that invalid values do not override previous values in the field, including - // arrays, including pre-existing invalid values. - deserialized.optionalE = EnumValidity.E.BAR; - deserialized.defaultE = alsoInvalid; - deserialized.repeatedE = new int[] {EnumValidity.E.BAZ}; - deserialized.packedE = new int[] {EnumValidity.E.BAZ, alsoInvalid}; - deserialized.repeatedE2 = new int[] {invalid, alsoInvalid}; - deserialized.packedE2 = null; - deserialized.repeatedE3 = null; - deserialized.packedE3 = new int[0]; - MessageNano.mergeFrom(deserialized, serialized); - assertEquals(EnumValidity.E.BAR, deserialized.optionalE); - assertEquals(alsoInvalid, deserialized.defaultE); - assertTrue(Arrays.equals( - new int[] {EnumValidity.E.BAZ, /* + */ EnumValidity.E.FOO, EnumValidity.E.BAR}, - deserialized.repeatedE)); - assertTrue(Arrays.equals( - new int[] {EnumValidity.E.BAZ, alsoInvalid, /* + */ EnumValidity.E.FOO, EnumValidity.E.BAZ}, - deserialized.packedE)); - assertTrue(Arrays.equals( - new int[] {invalid, alsoInvalid, /* + */ EnumValidity.E.BAR}, - deserialized.repeatedE2)); - assertTrue(Arrays.equals( - new int[] {/* <null> + */ EnumValidity.E.FOO}, - deserialized.packedE2)); - assertNull(deserialized.repeatedE3); // null + all invalid == null - assertEquals(0, deserialized.packedE3.length); // empty + all invalid == empty - - // Test 3: reading by alternative forms - EnumValidity.Alt alt = MessageNano.mergeFrom(new EnumValidity.Alt(), serialized); - assertEquals(EnumValidity.E.BAR, // last valid value in m.repeatedE2 - alt.repeatedE2AsOptional); - assertTrue(Arrays.equals(new int[] {EnumValidity.E.FOO}, alt.packedE2AsNonPacked)); - assertEquals(0, alt.nonPackedE3AsPacked.length); - } - - /** - * Tests the same as {@link #testNanoEnumValidity()} with accessor style. Repeated fields are - * not re-tested here because they are not affected by the accessor style. - */ - public void testNanoEnumValidityAccessors() throws Exception { - final int invalid = 120; - final int alsoInvalid = 121; - - EnumValidityAccessors.M m = new EnumValidityAccessors.M(); - // Sanity check & baseline of the assertions for the first case below. - assertEquals(EnumValidityAccessors.default_, m.getOptionalE()); - assertEquals(EnumValidityAccessors.BAZ, m.getDefaultE()); - - m.setOptionalE(invalid); - m.setDefaultE(invalid); - // Set repeatedE2 for Alt.repeatedE2AsOptional - m.repeatedE2 = new int[] {invalid, EnumValidityAccessors.BAR, alsoInvalid}; - byte[] serialized = MessageNano.toByteArray(m); - // Sanity check that we do have all data in the byte array. - assertEquals(10, serialized.length); - - // Test 1: tests that invalid values aren't included in the deserialized message. - EnumValidityAccessors.M deserialized = - MessageNano.mergeFrom(new EnumValidityAccessors.M(), serialized); - assertEquals(EnumValidityAccessors.default_, deserialized.getOptionalE()); - assertEquals(EnumValidityAccessors.BAZ, deserialized.getDefaultE()); - - // Test 2: tests that invalid values do not override previous values in the field, including - // pre-existing invalid values. - deserialized.setOptionalE(EnumValidityAccessors.BAR); - deserialized.setDefaultE(alsoInvalid); - MessageNano.mergeFrom(deserialized, serialized); - assertEquals(EnumValidityAccessors.BAR, deserialized.getOptionalE()); - assertEquals(alsoInvalid, deserialized.getDefaultE()); - - // Test 3: reading by alternative forms - EnumValidityAccessors.Alt alt = - MessageNano.mergeFrom(new EnumValidityAccessors.Alt(), serialized); - assertEquals(EnumValidityAccessors.BAR, // last valid value in m.repeatedE2 - alt.getRepeatedE2AsOptional()); - } - - /** - * Tests that code generation correctly wraps a single message into its outer - * class. The class {@code SingleMessageNano} is imported from the outer - * class {@code UnittestSingleNano}, whose name is implicit. Any error would - * cause this method to fail compilation. - */ - public void testNanoSingle() throws Exception { - SingleMessageNano msg = new SingleMessageNano(); - assertNotNull(msg); - } - - /** - * Tests that code generation correctly skips generating the outer class if - * unnecessary, letting a file-scope entity have the same name. The class - * {@code MultipleNameClashNano} shares the same name with the file's outer - * class defined explicitly, but the file contains no other entities and has - * java_multiple_files set. Any error would cause this method to fail - * compilation. - */ - public void testNanoMultipleNameClash() throws Exception { - MultipleNameClashNano msg = new MultipleNameClashNano(); - msg.field = 0; - } - - /** - * Tests that code generation correctly handles enums in different scopes in - * a source file with the option java_multiple_files set to true. Any error - * would cause this method to fail compilation. - */ - public void testNanoMultipleEnumScoping() throws Exception { - FileScopeEnumRefNano msg1 = new FileScopeEnumRefNano(); - msg1.enumField = UnittestMultipleNano.ONE; - MessageScopeEnumRefNano msg2 = new MessageScopeEnumRefNano(); - msg2.enumField = MessageScopeEnumRefNano.TWO; - } - - /** - * Tests that code generation with mixed values of the java_multiple_files - * options between the main source file and the imported source files would - * generate correct references. Any error would cause this method to fail - * compilation. - */ - public void testNanoMultipleImportingNonMultiple() throws Exception { - UnittestImportNano.ImportMessageNano importMsg = new UnittestImportNano.ImportMessageNano(); - MultipleImportingNonMultipleNano1 nano1 = new MultipleImportingNonMultipleNano1(); - nano1.field = importMsg; - MultipleImportingNonMultipleNano2 nano2 = new MultipleImportingNonMultipleNano2(); - nano2.nano1 = nano1; - } - - public void testNanoDefaults() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - for (int i = 0; i < 2; i++) { - assertEquals(41, msg.defaultInt32); - assertEquals(42, msg.defaultInt64); - assertEquals(43, msg.defaultUint32); - assertEquals(44, msg.defaultUint64); - assertEquals(-45, msg.defaultSint32); - assertEquals(46, msg.defaultSint64); - assertEquals(47, msg.defaultFixed32); - assertEquals(48, msg.defaultFixed64); - assertEquals(49, msg.defaultSfixed32); - assertEquals(-50, msg.defaultSfixed64); - assertTrue(51.5f == msg.defaultFloat); - assertTrue(52.0e3 == msg.defaultDouble); - assertEquals(true, msg.defaultBool); - assertEquals("hello", msg.defaultString); - assertEquals("world", new String(msg.defaultBytes, InternalNano.UTF_8)); - assertEquals("dünya", msg.defaultStringNonascii); - assertEquals("dünyab", new String(msg.defaultBytesNonascii, InternalNano.UTF_8)); - assertEquals(TestAllTypesNano.BAR, msg.defaultNestedEnum); - assertEquals(NanoOuterClass.FOREIGN_NANO_BAR, msg.defaultForeignEnum); - assertEquals(UnittestImportNano.IMPORT_NANO_BAR, msg.defaultImportEnum); - assertEquals(Float.POSITIVE_INFINITY, msg.defaultFloatInf); - assertEquals(Float.NEGATIVE_INFINITY, msg.defaultFloatNegInf); - assertEquals(Float.NaN, msg.defaultFloatNan); - assertEquals(Double.POSITIVE_INFINITY, msg.defaultDoubleInf); - assertEquals(Double.NEGATIVE_INFINITY, msg.defaultDoubleNegInf); - assertEquals(Double.NaN, msg.defaultDoubleNan); - - // Default values are not output, except for required fields. - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 3); - assertEquals(result.length, msgSerializedSize); - msg.clear(); - } - } - - public void testDifferentStringLengthsNano() throws Exception { - // Test string serialization roundtrip using strings of the following lengths, - // with ASCII and Unicode characters requiring different UTF-8 byte counts per - // char, hence causing the length delimiter varint to sometimes require more - // bytes for the Unicode strings than the ASCII string of the same length. - int[] lengths = new int[] { - 0, - 1, - (1 << 4) - 1, // 1 byte for ASCII and Unicode - (1 << 7) - 1, // 1 byte for ASCII, 2 bytes for Unicode - (1 << 11) - 1, // 2 bytes for ASCII and Unicode - (1 << 14) - 1, // 2 bytes for ASCII, 3 bytes for Unicode - (1 << 17) - 1, // 3 bytes for ASCII and Unicode - }; - for (int i : lengths) { - testEncodingOfString('q', i); // 1 byte per char - testEncodingOfString('\u07FF', i); // 2 bytes per char - testEncodingOfString('\u0981', i); // 3 bytes per char - } - } - - /** Regression test for https://github.com/google/protobuf/issues/292 */ - public void testCorrectExceptionThrowWhenEncodingStringsWithoutEnoughSpace() throws Exception { - String testCase = "Foooooooo"; - assertEquals(CodedOutputByteBufferNano.computeRawVarint32Size(testCase.length()), - CodedOutputByteBufferNano.computeRawVarint32Size(testCase.length() * 3)); - assertEquals(11, CodedOutputByteBufferNano.computeStringSize(1, testCase)); - // Tag is one byte, varint describing string length is 1 byte, string length is 9 bytes. - // An array of size 1 will cause a failure when trying to write the varint. - for (int i = 0; i < 11; i++) { - CodedOutputByteBufferNano bufferNano = CodedOutputByteBufferNano.newInstance(new byte[i]); - try { - bufferNano.writeString(1, testCase); - fail("Should have thrown an out of space exception"); - } catch (CodedOutputByteBufferNano.OutOfSpaceException expected) {} - } - } - - private void testEncodingOfString(char c, int length) throws InvalidProtocolBufferNanoException { - TestAllTypesNano testAllTypesNano = new TestAllTypesNano(); - final String fullString = fullString(c, length); - testAllTypesNano.optionalString = fullString; - final TestAllTypesNano resultNano = new TestAllTypesNano(); - MessageNano.mergeFrom(resultNano, MessageNano.toByteArray(testAllTypesNano)); - assertEquals(fullString, resultNano.optionalString); - } - - private String fullString(char c, int length) { - char[] result = new char[length]; - Arrays.fill(result, c); - return new String(result); - } - - public void testNanoWithHasParseFrom() throws Exception { - TestAllTypesNanoHas msg = null; - // Test false on creation, after clear and upon empty parse. - for (int i = 0; i < 3; i++) { - if (i == 0) { - msg = new TestAllTypesNanoHas(); - } else if (i == 1) { - msg.clear(); - } else if (i == 2) { - msg = TestAllTypesNanoHas.parseFrom(new byte[0]); - } - assertFalse(msg.hasOptionalInt32); - assertFalse(msg.hasOptionalString); - assertFalse(msg.hasOptionalBytes); - assertFalse(msg.hasOptionalNestedEnum); - assertFalse(msg.hasDefaultInt32); - assertFalse(msg.hasDefaultString); - assertFalse(msg.hasDefaultBytes); - assertFalse(msg.hasDefaultFloatNan); - assertFalse(msg.hasDefaultNestedEnum); - assertFalse(msg.hasId); - assertFalse(msg.hasRequiredEnum); - msg.optionalInt32 = 123; - msg.optionalNestedMessage = new TestAllTypesNanoHas.NestedMessage(); - msg.optionalNestedMessage.bb = 2; - msg.optionalNestedEnum = TestAllTypesNano.BAZ; - } - - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 10); - assertEquals(result.length, msgSerializedSize); - - // Has fields true upon parse. - TestAllTypesNanoHas newMsg = TestAllTypesNanoHas.parseFrom(result); - assertEquals(123, newMsg.optionalInt32); - assertTrue(newMsg.hasOptionalInt32); - assertEquals(2, newMsg.optionalNestedMessage.bb); - assertTrue(newMsg.optionalNestedMessage.hasBb); - assertEquals(TestAllTypesNanoHas.BAZ, newMsg.optionalNestedEnum); - assertTrue(newMsg.hasOptionalNestedEnum); - } - - public void testNanoWithHasSerialize() throws Exception { - TestAllTypesNanoHas msg = new TestAllTypesNanoHas(); - msg.hasOptionalInt32 = true; - msg.hasOptionalString = true; - msg.hasOptionalBytes = true; - msg.optionalNestedMessage = new TestAllTypesNanoHas.NestedMessage(); - msg.optionalNestedMessage.hasBb = true; - msg.hasOptionalNestedEnum = true; - msg.hasDefaultInt32 = true; - msg.hasDefaultString = true; - msg.hasDefaultBytes = true; - msg.hasDefaultFloatNan = true; - msg.hasDefaultNestedEnum = true; - msg.hasId = true; - msg.hasRequiredEnum = true; - - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - assertEquals(result.length, msgSerializedSize); - - // Now deserialize and find that all fields are set and equal to their defaults. - TestAllTypesNanoHas newMsg = TestAllTypesNanoHas.parseFrom(result); - assertTrue(newMsg.hasOptionalInt32); - assertTrue(newMsg.hasOptionalString); - assertTrue(newMsg.hasOptionalBytes); - assertTrue(newMsg.optionalNestedMessage.hasBb); - assertTrue(newMsg.hasOptionalNestedEnum); - assertTrue(newMsg.hasDefaultInt32); - assertTrue(newMsg.hasDefaultString); - assertTrue(newMsg.hasDefaultBytes); - assertTrue(newMsg.hasDefaultFloatNan); - assertTrue(newMsg.hasDefaultNestedEnum); - assertTrue(newMsg.hasId); - assertTrue(newMsg.hasRequiredEnum); - assertEquals(0, newMsg.optionalInt32); - assertEquals(0, newMsg.optionalString.length()); - assertEquals(0, newMsg.optionalBytes.length); - assertEquals(0, newMsg.optionalNestedMessage.bb); - assertEquals(TestAllTypesNanoHas.FOO, newMsg.optionalNestedEnum); - assertEquals(41, newMsg.defaultInt32); - assertEquals("hello", newMsg.defaultString); - assertEquals("world", new String(newMsg.defaultBytes, InternalNano.UTF_8)); - assertEquals(TestAllTypesNanoHas.BAR, newMsg.defaultNestedEnum); - assertEquals(Float.NaN, newMsg.defaultFloatNan); - assertEquals(0, newMsg.id); - assertEquals(TestAllTypesNanoHas.FOO, newMsg.requiredEnum); - } - - public void testNanoWithAccessorsBasic() throws Exception { - TestNanoAccessors msg = new TestNanoAccessors(); - - // Makes sure required, repeated, and message fields are still public - msg.id = 3; - msg.repeatedBytes = new byte[2][3]; - msg.optionalNestedMessage = null; - - // Test accessors - assertEquals(0, msg.getOptionalInt32()); - assertFalse(msg.hasOptionalInt32()); - msg.setOptionalInt32(135); - assertEquals(135, msg.getOptionalInt32()); - assertTrue(msg.hasOptionalInt32()); - msg.clearOptionalInt32(); - assertFalse(msg.hasOptionalInt32()); - msg.setOptionalInt32(0); // default value - assertTrue(msg.hasOptionalInt32()); - - // Test NPE - try { - msg.setOptionalBytes(null); - fail(); - } catch (NullPointerException expected) {} - try { - msg.setOptionalString(null); - fail(); - } catch (NullPointerException expected) {} - - // Test has bit on bytes field with defaults and clear() re-clones the default array - assertFalse(msg.hasDefaultBytes()); - byte[] defaultBytes = msg.getDefaultBytes(); - msg.setDefaultBytes(defaultBytes); - assertTrue(msg.hasDefaultBytes()); - msg.clearDefaultBytes(); - assertFalse(msg.hasDefaultBytes()); - defaultBytes[0]++; // modify original array - assertFalse(Arrays.equals(defaultBytes, msg.getDefaultBytes())); - - // Test has bits that require additional bit fields - assertFalse(msg.hasBitFieldCheck()); - msg.setBitFieldCheck(0); - assertTrue(msg.hasBitFieldCheck()); - assertFalse(msg.hasBeforeBitFieldCheck()); // checks bit field does not leak - assertFalse(msg.hasAfterBitFieldCheck()); - - // Test clear() clears has bits - msg.setOptionalString("hi"); - msg.setDefaultString("there"); - msg.clear(); - assertFalse(msg.hasOptionalString()); - assertFalse(msg.hasDefaultString()); - assertFalse(msg.hasBitFieldCheck()); - - // Test set() and clear() returns itself (compiles = success) - msg.clear() - .setOptionalInt32(3) - .clearDefaultBytes() - .setOptionalString("4"); - } - - public void testNanoWithAccessorsParseFrom() throws Exception { - TestNanoAccessors msg = null; - // Test false on creation, after clear and upon empty parse. - for (int i = 0; i < 3; i++) { - if (i == 0) { - msg = new TestNanoAccessors(); - } else if (i == 1) { - msg.clear(); - } else if (i == 2) { - msg = TestNanoAccessors.parseFrom(new byte[0]); - } - assertFalse(msg.hasOptionalInt32()); - assertFalse(msg.hasOptionalString()); - assertFalse(msg.hasOptionalBytes()); - assertFalse(msg.hasOptionalNestedEnum()); - assertFalse(msg.hasDefaultInt32()); - assertFalse(msg.hasDefaultString()); - assertFalse(msg.hasDefaultBytes()); - assertFalse(msg.hasDefaultFloatNan()); - assertFalse(msg.hasDefaultNestedEnum()); - msg.optionalNestedMessage = new TestNanoAccessors.NestedMessage(); - msg.optionalNestedMessage.setBb(2); - msg.setOptionalNestedEnum(TestNanoAccessors.BAZ); - msg.setDefaultInt32(msg.getDefaultInt32()); - } - - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - //System.out.printf("mss=%d result.length=%d\n", msgSerializedSize, result.length); - assertTrue(msgSerializedSize == 14); - assertEquals(result.length, msgSerializedSize); - - // Has fields true upon parse. - TestNanoAccessors newMsg = TestNanoAccessors.parseFrom(result); - assertEquals(2, newMsg.optionalNestedMessage.getBb()); - assertTrue(newMsg.optionalNestedMessage.hasBb()); - assertEquals(TestNanoAccessors.BAZ, newMsg.getOptionalNestedEnum()); - assertTrue(newMsg.hasOptionalNestedEnum()); - - // Has field true on fields with explicit default values from wire. - assertTrue(newMsg.hasDefaultInt32()); - assertEquals(41, newMsg.getDefaultInt32()); - } - - public void testNanoWithAccessorsPublicFieldTypes() throws Exception { - TestNanoAccessors msg = new TestNanoAccessors(); - assertNull(msg.optionalNestedMessage); - assertEquals(0, msg.id); - assertEquals(0, msg.repeatedNestedEnum.length); - - TestNanoAccessors newMsg = TestNanoAccessors.parseFrom(MessageNano.toByteArray(msg)); - assertNull(newMsg.optionalNestedMessage); - assertEquals(0, newMsg.id); - assertEquals(0, newMsg.repeatedNestedEnum.length); - - TestNanoAccessors.NestedMessage nestedMessage = new TestNanoAccessors.NestedMessage(); - nestedMessage.setBb(5); - newMsg.optionalNestedMessage = nestedMessage; - newMsg.id = -1; - newMsg.repeatedNestedEnum = new int[] { TestAllTypesNano.FOO }; - - TestNanoAccessors newMsg2 = TestNanoAccessors.parseFrom(MessageNano.toByteArray(newMsg)); - assertEquals(nestedMessage.getBb(), newMsg2.optionalNestedMessage.getBb()); - assertEquals(-1, newMsg2.id); - assertEquals(TestAllTypesNano.FOO, newMsg2.repeatedNestedEnum[0]); - - newMsg2.optionalNestedMessage = null; - newMsg2.id = 0; - newMsg2.repeatedNestedEnum = null; - - TestNanoAccessors newMsg3 = TestNanoAccessors.parseFrom(MessageNano.toByteArray(newMsg2)); - assertNull(newMsg3.optionalNestedMessage); - assertEquals(0, newMsg3.id); - assertEquals(0, newMsg3.repeatedNestedEnum.length); - } - - public void testNanoWithAccessorsSerialize() throws Exception { - TestNanoAccessors msg = new TestNanoAccessors(); - msg.setOptionalInt32(msg.getOptionalInt32()); - msg.setOptionalString(msg.getOptionalString()); - msg.setOptionalBytes(msg.getOptionalBytes()); - TestNanoAccessors.NestedMessage nestedMessage = new TestNanoAccessors.NestedMessage(); - nestedMessage.setBb(nestedMessage.getBb()); - msg.optionalNestedMessage = nestedMessage; - msg.setOptionalNestedEnum(msg.getOptionalNestedEnum()); - msg.setDefaultInt32(msg.getDefaultInt32()); - msg.setDefaultString(msg.getDefaultString()); - msg.setDefaultBytes(msg.getDefaultBytes()); - msg.setDefaultFloatNan(msg.getDefaultFloatNan()); - msg.setDefaultNestedEnum(msg.getDefaultNestedEnum()); - - byte [] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - assertEquals(result.length, msgSerializedSize); - - // Now deserialize and find that all fields are set and equal to their defaults. - TestNanoAccessors newMsg = TestNanoAccessors.parseFrom(result); - assertTrue(newMsg.hasOptionalInt32()); - assertTrue(newMsg.hasOptionalString()); - assertTrue(newMsg.hasOptionalBytes()); - assertTrue(newMsg.optionalNestedMessage.hasBb()); - assertTrue(newMsg.hasOptionalNestedEnum()); - assertTrue(newMsg.hasDefaultInt32()); - assertTrue(newMsg.hasDefaultString()); - assertTrue(newMsg.hasDefaultBytes()); - assertTrue(newMsg.hasDefaultFloatNan()); - assertTrue(newMsg.hasDefaultNestedEnum()); - assertEquals(0, newMsg.getOptionalInt32()); - assertEquals(0, newMsg.getOptionalString().length()); - assertEquals(0, newMsg.getOptionalBytes().length); - assertEquals(0, newMsg.optionalNestedMessage.getBb()); - assertEquals(TestNanoAccessors.FOO, newMsg.getOptionalNestedEnum()); - assertEquals(41, newMsg.getDefaultInt32()); - assertEquals("hello", newMsg.getDefaultString()); - assertEquals("world", new String(newMsg.getDefaultBytes(), InternalNano.UTF_8)); - assertEquals(TestNanoAccessors.BAR, newMsg.getDefaultNestedEnum()); - assertEquals(Float.NaN, newMsg.getDefaultFloatNan()); - assertEquals(0, newMsg.id); - } - - public void testNanoJavaEnumStyle() throws Exception { - EnumClassNanos.EnumClassNano msg = new EnumClassNanos.EnumClassNano(); - assertEquals(EnumClassNanos.FileScopeEnum.ONE, msg.one); - assertEquals(EnumClassNanos.EnumClassNano.MessageScopeEnum.TWO, msg.two); - - EnumClassNanoMultiple msg2 = new EnumClassNanoMultiple(); - assertEquals(FileScopeEnumMultiple.THREE, msg2.three); - assertEquals(EnumClassNanoMultiple.MessageScopeEnumMultiple.FOUR, msg2.four); - } - - /** - * Tests that fields with a default value of NaN are not serialized when - * set to NaN. This is a special case as NaN != NaN, so normal equality - * checks don't work. - */ - public void testNanoNotANumberDefaults() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.defaultDoubleNan = 0; - msg.defaultFloatNan = 0; - byte[] result = MessageNano.toByteArray(msg); - int msgSerializedSize = msg.getSerializedSize(); - assertTrue(result.length == msgSerializedSize); - assertTrue(msgSerializedSize > 3); - - msg.defaultDoubleNan = Double.NaN; - msg.defaultFloatNan = Float.NaN; - result = MessageNano.toByteArray(msg); - msgSerializedSize = msg.getSerializedSize(); - assertEquals(3, result.length); - assertEquals(3, msgSerializedSize); - } - - /** - * Test that a bug in skipRawBytes() has been fixed: if the skip skips - * exactly up to a limit, this should not break things. - */ - public void testSkipRawBytesBug() throws Exception { - byte[] rawBytes = new byte[] { 1, 2 }; - CodedInputByteBufferNano input = CodedInputByteBufferNano.newInstance(rawBytes); - - int limit = input.pushLimit(1); - input.skipRawBytes(1); - input.popLimit(limit); - assertEquals(2, input.readRawByte()); - } - - /** - * Test that a bug in skipRawBytes() has been fixed: if the skip skips - * past the end of a buffer with a limit that has been set past the end of - * that buffer, this should not break things. - */ - public void testSkipRawBytesPastEndOfBufferWithLimit() throws Exception { - byte[] rawBytes = new byte[] { 1, 2, 3, 4, 5 }; - CodedInputByteBufferNano input = CodedInputByteBufferNano.newInstance(rawBytes); - - int limit = input.pushLimit(4); - // In order to expose the bug we need to read at least one byte to prime the - // buffer inside the CodedInputStream. - assertEquals(1, input.readRawByte()); - // Skip to the end of the limit. - input.skipRawBytes(3); - assertTrue(input.isAtEnd()); - input.popLimit(limit); - assertEquals(5, input.readRawByte()); - } - - // Test a smattering of various proto types for printing - public void testMessageNanoPrinter() { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.optionalInt32 = 14; - msg.optionalFloat = 42.3f; - msg.optionalString = "String \"with' both quotes"; - msg.optionalBytes = new byte[] {'"', '\0', 1, 8}; - msg.optionalGroup = new TestAllTypesNano.OptionalGroup(); - msg.optionalGroup.a = 15; - msg.repeatedInt64 = new long[2]; - msg.repeatedInt64[0] = 1L; - msg.repeatedInt64[1] = -1L; - msg.repeatedBytes = new byte[2][]; - msg.repeatedBytes[1] = new byte[] {'h', 'e', 'l', 'l', 'o'}; - msg.repeatedGroup = new TestAllTypesNano.RepeatedGroup[2]; - msg.repeatedGroup[0] = new TestAllTypesNano.RepeatedGroup(); - msg.repeatedGroup[0].a = -27; - msg.repeatedGroup[1] = new TestAllTypesNano.RepeatedGroup(); - msg.repeatedGroup[1].a = -72; - msg.optionalNestedMessage = new TestAllTypesNano.NestedMessage(); - msg.optionalNestedMessage.bb = 7; - msg.repeatedNestedMessage = new TestAllTypesNano.NestedMessage[2]; - msg.repeatedNestedMessage[0] = new TestAllTypesNano.NestedMessage(); - msg.repeatedNestedMessage[0].bb = 77; - msg.repeatedNestedMessage[1] = new TestAllTypesNano.NestedMessage(); - msg.repeatedNestedMessage[1].bb = 88; - msg.optionalNestedEnum = TestAllTypesNano.BAZ; - msg.repeatedNestedEnum = new int[2]; - msg.repeatedNestedEnum[0] = TestAllTypesNano.BAR; - msg.repeatedNestedEnum[1] = TestAllTypesNano.FOO; - msg.repeatedStringPiece = new String[] {null, "world"}; - msg.setOneofString("hello"); - - String protoPrint = msg.toString(); - assertTrue(protoPrint.contains("optional_int32: 14")); - assertTrue(protoPrint.contains("optional_float: 42.3")); - assertTrue(protoPrint.contains("optional_double: 0.0")); - assertTrue(protoPrint.contains("optional_string: \"String \\u0022with\\u0027 both quotes\"")); - assertTrue(protoPrint.contains("optional_bytes: \"\\\"\\000\\001\\010\"")); - assertTrue(protoPrint.contains("optional_group <\n a: 15\n>")); - - assertTrue(protoPrint.contains("repeated_int64: 1\nrepeated_int64: -1")); - assertFalse(protoPrint.contains("repeated_bytes: \"\"")); // null should be dropped - assertTrue(protoPrint.contains("repeated_bytes: \"hello\"")); - assertTrue(protoPrint.contains("repeated_group <\n a: -27\n>\n" - + "repeated_group <\n a: -72\n>")); - assertTrue(protoPrint.contains("optional_nested_message <\n bb: 7\n>")); - assertTrue(protoPrint.contains("repeated_nested_message <\n bb: 77\n>\n" - + "repeated_nested_message <\n bb: 88\n>")); - assertTrue(protoPrint.contains("optional_nested_enum: 3")); - assertTrue(protoPrint.contains("repeated_nested_enum: 2\nrepeated_nested_enum: 1")); - assertTrue(protoPrint.contains("default_int32: 41")); - assertTrue(protoPrint.contains("default_string: \"hello\"")); - assertFalse(protoPrint.contains("repeated_string_piece: \"\"")); // null should be dropped - assertTrue(protoPrint.contains("repeated_string_piece: \"world\"")); - assertTrue(protoPrint.contains("oneof_string: \"hello\"")); - } - - public void testMessageNanoPrinterAccessors() throws Exception { - TestNanoAccessors msg = new TestNanoAccessors(); - msg.setOptionalInt32(13); - msg.setOptionalString("foo"); - msg.setOptionalBytes(new byte[] {'"', '\0', 1, 8}); - msg.optionalNestedMessage = new TestNanoAccessors.NestedMessage(); - msg.optionalNestedMessage.setBb(7); - msg.setOptionalNestedEnum(TestNanoAccessors.BAZ); - msg.repeatedInt32 = new int[] { 1, -1 }; - msg.repeatedString = new String[] { "Hello", "world" }; - msg.repeatedBytes = new byte[2][]; - msg.repeatedBytes[1] = new byte[] {'h', 'e', 'l', 'l', 'o'}; - msg.repeatedNestedMessage = new TestNanoAccessors.NestedMessage[2]; - msg.repeatedNestedMessage[0] = new TestNanoAccessors.NestedMessage(); - msg.repeatedNestedMessage[0].setBb(5); - msg.repeatedNestedMessage[1] = new TestNanoAccessors.NestedMessage(); - msg.repeatedNestedMessage[1].setBb(6); - msg.repeatedNestedEnum = new int[] { TestNanoAccessors.FOO, TestNanoAccessors.BAR }; - msg.id = 33; - - String protoPrint = msg.toString(); - assertTrue(protoPrint.contains("optional_int32: 13")); - assertTrue(protoPrint.contains("optional_string: \"foo\"")); - assertTrue(protoPrint.contains("optional_bytes: \"\\\"\\000\\001\\010\"")); - assertTrue(protoPrint.contains("optional_nested_message <\n bb: 7\n>")); - assertTrue(protoPrint.contains("optional_nested_enum: 3")); - assertTrue(protoPrint.contains("repeated_int32: 1\nrepeated_int32: -1")); - assertTrue(protoPrint.contains("repeated_string: \"Hello\"\nrepeated_string: \"world\"")); - assertFalse(protoPrint.contains("repeated_bytes: \"\"")); // null should be dropped - assertTrue(protoPrint.contains("repeated_bytes: \"hello\"")); - assertTrue(protoPrint.contains("repeated_nested_message <\n bb: 5\n>\n" - + "repeated_nested_message <\n bb: 6\n>")); - assertTrue(protoPrint.contains("repeated_nested_enum: 1\nrepeated_nested_enum: 2")); - assertTrue(protoPrint.contains("id: 33")); - } - - public void testMessageNanoPrinterForMaps() throws Exception { - TestMap msg = new TestMap(); - MessageValue msgValues[] = new MessageValue[] { - new MessageValue(), new MessageValue() - }; - msgValues[0].value = 1; - msgValues[1].value = 2; - msg.int32ToBytesField = new HashMap<Integer, byte[]>(); - msg.int32ToBytesField.put(1, new byte[] {'"', '\0'}); - msg.int32ToBytesField.put(2, new byte[] {1, 8}); - msg.stringToInt32Field = new HashMap<String, Integer>(); - msg.stringToInt32Field.put("hello", 1); - msg.stringToInt32Field.put("world", 2); - msg.int32ToMessageField = new HashMap<Integer, MapTestProto.TestMap.MessageValue>(); - msg.int32ToMessageField.put(0, msgValues[0]); - msg.int32ToMessageField.put(1, msgValues[1]); - msg.int32ToEnumField = new HashMap<Integer, Integer>(); - msg.int32ToEnumField.put(1, 2); - msg.int32ToEnumField.put(2, 3); - String protoPrint = msg.toString(); - - assertTrue(protoPrint.contains( - "int32_to_bytes_field <\n key: 1\n value: \"\\\"\\000\"\n>")); - assertTrue(protoPrint.contains( - "int32_to_bytes_field <\n key: 2\n value: \"\\001\\010\"\n>")); - assertTrue(protoPrint.contains( - "string_to_int32_field <\n key: \"hello\"\n value: 1\n>")); - assertTrue(protoPrint.contains( - "string_to_int32_field <\n key: \"world\"\n value: 2\n>")); - assertTrue(protoPrint.contains( - "int32_to_message_field <\n key: 0\n value <\n value: 1\n")); - assertTrue(protoPrint.contains( - "int32_to_message_field <\n key: 1\n value <\n value: 2\n")); - assertTrue(protoPrint.contains( - "int32_to_enum_field <\n key: 1\n value: 2\n>")); - assertTrue(protoPrint.contains( - "int32_to_enum_field <\n key: 2\n value: 3\n>")); - } - - public void testExtensions() throws Exception { - Extensions.ExtendableMessage message = new Extensions.ExtendableMessage(); - message.field = 5; - int[] int32s = {1, 2}; - int[] uint32s = {3, 4}; - int[] sint32s = {-5, -6}; - long[] int64s = {7, 8}; - long[] uint64s = {9, 10}; - long[] sint64s = {-11, -12}; - int[] fixed32s = {13, 14}; - int[] sfixed32s = {-15, -16}; - long[] fixed64s = {17, 18}; - long[] sfixed64s = {-19, -20}; - boolean[] bools = {true, false}; - float[] floats = {2.1f, 2.2f}; - double[] doubles = {2.3, 2.4}; - int[] enums = {Extensions.SECOND_VALUE, Extensions.FIRST_VALUE}; - String[] strings = {"vijfentwintig", "twenty-six"}; - byte[][] bytess = {{2, 7}, {2, 8}}; - AnotherMessage another1 = new AnotherMessage(); - another1.string = "er shi jiu"; - another1.value = false; - AnotherMessage another2 = new AnotherMessage(); - another2.string = "trente"; - another2.value = true; - AnotherMessage[] messages = {another1, another2}; - RepeatedExtensions.RepeatedGroup group1 = new RepeatedExtensions.RepeatedGroup(); - group1.a = 31; - RepeatedExtensions.RepeatedGroup group2 = new RepeatedExtensions.RepeatedGroup(); - group2.a = 32; - RepeatedExtensions.RepeatedGroup[] groups = {group1, group2}; - assertFalse(message.hasExtension(RepeatedExtensions.repeatedInt32)); - message.setExtension(RepeatedExtensions.repeatedInt32, int32s); - assertTrue(message.hasExtension(RepeatedExtensions.repeatedInt32)); - assertFalse(message.hasExtension(RepeatedExtensions.repeatedUint32)); - message.setExtension(RepeatedExtensions.repeatedUint32, uint32s); - assertTrue(message.hasExtension(RepeatedExtensions.repeatedUint32)); - message.setExtension(RepeatedExtensions.repeatedSint32, sint32s); - assertFalse(message.hasExtension(RepeatedExtensions.repeatedInt64)); - message.setExtension(RepeatedExtensions.repeatedInt64, int64s); - assertTrue(message.hasExtension(RepeatedExtensions.repeatedInt64)); - assertFalse(message.hasExtension(RepeatedExtensions.repeatedUint64)); - message.setExtension(RepeatedExtensions.repeatedUint64, uint64s); - assertTrue(message.hasExtension(RepeatedExtensions.repeatedUint64)); - assertFalse(message.hasExtension(RepeatedExtensions.repeatedSint64)); - message.setExtension(RepeatedExtensions.repeatedSint64, sint64s); - assertTrue(message.hasExtension(RepeatedExtensions.repeatedSint64)); - assertFalse(message.hasExtension(RepeatedExtensions.repeatedFixed32)); - message.setExtension(RepeatedExtensions.repeatedFixed32, fixed32s); - assertTrue(message.hasExtension(RepeatedExtensions.repeatedFixed32)); - assertFalse(message.hasExtension(RepeatedExtensions.repeatedSfixed32)); - message.setExtension(RepeatedExtensions.repeatedSfixed32, sfixed32s); - assertTrue(message.hasExtension(RepeatedExtensions.repeatedSfixed32)); - assertFalse(message.hasExtension(RepeatedExtensions.repeatedFixed64)); - message.setExtension(RepeatedExtensions.repeatedFixed64, fixed64s); - assertTrue(message.hasExtension(RepeatedExtensions.repeatedFixed64)); - assertFalse(message.hasExtension(RepeatedExtensions.repeatedSfixed64)); - message.setExtension(RepeatedExtensions.repeatedSfixed64, sfixed64s); - assertTrue(message.hasExtension(RepeatedExtensions.repeatedSfixed64)); - assertFalse(message.hasExtension(RepeatedExtensions.repeatedBool)); - message.setExtension(RepeatedExtensions.repeatedBool, bools); - assertTrue(message.hasExtension(RepeatedExtensions.repeatedBool)); - assertFalse(message.hasExtension(RepeatedExtensions.repeatedFloat)); - message.setExtension(RepeatedExtensions.repeatedFloat, floats); - assertTrue(message.hasExtension(RepeatedExtensions.repeatedFloat)); - assertFalse(message.hasExtension(RepeatedExtensions.repeatedDouble)); - message.setExtension(RepeatedExtensions.repeatedDouble, doubles); - assertTrue(message.hasExtension(RepeatedExtensions.repeatedDouble)); - assertFalse(message.hasExtension(RepeatedExtensions.repeatedEnum)); - message.setExtension(RepeatedExtensions.repeatedEnum, enums); - assertTrue(message.hasExtension(RepeatedExtensions.repeatedEnum)); - assertFalse(message.hasExtension(RepeatedExtensions.repeatedString)); - message.setExtension(RepeatedExtensions.repeatedString, strings); - assertTrue(message.hasExtension(RepeatedExtensions.repeatedString)); - assertFalse(message.hasExtension(RepeatedExtensions.repeatedBytes)); - message.setExtension(RepeatedExtensions.repeatedBytes, bytess); - assertTrue(message.hasExtension(RepeatedExtensions.repeatedBytes)); - assertFalse(message.hasExtension(RepeatedExtensions.repeatedMessage)); - message.setExtension(RepeatedExtensions.repeatedMessage, messages); - assertTrue(message.hasExtension(RepeatedExtensions.repeatedMessage)); - assertFalse(message.hasExtension(RepeatedExtensions.repeatedGroup)); - message.setExtension(RepeatedExtensions.repeatedGroup, groups); - assertTrue(message.hasExtension(RepeatedExtensions.repeatedGroup)); - - byte[] data = MessageNano.toByteArray(message); - message = Extensions.ExtendableMessage.parseFrom(data); - assertEquals(5, message.field); - - // Test reading back using SingularExtensions: the retrieved value should equal the last - // in each array. - assertEquals(int32s[1], (int) message.getExtension(SingularExtensions.someInt32)); - assertEquals(uint32s[1], (int) message.getExtension(SingularExtensions.someUint32)); - assertEquals(sint32s[1], (int) message.getExtension(SingularExtensions.someSint32)); - assertEquals(int64s[1], (long) message.getExtension(SingularExtensions.someInt64)); - assertEquals(uint64s[1], (long) message.getExtension(SingularExtensions.someUint64)); - assertEquals(sint64s[1], (long) message.getExtension(SingularExtensions.someSint64)); - assertEquals(fixed32s[1], (int) message.getExtension(SingularExtensions.someFixed32)); - assertEquals(sfixed32s[1], (int) message.getExtension(SingularExtensions.someSfixed32)); - assertEquals(fixed64s[1], (long) message.getExtension(SingularExtensions.someFixed64)); - assertEquals(sfixed64s[1], (long) message.getExtension(SingularExtensions.someSfixed64)); - assertEquals(bools[1], (boolean) message.getExtension(SingularExtensions.someBool)); - assertEquals(floats[1], (float) message.getExtension(SingularExtensions.someFloat)); - assertEquals(doubles[1], (double) message.getExtension(SingularExtensions.someDouble)); - assertEquals(enums[1], (int) message.getExtension(SingularExtensions.someEnum)); - assertEquals(strings[1], message.getExtension(SingularExtensions.someString)); - assertTrue(Arrays.equals(bytess[1], message.getExtension(SingularExtensions.someBytes))); - AnotherMessage deserializedMessage = message.getExtension(SingularExtensions.someMessage); - assertEquals(another2.string, deserializedMessage.string); - assertEquals(another2.value, deserializedMessage.value); - assertEquals(group2.a, message.getExtension(SingularExtensions.someGroup).a); - - // Test reading back using RepeatedExtensions: the arrays should be equal. - message = Extensions.ExtendableMessage.parseFrom(data); - assertEquals(5, message.field); - assertTrue(Arrays.equals(int32s, message.getExtension(RepeatedExtensions.repeatedInt32))); - assertTrue(Arrays.equals(uint32s, message.getExtension(RepeatedExtensions.repeatedUint32))); - assertTrue(Arrays.equals(sint32s, message.getExtension(RepeatedExtensions.repeatedSint32))); - assertTrue(Arrays.equals(int64s, message.getExtension(RepeatedExtensions.repeatedInt64))); - assertTrue(Arrays.equals(uint64s, message.getExtension(RepeatedExtensions.repeatedUint64))); - assertTrue(Arrays.equals(sint64s, message.getExtension(RepeatedExtensions.repeatedSint64))); - assertTrue(Arrays.equals(fixed32s, message.getExtension(RepeatedExtensions.repeatedFixed32))); - assertTrue(Arrays.equals(sfixed32s, message.getExtension(RepeatedExtensions.repeatedSfixed32))); - assertTrue(Arrays.equals(fixed64s, message.getExtension(RepeatedExtensions.repeatedFixed64))); - assertTrue(Arrays.equals(sfixed64s, message.getExtension(RepeatedExtensions.repeatedSfixed64))); - assertTrue(Arrays.equals(bools, message.getExtension(RepeatedExtensions.repeatedBool))); - assertTrue(Arrays.equals(floats, message.getExtension(RepeatedExtensions.repeatedFloat))); - assertTrue(Arrays.equals(doubles, message.getExtension(RepeatedExtensions.repeatedDouble))); - assertTrue(Arrays.equals(enums, message.getExtension(RepeatedExtensions.repeatedEnum))); - assertTrue(Arrays.equals(strings, message.getExtension(RepeatedExtensions.repeatedString))); - byte[][] deserializedRepeatedBytes = message.getExtension(RepeatedExtensions.repeatedBytes); - assertEquals(2, deserializedRepeatedBytes.length); - assertTrue(Arrays.equals(bytess[0], deserializedRepeatedBytes[0])); - assertTrue(Arrays.equals(bytess[1], deserializedRepeatedBytes[1])); - AnotherMessage[] deserializedRepeatedMessage = - message.getExtension(RepeatedExtensions.repeatedMessage); - assertEquals(2, deserializedRepeatedMessage.length); - assertEquals(another1.string, deserializedRepeatedMessage[0].string); - assertEquals(another1.value, deserializedRepeatedMessage[0].value); - assertEquals(another2.string, deserializedRepeatedMessage[1].string); - assertEquals(another2.value, deserializedRepeatedMessage[1].value); - RepeatedExtensions.RepeatedGroup[] deserializedRepeatedGroup = - message.getExtension(RepeatedExtensions.repeatedGroup); - assertEquals(2, deserializedRepeatedGroup.length); - assertEquals(group1.a, deserializedRepeatedGroup[0].a); - assertEquals(group2.a, deserializedRepeatedGroup[1].a); - - message = Extensions.ExtendableMessage.parseFrom(data); - assertEquals(5, message.field); - // Test hasExtension using PackedExtensions. - assertTrue(message.hasExtension(PackedExtensions.packedInt32)); - assertTrue(message.hasExtension(PackedExtensions.packedUint32)); - assertTrue(message.hasExtension(PackedExtensions.packedSint32)); - assertTrue(message.hasExtension(PackedExtensions.packedInt64)); - assertTrue(message.hasExtension(PackedExtensions.packedUint64)); - assertTrue(message.hasExtension(PackedExtensions.packedSint64)); - assertTrue(message.hasExtension(PackedExtensions.packedFixed32)); - assertTrue(message.hasExtension(PackedExtensions.packedSfixed32)); - assertTrue(message.hasExtension(PackedExtensions.packedFixed64)); - assertTrue(message.hasExtension(PackedExtensions.packedSfixed64)); - assertTrue(message.hasExtension(PackedExtensions.packedBool)); - assertTrue(message.hasExtension(PackedExtensions.packedFloat)); - assertTrue(message.hasExtension(PackedExtensions.packedDouble)); - assertTrue(message.hasExtension(PackedExtensions.packedEnum)); - - // Test reading back using PackedExtensions: the arrays should be equal, even the fields - // are non-packed. - assertTrue(Arrays.equals(int32s, message.getExtension(PackedExtensions.packedInt32))); - assertTrue(Arrays.equals(uint32s, message.getExtension(PackedExtensions.packedUint32))); - assertTrue(Arrays.equals(sint32s, message.getExtension(PackedExtensions.packedSint32))); - assertTrue(Arrays.equals(int64s, message.getExtension(PackedExtensions.packedInt64))); - assertTrue(Arrays.equals(uint64s, message.getExtension(PackedExtensions.packedUint64))); - assertTrue(Arrays.equals(sint64s, message.getExtension(PackedExtensions.packedSint64))); - assertTrue(Arrays.equals(fixed32s, message.getExtension(PackedExtensions.packedFixed32))); - assertTrue(Arrays.equals(sfixed32s, message.getExtension(PackedExtensions.packedSfixed32))); - assertTrue(Arrays.equals(fixed64s, message.getExtension(PackedExtensions.packedFixed64))); - assertTrue(Arrays.equals(sfixed64s, message.getExtension(PackedExtensions.packedSfixed64))); - assertTrue(Arrays.equals(bools, message.getExtension(PackedExtensions.packedBool))); - assertTrue(Arrays.equals(floats, message.getExtension(PackedExtensions.packedFloat))); - assertTrue(Arrays.equals(doubles, message.getExtension(PackedExtensions.packedDouble))); - assertTrue(Arrays.equals(enums, message.getExtension(PackedExtensions.packedEnum))); - - // Now set the packable extension values using PackedExtensions so they're serialized packed. - message.setExtension(PackedExtensions.packedInt32, int32s); - message.setExtension(PackedExtensions.packedUint32, uint32s); - message.setExtension(PackedExtensions.packedSint32, sint32s); - message.setExtension(PackedExtensions.packedInt64, int64s); - message.setExtension(PackedExtensions.packedUint64, uint64s); - message.setExtension(PackedExtensions.packedSint64, sint64s); - message.setExtension(PackedExtensions.packedFixed32, fixed32s); - message.setExtension(PackedExtensions.packedSfixed32, sfixed32s); - message.setExtension(PackedExtensions.packedFixed64, fixed64s); - message.setExtension(PackedExtensions.packedSfixed64, sfixed64s); - message.setExtension(PackedExtensions.packedBool, bools); - message.setExtension(PackedExtensions.packedFloat, floats); - message.setExtension(PackedExtensions.packedDouble, doubles); - message.setExtension(PackedExtensions.packedEnum, enums); - - // And read back using non-packed RepeatedExtensions. - byte[] data2 = MessageNano.toByteArray(message); - message = MessageNano.mergeFrom(new Extensions.ExtendableMessage(), data2); - assertTrue(Arrays.equals(int32s, message.getExtension(RepeatedExtensions.repeatedInt32))); - assertTrue(Arrays.equals(uint32s, message.getExtension(RepeatedExtensions.repeatedUint32))); - assertTrue(Arrays.equals(sint32s, message.getExtension(RepeatedExtensions.repeatedSint32))); - assertTrue(Arrays.equals(int64s, message.getExtension(RepeatedExtensions.repeatedInt64))); - assertTrue(Arrays.equals(uint64s, message.getExtension(RepeatedExtensions.repeatedUint64))); - assertTrue(Arrays.equals(sint64s, message.getExtension(RepeatedExtensions.repeatedSint64))); - assertTrue(Arrays.equals(fixed32s, message.getExtension(RepeatedExtensions.repeatedFixed32))); - assertTrue(Arrays.equals(sfixed32s, message.getExtension(RepeatedExtensions.repeatedSfixed32))); - assertTrue(Arrays.equals(fixed64s, message.getExtension(RepeatedExtensions.repeatedFixed64))); - assertTrue(Arrays.equals(sfixed64s, message.getExtension(RepeatedExtensions.repeatedSfixed64))); - assertTrue(Arrays.equals(bools, message.getExtension(RepeatedExtensions.repeatedBool))); - assertTrue(Arrays.equals(floats, message.getExtension(RepeatedExtensions.repeatedFloat))); - assertTrue(Arrays.equals(doubles, message.getExtension(RepeatedExtensions.repeatedDouble))); - assertTrue(Arrays.equals(enums, message.getExtension(RepeatedExtensions.repeatedEnum))); - - // Clone the message and ensure it's still equal. - Extensions.ExtendableMessage clone = message.clone(); - assertEquals(clone, message); - } - - public void testNullExtensions() throws Exception { - // Check that clearing the extension on an empty message is a no-op. - Extensions.ExtendableMessage message = new Extensions.ExtendableMessage(); - assertFalse(message.hasExtension(SingularExtensions.someMessage)); - message.setExtension(SingularExtensions.someMessage, null); - assertFalse(message.hasExtension(SingularExtensions.someMessage)); - assertEquals(0, MessageNano.toByteArray(message).length); - - // Check that the message is empty after setting and clearing an extension. - AnotherMessage another = new AnotherMessage(); - assertFalse(message.hasExtension(SingularExtensions.someMessage)); - message.setExtension(SingularExtensions.someMessage, another); - assertTrue(message.hasExtension(SingularExtensions.someMessage)); - assertTrue(MessageNano.toByteArray(message).length > 0); - message.setExtension(SingularExtensions.someMessage, null); - assertFalse(message.hasExtension(SingularExtensions.someMessage)); - assertEquals(0, MessageNano.toByteArray(message).length); - } - - public void testExtensionsMutation() { - Extensions.ExtendableMessage extendableMessage = new Extensions.ExtendableMessage(); - extendableMessage.setExtension(SingularExtensions.someMessage, - new Extensions.AnotherMessage()); - - extendableMessage.getExtension(SingularExtensions.someMessage).string = "not empty"; - - assertEquals("not empty", - extendableMessage.getExtension(SingularExtensions.someMessage).string); - } - - public void testExtensionsMutation_Equals() throws InvalidProtocolBufferNanoException { - Extensions.ExtendableMessage extendableMessage = new Extensions.ExtendableMessage(); - extendableMessage.field = 5; - int int32 = 42; - int[] uint32s = {3, 4}; - int[] sint32s = {-5, -6}; - long[] int64s = {7, 8}; - long[] uint64s = {9, 10}; - long[] sint64s = {-11, -12}; - int[] fixed32s = {13, 14}; - int[] sfixed32s = {-15, -16}; - long[] fixed64s = {17, 18}; - long[] sfixed64s = {-19, -20}; - boolean[] bools = {true, false}; - float[] floats = {2.1f, 2.2f}; - double[] doubles = {2.3, 2.4}; - int[] enums = {Extensions.SECOND_VALUE, Extensions.FIRST_VALUE}; - String[] strings = {"vijfentwintig", "twenty-six"}; - byte[][] bytess = {{2, 7}, {2, 8}}; - AnotherMessage another1 = new AnotherMessage(); - another1.string = "er shi jiu"; - another1.value = false; - AnotherMessage another2 = new AnotherMessage(); - another2.string = "trente"; - another2.value = true; - AnotherMessage[] messages = {another1, another2}; - RepeatedExtensions.RepeatedGroup group1 = new RepeatedExtensions.RepeatedGroup(); - group1.a = 31; - RepeatedExtensions.RepeatedGroup group2 = new RepeatedExtensions.RepeatedGroup(); - group2.a = 32; - RepeatedExtensions.RepeatedGroup[] groups = {group1, group2}; - extendableMessage.setExtension(SingularExtensions.someInt32, int32); - extendableMessage.setExtension(RepeatedExtensions.repeatedUint32, uint32s); - extendableMessage.setExtension(RepeatedExtensions.repeatedSint32, sint32s); - extendableMessage.setExtension(RepeatedExtensions.repeatedInt64, int64s); - extendableMessage.setExtension(RepeatedExtensions.repeatedUint64, uint64s); - extendableMessage.setExtension(RepeatedExtensions.repeatedSint64, sint64s); - extendableMessage.setExtension(RepeatedExtensions.repeatedFixed32, fixed32s); - extendableMessage.setExtension(RepeatedExtensions.repeatedSfixed32, sfixed32s); - extendableMessage.setExtension(RepeatedExtensions.repeatedFixed64, fixed64s); - extendableMessage.setExtension(RepeatedExtensions.repeatedSfixed64, sfixed64s); - extendableMessage.setExtension(RepeatedExtensions.repeatedBool, bools); - extendableMessage.setExtension(RepeatedExtensions.repeatedFloat, floats); - extendableMessage.setExtension(RepeatedExtensions.repeatedDouble, doubles); - extendableMessage.setExtension(RepeatedExtensions.repeatedEnum, enums); - extendableMessage.setExtension(RepeatedExtensions.repeatedString, strings); - extendableMessage.setExtension(RepeatedExtensions.repeatedBytes, bytess); - extendableMessage.setExtension(RepeatedExtensions.repeatedMessage, messages); - extendableMessage.setExtension(RepeatedExtensions.repeatedGroup, groups); - - byte[] data = MessageNano.toByteArray(extendableMessage); - - extendableMessage = Extensions.ExtendableMessage.parseFrom(data); - Extensions.ExtendableMessage messageCopy = Extensions.ExtendableMessage.parseFrom(data); - - // Without deserialising. - assertEquals(extendableMessage, messageCopy); - assertEquals(extendableMessage.hashCode(), messageCopy.hashCode()); - - // Only one deserialized. - extendableMessage.getExtension(SingularExtensions.someInt32); - extendableMessage.getExtension(RepeatedExtensions.repeatedUint32); - extendableMessage.getExtension(RepeatedExtensions.repeatedSint32); - extendableMessage.getExtension(RepeatedExtensions.repeatedInt64); - extendableMessage.getExtension(RepeatedExtensions.repeatedUint64); - extendableMessage.getExtension(RepeatedExtensions.repeatedSint64); - extendableMessage.getExtension(RepeatedExtensions.repeatedFixed32); - extendableMessage.getExtension(RepeatedExtensions.repeatedSfixed32); - extendableMessage.getExtension(RepeatedExtensions.repeatedFixed64); - extendableMessage.getExtension(RepeatedExtensions.repeatedSfixed64); - extendableMessage.getExtension(RepeatedExtensions.repeatedBool); - extendableMessage.getExtension(RepeatedExtensions.repeatedFloat); - extendableMessage.getExtension(RepeatedExtensions.repeatedDouble); - extendableMessage.getExtension(RepeatedExtensions.repeatedEnum); - extendableMessage.getExtension(RepeatedExtensions.repeatedString); - extendableMessage.getExtension(RepeatedExtensions.repeatedBytes); - extendableMessage.getExtension(RepeatedExtensions.repeatedMessage); - extendableMessage.getExtension(RepeatedExtensions.repeatedGroup); - assertEquals(extendableMessage, messageCopy); - assertEquals(extendableMessage.hashCode(), messageCopy.hashCode()); - - // Both deserialized. - messageCopy.getExtension(SingularExtensions.someInt32); - messageCopy.getExtension(RepeatedExtensions.repeatedUint32); - messageCopy.getExtension(RepeatedExtensions.repeatedSint32); - messageCopy.getExtension(RepeatedExtensions.repeatedInt64); - messageCopy.getExtension(RepeatedExtensions.repeatedUint64); - messageCopy.getExtension(RepeatedExtensions.repeatedSint64); - messageCopy.getExtension(RepeatedExtensions.repeatedFixed32); - messageCopy.getExtension(RepeatedExtensions.repeatedSfixed32); - messageCopy.getExtension(RepeatedExtensions.repeatedFixed64); - messageCopy.getExtension(RepeatedExtensions.repeatedSfixed64); - messageCopy.getExtension(RepeatedExtensions.repeatedBool); - messageCopy.getExtension(RepeatedExtensions.repeatedFloat); - messageCopy.getExtension(RepeatedExtensions.repeatedDouble); - messageCopy.getExtension(RepeatedExtensions.repeatedEnum); - messageCopy.getExtension(RepeatedExtensions.repeatedString); - messageCopy.getExtension(RepeatedExtensions.repeatedBytes); - messageCopy.getExtension(RepeatedExtensions.repeatedMessage); - messageCopy.getExtension(RepeatedExtensions.repeatedGroup); - assertEquals(extendableMessage, messageCopy); - assertEquals(extendableMessage.hashCode(), messageCopy.hashCode()); - - // Change one, make sure they are still different. - messageCopy.getExtension(RepeatedExtensions.repeatedMessage)[0].string = "not empty"; - assertFalse(extendableMessage.equals(messageCopy)); - - // Even if the extension hasn't been deserialized. - extendableMessage = Extensions.ExtendableMessage.parseFrom(data); - assertFalse(extendableMessage.equals(messageCopy)); - } - - public void testExtensionsCaching() { - Extensions.ExtendableMessage extendableMessage = new Extensions.ExtendableMessage(); - extendableMessage.setExtension(SingularExtensions.someMessage, - new Extensions.AnotherMessage()); - assertSame("Consecutive calls to getExtensions should return the same object", - extendableMessage.getExtension(SingularExtensions.someMessage), - extendableMessage.getExtension(SingularExtensions.someMessage)); - } - - public void testUnknownFields() throws Exception { - // Check that we roundtrip (serialize and deserialize) unrecognized fields. - AnotherMessage message = new AnotherMessage(); - message.string = "Hello World"; - message.value = false; - - byte[] bytes = MessageNano.toByteArray(message); - int extraFieldSize = CodedOutputByteBufferNano.computeStringSize( - 1001, "This is an unknown field"); - byte[] newBytes = new byte[bytes.length + extraFieldSize]; - System.arraycopy(bytes, 0, newBytes, 0, bytes.length); - CodedOutputByteBufferNano.newInstance(newBytes, bytes.length, extraFieldSize) - .writeString(1001, "This is an unknown field"); - - // Deserialize with an unknown field. - AnotherMessage deserialized = AnotherMessage.parseFrom(newBytes); - byte[] serialized = MessageNano.toByteArray(deserialized); - - assertEquals(newBytes.length, serialized.length); - - // Clear, and make sure it clears everything. - deserialized.clear(); - assertEquals(0, MessageNano.toByteArray(deserialized).length); - } - - public void testMergeFrom() throws Exception { - SimpleMessageNano message = new SimpleMessageNano(); - message.d = 123; - byte[] bytes = MessageNano.toByteArray(message); - - SimpleMessageNano newMessage = MessageNano.mergeFrom(new SimpleMessageNano(), bytes); - assertEquals(message.d, newMessage.d); - } - - public void testJavaKeyword() throws Exception { - TestAllTypesNano msg = new TestAllTypesNano(); - msg.synchronized_ = 123; - assertEquals(123, msg.synchronized_); - } - - public void testReferenceTypesForPrimitives() throws Exception { - NanoReferenceTypes.TestAllTypesNano message = new NanoReferenceTypes.TestAllTypesNano(); - - // Base check - when nothing is set, we serialize nothing. - assertHasWireData(message, false); - - message.defaultBool = true; - assertHasWireData(message, true); - - message.defaultBool = false; - assertHasWireData(message, true); - - message.defaultBool = null; - assertHasWireData(message, false); - - message.defaultInt32 = 5; - assertHasWireData(message, true); - - message.defaultInt32 = null; - assertHasWireData(message, false); - - message.defaultInt64 = 123456L; - assertHasWireData(message, true); - - message.defaultInt64 = null; - assertHasWireData(message, false); - - message.defaultFloat = 1f; - assertHasWireData(message, true); - - message.defaultFloat = null; - assertHasWireData(message, false); - - message.defaultDouble = 2.1; - assertHasWireData(message, true); - - message.defaultDouble = null; - assertHasWireData(message, false); - - message.defaultString = "hello"; - assertHasWireData(message, true); - - message.defaultString = null; - assertHasWireData(message, false); - - message.defaultBytes = new byte[] { 1, 2, 3 }; - assertHasWireData(message, true); - - message.defaultBytes = null; - assertHasWireData(message, false); - } - - public void testHashCodeEquals() throws Exception { - // Complete equality: - TestAllTypesNano a = createMessageForHashCodeEqualsTest(); - TestAllTypesNano aEquivalent = createMessageForHashCodeEqualsTest(); - - assertTrue(MessageNano.messageNanoEquals(a, aEquivalent)); - assertFalse(MessageNano.messageNanoEquals(a, new TestAllTypesNano())); - - // Null and empty array for repeated fields equality: - TestAllTypesNano b = createMessageForHashCodeEqualsTest(); - b.repeatedBool = null; - b.repeatedFloat = new float[0]; - TestAllTypesNano bEquivalent = createMessageForHashCodeEqualsTest(); - bEquivalent.repeatedBool = new boolean[0]; - bEquivalent.repeatedFloat = null; - - // Ref-element-type repeated fields use non-null subsequence equality: - TestAllTypesNano c = createMessageForHashCodeEqualsTest(); - c.repeatedString = null; - c.repeatedStringPiece = new String[] {null, "one", null, "two"}; - c.repeatedBytes = new byte[][] {{3, 4}, null}; - TestAllTypesNano cEquivalent = createMessageForHashCodeEqualsTest(); - cEquivalent.repeatedString = new String[3]; - cEquivalent.repeatedStringPiece = new String[] {"one", "two", null}; - cEquivalent.repeatedBytes = new byte[][] {{3, 4}}; - - // Complete equality for messages with has fields: - TestAllTypesNanoHas d = createMessageWithHasForHashCodeEqualsTest(); - TestAllTypesNanoHas dEquivalent = createMessageWithHasForHashCodeEqualsTest(); - - // If has-fields exist, fields with the same default values but - // different has-field values are different. - TestAllTypesNanoHas e = createMessageWithHasForHashCodeEqualsTest(); - e.optionalInt32++; // make different from d - e.hasDefaultString = false; - TestAllTypesNanoHas eDifferent = createMessageWithHasForHashCodeEqualsTest(); - eDifferent.optionalInt32 = e.optionalInt32; - eDifferent.hasDefaultString = true; - - // Complete equality for messages with accessors: - TestNanoAccessors f = createMessageWithAccessorsForHashCodeEqualsTest(); - TestNanoAccessors fEquivalent = createMessageWithAccessorsForHashCodeEqualsTest(); - - // If using accessors, explicitly setting a field to its default value - // should make the message different. - TestNanoAccessors g = createMessageWithAccessorsForHashCodeEqualsTest(); - g.setOptionalInt32(g.getOptionalInt32() + 1); // make different from f - g.clearDefaultString(); - TestNanoAccessors gDifferent = createMessageWithAccessorsForHashCodeEqualsTest(); - gDifferent.setOptionalInt32(g.getOptionalInt32()); - gDifferent.setDefaultString(g.getDefaultString()); - - // Complete equality for reference typed messages: - NanoReferenceTypes.TestAllTypesNano h = createRefTypedMessageForHashCodeEqualsTest(); - NanoReferenceTypes.TestAllTypesNano hEquivalent = createRefTypedMessageForHashCodeEqualsTest(); - - // Inequality of null and default value for reference typed messages: - NanoReferenceTypes.TestAllTypesNano i = createRefTypedMessageForHashCodeEqualsTest(); - i.optionalInt32 = 1; // make different from h - i.optionalFloat = null; - NanoReferenceTypes.TestAllTypesNano iDifferent = createRefTypedMessageForHashCodeEqualsTest(); - iDifferent.optionalInt32 = i.optionalInt32; - iDifferent.optionalFloat = 0.0f; - - HashMap<MessageNano, String> hashMap = new HashMap<MessageNano, String>(); - hashMap.put(a, "a"); - hashMap.put(b, "b"); - hashMap.put(c, "c"); - hashMap.put(d, "d"); - hashMap.put(e, "e"); - hashMap.put(f, "f"); - hashMap.put(g, "g"); - hashMap.put(h, "h"); - hashMap.put(i, "i"); - - assertEquals(9, hashMap.size()); // a-i should be different from each other. - - assertEquals("a", hashMap.get(a)); - assertEquals("a", hashMap.get(aEquivalent)); - - assertEquals("b", hashMap.get(b)); - assertEquals("b", hashMap.get(bEquivalent)); - - assertEquals("c", hashMap.get(c)); - assertEquals("c", hashMap.get(cEquivalent)); - - assertEquals("d", hashMap.get(d)); - assertEquals("d", hashMap.get(dEquivalent)); - - assertEquals("e", hashMap.get(e)); - assertNull(hashMap.get(eDifferent)); - - assertEquals("f", hashMap.get(f)); - assertEquals("f", hashMap.get(fEquivalent)); - - assertEquals("g", hashMap.get(g)); - assertNull(hashMap.get(gDifferent)); - - assertEquals("h", hashMap.get(h)); - assertEquals("h", hashMap.get(hEquivalent)); - - assertEquals("i", hashMap.get(i)); - assertNull(hashMap.get(iDifferent)); - } - - private TestAllTypesNano createMessageForHashCodeEqualsTest() { - TestAllTypesNano message = new TestAllTypesNano(); - message.optionalInt32 = 5; - message.optionalInt64 = 777; - message.optionalFloat = 1.0f; - message.optionalDouble = 2.0; - message.optionalBool = true; - message.optionalString = "Hello"; - message.optionalBytes = new byte[] { 1, 2, 3 }; - message.optionalNestedMessage = new TestAllTypesNano.NestedMessage(); - message.optionalNestedMessage.bb = 27; - message.optionalNestedEnum = TestAllTypesNano.BAR; - message.repeatedInt32 = new int[] { 5, 6, 7, 8 }; - message.repeatedInt64 = new long[] { 27L, 28L, 29L }; - message.repeatedFloat = new float[] { 5.0f, 6.0f }; - message.repeatedDouble = new double[] { 99.1, 22.5 }; - message.repeatedBool = new boolean[] { true, false, true }; - message.repeatedString = new String[] { "One", "Two" }; - message.repeatedBytes = new byte[][] { { 2, 7 }, { 2, 7 } }; - message.repeatedNestedMessage = new TestAllTypesNano.NestedMessage[] { - message.optionalNestedMessage, - message.optionalNestedMessage - }; - message.repeatedNestedEnum = new int[] { - TestAllTypesNano.BAR, - TestAllTypesNano.BAZ - }; - message.setOneofUint32(3); - return message; - } - - private TestAllTypesNanoHas createMessageWithHasForHashCodeEqualsTest() { - TestAllTypesNanoHas message = new TestAllTypesNanoHas(); - message.optionalInt32 = 5; - message.optionalString = "Hello"; - message.optionalBytes = new byte[] { 1, 2, 3 }; - message.optionalNestedMessage = new TestAllTypesNanoHas.NestedMessage(); - message.optionalNestedMessage.bb = 27; - message.optionalNestedEnum = TestAllTypesNano.BAR; - message.repeatedInt32 = new int[] { 5, 6, 7, 8 }; - message.repeatedString = new String[] { "One", "Two" }; - message.repeatedBytes = new byte[][] { { 2, 7 }, { 2, 7 } }; - message.repeatedNestedMessage = new TestAllTypesNanoHas.NestedMessage[] { - message.optionalNestedMessage, - message.optionalNestedMessage - }; - message.repeatedNestedEnum = new int[] { - TestAllTypesNano.BAR, - TestAllTypesNano.BAZ - }; - return message; - } - - private TestNanoAccessors createMessageWithAccessorsForHashCodeEqualsTest() { - TestNanoAccessors message = new TestNanoAccessors() - .setOptionalInt32(5) - .setOptionalString("Hello") - .setOptionalBytes(new byte[] {1, 2, 3}) - .setOptionalNestedEnum(TestNanoAccessors.BAR); - message.optionalNestedMessage = new TestNanoAccessors.NestedMessage().setBb(27); - message.repeatedInt32 = new int[] { 5, 6, 7, 8 }; - message.repeatedString = new String[] { "One", "Two" }; - message.repeatedBytes = new byte[][] { { 2, 7 }, { 2, 7 } }; - message.repeatedNestedMessage = new TestNanoAccessors.NestedMessage[] { - message.optionalNestedMessage, - message.optionalNestedMessage - }; - message.repeatedNestedEnum = new int[] { - TestAllTypesNano.BAR, - TestAllTypesNano.BAZ - }; - return message; - } - - private NanoReferenceTypes.TestAllTypesNano createRefTypedMessageForHashCodeEqualsTest() { - NanoReferenceTypes.TestAllTypesNano message = new NanoReferenceTypes.TestAllTypesNano(); - message.optionalInt32 = 5; - message.optionalInt64 = 777L; - message.optionalFloat = 1.0f; - message.optionalDouble = 2.0; - message.optionalBool = true; - message.optionalString = "Hello"; - message.optionalBytes = new byte[] { 1, 2, 3 }; - message.optionalNestedMessage = - new NanoReferenceTypes.TestAllTypesNano.NestedMessage(); - message.optionalNestedMessage.foo = 27; - message.optionalNestedEnum = NanoReferenceTypes.TestAllTypesNano.BAR; - message.repeatedInt32 = new int[] { 5, 6, 7, 8 }; - message.repeatedInt64 = new long[] { 27L, 28L, 29L }; - message.repeatedFloat = new float[] { 5.0f, 6.0f }; - message.repeatedDouble = new double[] { 99.1, 22.5 }; - message.repeatedBool = new boolean[] { true, false, true }; - message.repeatedString = new String[] { "One", "Two" }; - message.repeatedBytes = new byte[][] { { 2, 7 }, { 2, 7 } }; - message.repeatedNestedMessage = - new NanoReferenceTypes.TestAllTypesNano.NestedMessage[] { - message.optionalNestedMessage, - message.optionalNestedMessage - }; - message.repeatedNestedEnum = new int[] { - NanoReferenceTypes.TestAllTypesNano.BAR, - NanoReferenceTypes.TestAllTypesNano.BAZ - }; - return message; - } - - public void testEqualsWithSpecialFloatingPointValues() throws Exception { - // Checks that the nano implementation complies with Object.equals() when treating - // floating point numbers, i.e. NaN == NaN and +0.0 != -0.0. - // This test assumes that the generated equals() implementations are symmetric, so - // there will only be one direction for each equality check. - - TestAllTypesNano m1 = new TestAllTypesNano(); - m1.optionalFloat = Float.NaN; - m1.optionalDouble = Double.NaN; - TestAllTypesNano m2 = new TestAllTypesNano(); - m2.optionalFloat = Float.NaN; - m2.optionalDouble = Double.NaN; - assertTrue(m1.equals(m2)); - assertTrue(m1.equals( - MessageNano.mergeFrom(new TestAllTypesNano(), MessageNano.toByteArray(m1)))); - - m1.optionalFloat = +0f; - m2.optionalFloat = -0f; - assertFalse(m1.equals(m2)); - - m1.optionalFloat = -0f; - m1.optionalDouble = +0d; - m2.optionalDouble = -0d; - assertFalse(m1.equals(m2)); - - m1.optionalDouble = -0d; - assertTrue(m1.equals(m2)); - assertFalse(m1.equals(new TestAllTypesNano())); // -0 does not equals() the default +0 - assertTrue(m1.equals( - MessageNano.mergeFrom(new TestAllTypesNano(), MessageNano.toByteArray(m1)))); - - // ------- - - TestAllTypesNanoHas m3 = new TestAllTypesNanoHas(); - m3.optionalFloat = Float.NaN; - m3.hasOptionalFloat = true; - m3.optionalDouble = Double.NaN; - m3.hasOptionalDouble = true; - TestAllTypesNanoHas m4 = new TestAllTypesNanoHas(); - m4.optionalFloat = Float.NaN; - m4.hasOptionalFloat = true; - m4.optionalDouble = Double.NaN; - m4.hasOptionalDouble = true; - assertTrue(m3.equals(m4)); - assertTrue(m3.equals( - MessageNano.mergeFrom(new TestAllTypesNanoHas(), MessageNano.toByteArray(m3)))); - - m3.optionalFloat = +0f; - m4.optionalFloat = -0f; - assertFalse(m3.equals(m4)); - - m3.optionalFloat = -0f; - m3.optionalDouble = +0d; - m4.optionalDouble = -0d; - assertFalse(m3.equals(m4)); - - m3.optionalDouble = -0d; - m3.hasOptionalFloat = false; // -0 does not equals() the default +0, - m3.hasOptionalDouble = false; // so these incorrect 'has' flags should be disregarded. - assertTrue(m3.equals(m4)); // note: m4 has the 'has' flags set. - assertFalse(m3.equals(new TestAllTypesNanoHas())); // note: the new message has +0 defaults - assertTrue(m3.equals( - MessageNano.mergeFrom(new TestAllTypesNanoHas(), MessageNano.toByteArray(m3)))); - // note: the deserialized message has the 'has' flags set. - - // ------- - - TestNanoAccessors m5 = new TestNanoAccessors(); - m5.setOptionalFloat(Float.NaN); - m5.setOptionalDouble(Double.NaN); - TestNanoAccessors m6 = new TestNanoAccessors(); - m6.setOptionalFloat(Float.NaN); - m6.setOptionalDouble(Double.NaN); - assertTrue(m5.equals(m6)); - assertTrue(m5.equals( - MessageNano.mergeFrom(new TestNanoAccessors(), MessageNano.toByteArray(m6)))); - - m5.setOptionalFloat(+0f); - m6.setOptionalFloat(-0f); - assertFalse(m5.equals(m6)); - - m5.setOptionalFloat(-0f); - m5.setOptionalDouble(+0d); - m6.setOptionalDouble(-0d); - assertFalse(m5.equals(m6)); - - m5.setOptionalDouble(-0d); - assertTrue(m5.equals(m6)); - assertFalse(m5.equals(new TestNanoAccessors())); - assertTrue(m5.equals( - MessageNano.mergeFrom(new TestNanoAccessors(), MessageNano.toByteArray(m6)))); - - // ------- - - NanoReferenceTypes.TestAllTypesNano m7 = new NanoReferenceTypes.TestAllTypesNano(); - m7.optionalFloat = Float.NaN; - m7.optionalDouble = Double.NaN; - NanoReferenceTypes.TestAllTypesNano m8 = new NanoReferenceTypes.TestAllTypesNano(); - m8.optionalFloat = Float.NaN; - m8.optionalDouble = Double.NaN; - assertTrue(m7.equals(m8)); - assertTrue(m7.equals(MessageNano.mergeFrom( - new NanoReferenceTypes.TestAllTypesNano(), MessageNano.toByteArray(m7)))); - - m7.optionalFloat = +0f; - m8.optionalFloat = -0f; - assertFalse(m7.equals(m8)); - - m7.optionalFloat = -0f; - m7.optionalDouble = +0d; - m8.optionalDouble = -0d; - assertFalse(m7.equals(m8)); - - m7.optionalDouble = -0d; - assertTrue(m7.equals(m8)); - assertFalse(m7.equals(new NanoReferenceTypes.TestAllTypesNano())); - assertTrue(m7.equals(MessageNano.mergeFrom( - new NanoReferenceTypes.TestAllTypesNano(), MessageNano.toByteArray(m7)))); - } - - private static TestAllTypesNano generateMessageForOneof(int caseNumber) { - TestAllTypesNano result = new TestAllTypesNano(); - TestAllTypesNano.NestedMessage nested = - new TestAllTypesNano.NestedMessage(); - nested.bb = 2; - switch (caseNumber) { - case TestAllTypesNano.ONEOF_UINT32_FIELD_NUMBER: - result.setOneofUint32(1); - break; - case TestAllTypesNano.ONEOF_ENUM_FIELD_NUMBER: - result.setOneofEnum(TestAllTypesNano.BAR); - break; - case TestAllTypesNano.ONEOF_NESTED_MESSAGE_FIELD_NUMBER: - result.setOneofNestedMessage(nested); - break; - case TestAllTypesNano.ONEOF_BYTES_FIELD_NUMBER: - result.setOneofBytes(new byte[] {1, 2}); - break; - case TestAllTypesNano.ONEOF_STRING_FIELD_NUMBER: - result.setOneofString("hello"); - break; - case TestAllTypesNano.ONEOF_FIXED64_FIELD_NUMBER: - result.setOneofFixed64(-1L); - break; - default: - throw new RuntimeException("unexpected case number: " + caseNumber); - } - return result; - } - - public void testOneofHashCodeEquals() throws Exception { - TestAllTypesNano m1 = generateMessageForOneof( - TestAllTypesNano.ONEOF_UINT32_FIELD_NUMBER); - assertEquals(m1, generateMessageForOneof( - TestAllTypesNano.ONEOF_UINT32_FIELD_NUMBER)); - assertFalse(m1.equals(new TestAllTypesNano())); - - TestAllTypesNano m2 = generateMessageForOneof( - TestAllTypesNano.ONEOF_ENUM_FIELD_NUMBER); - assertEquals(m2, generateMessageForOneof( - TestAllTypesNano.ONEOF_ENUM_FIELD_NUMBER)); - assertFalse(m2.equals(new TestAllTypesNano())); - - TestAllTypesNano m3 = generateMessageForOneof( - TestAllTypesNano.ONEOF_NESTED_MESSAGE_FIELD_NUMBER); - assertEquals(m3, generateMessageForOneof( - TestAllTypesNano.ONEOF_NESTED_MESSAGE_FIELD_NUMBER)); - assertFalse(m3.equals(new TestAllTypesNano())); - - TestAllTypesNano m4 = generateMessageForOneof( - TestAllTypesNano.ONEOF_BYTES_FIELD_NUMBER); - assertEquals(m4, generateMessageForOneof( - TestAllTypesNano.ONEOF_BYTES_FIELD_NUMBER)); - assertFalse(m4.equals(new TestAllTypesNano())); - - TestAllTypesNano m5 = generateMessageForOneof( - TestAllTypesNano.ONEOF_STRING_FIELD_NUMBER); - assertEquals(m5, generateMessageForOneof( - TestAllTypesNano.ONEOF_STRING_FIELD_NUMBER)); - assertFalse(m5.equals(new TestAllTypesNano())); - - TestAllTypesNano m6 = generateMessageForOneof( - TestAllTypesNano.ONEOF_FIXED64_FIELD_NUMBER); - assertEquals(m6, generateMessageForOneof( - TestAllTypesNano.ONEOF_FIXED64_FIELD_NUMBER)); - assertFalse(m6.equals(new TestAllTypesNano())); - - Map<TestAllTypesNano, Integer> map = - new HashMap<TestAllTypesNano, Integer>(); - map.put(m1, 1); - map.put(m2, 2); - map.put(m3, 3); - map.put(m4, 4); - map.put(m5, 5); - map.put(m6, 6); - - assertEquals(6, map.size()); - } - - private void checkOneofCase(TestAllTypesNano nano, int field) - throws Exception { - assertEquals(field, nano.getOneofFieldCase()); - assertEquals( - field == TestAllTypesNano.ONEOF_BYTES_FIELD_NUMBER, - nano.hasOneofBytes()); - assertEquals( - field == TestAllTypesNano.ONEOF_ENUM_FIELD_NUMBER, - nano.hasOneofEnum()); - assertEquals( - field == TestAllTypesNano.ONEOF_FIXED64_FIELD_NUMBER, - nano.hasOneofFixed64()); - assertEquals( - field == TestAllTypesNano.ONEOF_NESTED_MESSAGE_FIELD_NUMBER, - nano.hasOneofNestedMessage()); - assertEquals( - field == TestAllTypesNano.ONEOF_STRING_FIELD_NUMBER, - nano.hasOneofString()); - assertEquals( - field == TestAllTypesNano.ONEOF_UINT32_FIELD_NUMBER, - nano.hasOneofUint32()); - - } - - public void testOneofDefault() throws Exception { - TestAllTypesNano m1 = new TestAllTypesNano(); - checkOneofCase(m1, 0); - assertEquals(WireFormatNano.EMPTY_BYTES, m1.getOneofBytes()); - assertEquals(TestAllTypesNano.FOO, m1.getOneofEnum()); - assertEquals(0L, m1.getOneofFixed64()); - assertEquals(null, m1.getOneofNestedMessage()); - assertEquals("", m1.getOneofString()); - assertEquals(0, m1.getOneofUint32()); - } - - public void testOneofExclusiveness() throws Exception { - TestAllTypesNano m = new TestAllTypesNano(); - checkOneofCase(m, 0); - - m.setOneofBytes(new byte[]{0, 1}); - checkOneofCase(m, TestAllTypesNano.ONEOF_BYTES_FIELD_NUMBER); - assertTrue(Arrays.equals(new byte[]{0, 1}, m.getOneofBytes())); - - m.setOneofEnum(TestAllTypesNano.BAZ); - checkOneofCase(m, TestAllTypesNano.ONEOF_ENUM_FIELD_NUMBER); - assertEquals(TestAllTypesNano.BAZ, m.getOneofEnum()); - assertEquals(WireFormatNano.EMPTY_BYTES, m.getOneofBytes()); - - m.setOneofFixed64(-1L); - checkOneofCase(m, TestAllTypesNano.ONEOF_FIXED64_FIELD_NUMBER); - assertEquals(-1L, m.getOneofFixed64()); - assertEquals(TestAllTypesNano.FOO, m.getOneofEnum()); - - m.setOneofNestedMessage(new TestAllTypesNano.NestedMessage()); - checkOneofCase(m, TestAllTypesNano.ONEOF_NESTED_MESSAGE_FIELD_NUMBER); - assertEquals( - new TestAllTypesNano.NestedMessage(), m.getOneofNestedMessage()); - assertEquals(0L, m.getOneofFixed64()); - - m.setOneofString("hello"); - checkOneofCase(m, TestAllTypesNano.ONEOF_STRING_FIELD_NUMBER); - assertEquals("hello", m.getOneofString()); - assertNull(m.getOneofNestedMessage()); - - m.setOneofUint32(10); - checkOneofCase(m, TestAllTypesNano.ONEOF_UINT32_FIELD_NUMBER); - assertEquals(10, m.getOneofUint32()); - assertEquals("", m.getOneofString()); - - m.setOneofBytes(new byte[]{0, 1}); - checkOneofCase(m, TestAllTypesNano.ONEOF_BYTES_FIELD_NUMBER); - assertTrue(Arrays.equals(new byte[]{0, 1}, m.getOneofBytes())); - assertEquals(0, m.getOneofUint32()); - } - - public void testOneofClear() throws Exception { - TestAllTypesNano m = new TestAllTypesNano(); - m.setOneofBytes(new byte[]{0, 1}); - m.clearOneofField(); - checkOneofCase(m, 0); - - m.setOneofEnum(TestAllTypesNano.BAZ); - m.clearOneofField(); - checkOneofCase(m, 0); - - m.setOneofFixed64(-1L); - m.clearOneofField(); - checkOneofCase(m, 0); - - m.setOneofNestedMessage(new TestAllTypesNano.NestedMessage()); - m.clearOneofField(); - checkOneofCase(m, 0); - - m.setOneofString("hello"); - m.clearOneofField(); - checkOneofCase(m, 0); - - m.setOneofUint32(10); - m.clearOneofField(); - checkOneofCase(m, 0); - } - - public void testOneofMarshaling() throws Exception { - TestAllTypesNano m = new TestAllTypesNano(); - TestAllTypesNano parsed = new TestAllTypesNano(); - { - m.setOneofBytes(new byte[]{0, 1}); - byte[] serialized = MessageNano.toByteArray(m); - MessageNano.mergeFrom(parsed, serialized); - checkOneofCase(parsed, TestAllTypesNano.ONEOF_BYTES_FIELD_NUMBER); - assertTrue(Arrays.equals(new byte[]{0, 1}, parsed.getOneofBytes())); - } - { - m.setOneofEnum(TestAllTypesNano.BAZ); - byte[] serialized = MessageNano.toByteArray(m); - MessageNano.mergeFrom(parsed, serialized); - checkOneofCase(m, TestAllTypesNano.ONEOF_ENUM_FIELD_NUMBER); - assertEquals(TestAllTypesNano.BAZ, m.getOneofEnum()); - } - { - m.setOneofEnum(TestAllTypesNano.BAZ); - byte[] serialized = MessageNano.toByteArray(m); - MessageNano.mergeFrom(parsed, serialized); - checkOneofCase(m, TestAllTypesNano.ONEOF_ENUM_FIELD_NUMBER); - assertEquals(TestAllTypesNano.BAZ, m.getOneofEnum()); - } - { - m.setOneofFixed64(-1L); - byte[] serialized = MessageNano.toByteArray(m); - MessageNano.mergeFrom(parsed, serialized); - checkOneofCase(m, TestAllTypesNano.ONEOF_FIXED64_FIELD_NUMBER); - assertEquals(-1L, m.getOneofFixed64()); - } - { - m.setOneofNestedMessage(new TestAllTypesNano.NestedMessage()); - byte[] serialized = MessageNano.toByteArray(m); - MessageNano.mergeFrom(parsed, serialized); - checkOneofCase(m, TestAllTypesNano.ONEOF_NESTED_MESSAGE_FIELD_NUMBER); - assertEquals( - new TestAllTypesNano.NestedMessage(), m.getOneofNestedMessage()); - } - { - m.setOneofString("hello"); - byte[] serialized = MessageNano.toByteArray(m); - MessageNano.mergeFrom(parsed, serialized); - assertEquals("hello", m.getOneofString()); - assertNull(m.getOneofNestedMessage()); - } - { - m.setOneofUint32(10); - byte[] serialized = MessageNano.toByteArray(m); - MessageNano.mergeFrom(parsed, serialized); - checkOneofCase(m, TestAllTypesNano.ONEOF_UINT32_FIELD_NUMBER); - assertEquals(10, m.getOneofUint32()); - } - } - - public void testOneofSerializedConcat() throws Exception { - TestAllTypesNano m1 = new TestAllTypesNano(); - m1.setOneofBytes(new byte[] {0, 1}); - byte[] b1 = MessageNano.toByteArray(m1); - TestAllTypesNano m2 = new TestAllTypesNano(); - m2.setOneofEnum(TestAllTypesNano.BAZ); - byte[] b2 = MessageNano.toByteArray(m2); - byte[] b3 = new byte[b1.length + b2.length]; - System.arraycopy(b1, 0, b3, 0, b1.length); - System.arraycopy(b2, 0, b3, b1.length, b2.length); - TestAllTypesNano parsed = new TestAllTypesNano(); - MessageNano.mergeFrom(parsed, b3); - // the last on the wire wins. - checkOneofCase(parsed, TestAllTypesNano.ONEOF_ENUM_FIELD_NUMBER); - assertEquals(TestAllTypesNano.BAZ, parsed.getOneofEnum()); - } - - public void testNullRepeatedFields() throws Exception { - // Check that serialization after explicitly setting a repeated field - // to null doesn't NPE. - TestAllTypesNano message = new TestAllTypesNano(); - message.repeatedInt32 = null; - MessageNano.toByteArray(message); // should not NPE - message.toString(); // should not NPE - - message.repeatedNestedEnum = null; - MessageNano.toByteArray(message); // should not NPE - message.toString(); // should not NPE - - message.repeatedBytes = null; - MessageNano.toByteArray(message); // should not NPE - message.toString(); // should not NPE - - message.repeatedNestedMessage = null; - MessageNano.toByteArray(message); // should not NPE - message.toString(); // should not NPE - - message.repeatedPackedInt32 = null; - MessageNano.toByteArray(message); // should not NPE - message.toString(); // should not NPE - - message.repeatedPackedNestedEnum = null; - MessageNano.toByteArray(message); // should not NPE - message.toString(); // should not NPE - - // Create a second message to merge into message. - TestAllTypesNano secondMessage = new TestAllTypesNano(); - secondMessage.repeatedInt32 = new int[] {1, 2, 3}; - secondMessage.repeatedNestedEnum = new int[] { - TestAllTypesNano.FOO, TestAllTypesNano.BAR - }; - secondMessage.repeatedBytes = new byte[][] {{1, 2}, {3, 4}}; - TestAllTypesNano.NestedMessage nested = - new TestAllTypesNano.NestedMessage(); - nested.bb = 55; - secondMessage.repeatedNestedMessage = - new TestAllTypesNano.NestedMessage[] {nested}; - secondMessage.repeatedPackedInt32 = new int[] {1, 2, 3}; - secondMessage.repeatedPackedNestedEnum = new int[] { - TestAllTypesNano.FOO, TestAllTypesNano.BAR - }; - - // Should not NPE - message.mergeFrom(CodedInputByteBufferNano.newInstance( - MessageNano.toByteArray(secondMessage))); - assertEquals(3, message.repeatedInt32.length); - assertEquals(3, message.repeatedInt32[2]); - assertEquals(2, message.repeatedNestedEnum.length); - assertEquals(TestAllTypesNano.FOO, message.repeatedNestedEnum[0]); - assertEquals(2, message.repeatedBytes.length); - assertEquals(4, message.repeatedBytes[1][1]); - assertEquals(1, message.repeatedNestedMessage.length); - assertEquals(55, message.repeatedNestedMessage[0].bb); - assertEquals(3, message.repeatedPackedInt32.length); - assertEquals(2, message.repeatedPackedInt32[1]); - assertEquals(2, message.repeatedPackedNestedEnum.length); - assertEquals(TestAllTypesNano.BAR, message.repeatedPackedNestedEnum[1]); - } - - public void testNullRepeatedFieldElements() throws Exception { - // Check that serialization with null array elements doesn't NPE. - String string1 = "1"; - String string2 = "2"; - byte[] bytes1 = {3, 4}; - byte[] bytes2 = {5, 6}; - TestAllTypesNano.NestedMessage msg1 = new TestAllTypesNano.NestedMessage(); - msg1.bb = 7; - TestAllTypesNano.NestedMessage msg2 = new TestAllTypesNano.NestedMessage(); - msg2.bb = 8; - - TestAllTypesNano message = new TestAllTypesNano(); - message.repeatedString = new String[] {null, string1, string2}; - message.repeatedBytes = new byte[][] {bytes1, null, bytes2}; - message.repeatedNestedMessage = new TestAllTypesNano.NestedMessage[] {msg1, msg2, null}; - message.repeatedGroup = new TestAllTypesNano.RepeatedGroup[] {null, null, null}; - - byte[] serialized = MessageNano.toByteArray(message); // should not NPE - TestAllTypesNano deserialized = MessageNano.mergeFrom(new TestAllTypesNano(), serialized); - assertEquals(2, deserialized.repeatedString.length); - assertEquals(string1, deserialized.repeatedString[0]); - assertEquals(string2, deserialized.repeatedString[1]); - assertEquals(2, deserialized.repeatedBytes.length); - assertTrue(Arrays.equals(bytes1, deserialized.repeatedBytes[0])); - assertTrue(Arrays.equals(bytes2, deserialized.repeatedBytes[1])); - assertEquals(2, deserialized.repeatedNestedMessage.length); - assertEquals(msg1.bb, deserialized.repeatedNestedMessage[0].bb); - assertEquals(msg2.bb, deserialized.repeatedNestedMessage[1].bb); - assertEquals(0, deserialized.repeatedGroup.length); - } - - public void testRepeatedMerge() throws Exception { - // Check that merging repeated fields cause the arrays to expand with - // new data. - TestAllTypesNano first = new TestAllTypesNano(); - first.repeatedInt32 = new int[] {1, 2, 3}; - TestAllTypesNano second = new TestAllTypesNano(); - second.repeatedInt32 = new int[] {4, 5}; - MessageNano.mergeFrom(first, MessageNano.toByteArray(second)); - assertEquals(5, first.repeatedInt32.length); - assertEquals(1, first.repeatedInt32[0]); - assertEquals(4, first.repeatedInt32[3]); - - first = new TestAllTypesNano(); - first.repeatedNestedEnum = new int[] {TestAllTypesNano.BAR}; - second = new TestAllTypesNano(); - second.repeatedNestedEnum = new int[] {TestAllTypesNano.FOO}; - MessageNano.mergeFrom(first, MessageNano.toByteArray(second)); - assertEquals(2, first.repeatedNestedEnum.length); - assertEquals(TestAllTypesNano.BAR, first.repeatedNestedEnum[0]); - assertEquals(TestAllTypesNano.FOO, first.repeatedNestedEnum[1]); - - first = new TestAllTypesNano(); - first.repeatedNestedMessage = new TestAllTypesNano.NestedMessage[] { - new TestAllTypesNano.NestedMessage() - }; - first.repeatedNestedMessage[0].bb = 3; - second = new TestAllTypesNano(); - second.repeatedNestedMessage = new TestAllTypesNano.NestedMessage[] { - new TestAllTypesNano.NestedMessage() - }; - second.repeatedNestedMessage[0].bb = 5; - MessageNano.mergeFrom(first, MessageNano.toByteArray(second)); - assertEquals(2, first.repeatedNestedMessage.length); - assertEquals(3, first.repeatedNestedMessage[0].bb); - assertEquals(5, first.repeatedNestedMessage[1].bb); - - first = new TestAllTypesNano(); - first.repeatedPackedSfixed64 = new long[] {-1, -2, -3}; - second = new TestAllTypesNano(); - second.repeatedPackedSfixed64 = new long[] {-4, -5}; - MessageNano.mergeFrom(first, MessageNano.toByteArray(second)); - assertEquals(5, first.repeatedPackedSfixed64.length); - assertEquals(-1, first.repeatedPackedSfixed64[0]); - assertEquals(-4, first.repeatedPackedSfixed64[3]); - - first = new TestAllTypesNano(); - first.repeatedPackedNestedEnum = new int[] {TestAllTypesNano.BAR}; - second = new TestAllTypesNano(); - second.repeatedPackedNestedEnum = new int[] {TestAllTypesNano.FOO}; - MessageNano.mergeFrom(first, MessageNano.toByteArray(second)); - assertEquals(2, first.repeatedPackedNestedEnum.length); - assertEquals(TestAllTypesNano.BAR, first.repeatedPackedNestedEnum[0]); - assertEquals(TestAllTypesNano.FOO, first.repeatedPackedNestedEnum[1]); - - // Now test repeated merging in a nested scope - TestRepeatedMergeNano firstContainer = new TestRepeatedMergeNano(); - firstContainer.contained = new TestAllTypesNano(); - firstContainer.contained.repeatedInt32 = new int[] {10, 20}; - TestRepeatedMergeNano secondContainer = new TestRepeatedMergeNano(); - secondContainer.contained = new TestAllTypesNano(); - secondContainer.contained.repeatedInt32 = new int[] {30}; - MessageNano.mergeFrom(firstContainer, MessageNano.toByteArray(secondContainer)); - assertEquals(3, firstContainer.contained.repeatedInt32.length); - assertEquals(20, firstContainer.contained.repeatedInt32[1]); - assertEquals(30, firstContainer.contained.repeatedInt32[2]); - } - - public void testRepeatedPackables() throws Exception { - // Check that repeated fields with packable types can accept both packed and unpacked - // serialized forms. - NanoRepeatedPackables.NonPacked nonPacked = new NanoRepeatedPackables.NonPacked(); - // Exaggerates the first values of varint-typed arrays. This is to test that the parsing code - // of packed fields handles non-packed data correctly. If the code incorrectly thinks it is - // reading from a packed tag, it will read the first value as the byte length of the field, - // and the large number will cause the input to go out of bounds, thus capturing the error. - nonPacked.int32S = new int[] {1000, 2, 3}; - nonPacked.int64S = new long[] {4000, 5, 6}; - nonPacked.uint32S = new int[] {7000, 8, 9}; - nonPacked.uint64S = new long[] {10000, 11, 12}; - nonPacked.sint32S = new int[] {13000, 14, 15}; - nonPacked.sint64S = new long[] {16000, 17, 18}; - nonPacked.fixed32S = new int[] {19, 20, 21}; - nonPacked.fixed64S = new long[] {22, 23, 24}; - nonPacked.sfixed32S = new int[] {25, 26, 27}; - nonPacked.sfixed64S = new long[] {28, 29, 30}; - nonPacked.floats = new float[] {31, 32, 33}; - nonPacked.doubles = new double[] {34, 35, 36}; - nonPacked.bools = new boolean[] {false, true}; - nonPacked.enums = new int[] { - NanoRepeatedPackables.Enum.OPTION_ONE, - NanoRepeatedPackables.Enum.OPTION_TWO, - }; - nonPacked.noise = 13579; - - byte[] nonPackedSerialized = MessageNano.toByteArray(nonPacked); - - NanoRepeatedPackables.Packed packed = - MessageNano.mergeFrom(new NanoRepeatedPackables.Packed(), nonPackedSerialized); - assertRepeatedPackablesEqual(nonPacked, packed); - - byte[] packedSerialized = MessageNano.toByteArray(packed); - // Just a cautious check that the two serialized forms are different, - // to make sure the remaining of this test is useful: - assertFalse(Arrays.equals(nonPackedSerialized, packedSerialized)); - - nonPacked = MessageNano.mergeFrom(new NanoRepeatedPackables.NonPacked(), packedSerialized); - assertRepeatedPackablesEqual(nonPacked, packed); - - // Test mixed serialized form. - byte[] mixedSerialized = new byte[nonPackedSerialized.length + packedSerialized.length]; - System.arraycopy(nonPackedSerialized, 0, mixedSerialized, 0, nonPackedSerialized.length); - System.arraycopy(packedSerialized, 0, - mixedSerialized, nonPackedSerialized.length, packedSerialized.length); - - nonPacked = MessageNano.mergeFrom(new NanoRepeatedPackables.NonPacked(), mixedSerialized); - packed = MessageNano.mergeFrom(new NanoRepeatedPackables.Packed(), mixedSerialized); - assertRepeatedPackablesEqual(nonPacked, packed); - assertTrue(Arrays.equals(new int[] {1000, 2, 3, 1000, 2, 3}, nonPacked.int32S)); - assertTrue(Arrays.equals(new int[] {13000, 14, 15, 13000, 14, 15}, nonPacked.sint32S)); - assertTrue(Arrays.equals(new int[] {25, 26, 27, 25, 26, 27}, nonPacked.sfixed32S)); - assertTrue(Arrays.equals(new boolean[] {false, true, false, true}, nonPacked.bools)); - } - - public void testMapsSerializeAndParse() throws Exception { - TestMap origin = new TestMap(); - setMapMessage(origin); - assertMapMessageSet(origin); - - byte[] output = MessageNano.toByteArray(origin); - TestMap parsed = new TestMap(); - MessageNano.mergeFrom(parsed, output); - } - - public void testMapSerializeRejectNull() throws Exception { - TestMap primitiveMap = new TestMap(); - primitiveMap.int32ToInt32Field = new HashMap<Integer, Integer>(); - primitiveMap.int32ToInt32Field.put(null, 1); - try { - MessageNano.toByteArray(primitiveMap); - fail("should reject null keys"); - } catch (IllegalStateException e) { - // pass. - } - - TestMap messageMap = new TestMap(); - messageMap.int32ToMessageField = - new HashMap<Integer, MapTestProto.TestMap.MessageValue>(); - messageMap.int32ToMessageField.put(0, null); - try { - MessageNano.toByteArray(messageMap); - fail("should reject null values"); - } catch (IllegalStateException e) { - // pass. - } - } - - /** - * Tests that merging bytes containing conflicting keys with override the - * message value instead of merging the message value into the existing entry. - */ - public void testMapMergeOverrideMessageValues() throws Exception { - TestMap.MessageValue origValue = new TestMap.MessageValue(); - origValue.value = 1; - origValue.value2 = 2; - TestMap.MessageValue newValue = new TestMap.MessageValue(); - newValue.value = 3; - - TestMap origMessage = new TestMap(); - origMessage.int32ToMessageField = - new HashMap<Integer, MapTestProto.TestMap.MessageValue>(); - origMessage.int32ToMessageField.put(1, origValue); - - TestMap newMessage = new TestMap(); - newMessage.int32ToMessageField = - new HashMap<Integer, MapTestProto.TestMap.MessageValue>(); - newMessage.int32ToMessageField.put(1, newValue); - MessageNano.mergeFrom(origMessage, - MessageNano.toByteArray(newMessage)); - TestMap.MessageValue mergedValue = origMessage.int32ToMessageField.get(1); - assertEquals(3, mergedValue.value); - assertEquals(0, mergedValue.value2); - } - - /** - * Tests that when merging with empty entries, - * we will use default for the key and value, instead of null. - */ - public void testMapMergeEmptyEntry() throws Exception { - TestMap testMap = new TestMap(); - byte[] buffer = new byte[1024]; - CodedOutputByteBufferNano output = - CodedOutputByteBufferNano.newInstance(buffer); - // An empty entry for int32_to_int32 map. - output.writeTag(1, WireFormatNano.WIRETYPE_LENGTH_DELIMITED); - output.writeRawVarint32(0); - // An empty entry for int32_to_message map. - output.writeTag(5, WireFormatNano.WIRETYPE_LENGTH_DELIMITED); - output.writeRawVarint32(0); - - CodedInputByteBufferNano input = CodedInputByteBufferNano.newInstance( - buffer, 0, buffer.length - output.spaceLeft()); - testMap.mergeFrom(input); - assertNotNull(testMap.int32ToInt32Field);; - assertEquals(1, testMap.int32ToInt32Field.size()); - assertEquals(Integer.valueOf(0), testMap.int32ToInt32Field.get(0)); - assertNotNull(testMap.int32ToMessageField); - assertEquals(1, testMap.int32ToMessageField.size()); - TestMap.MessageValue messageValue = testMap.int32ToMessageField.get(0); - assertNotNull(messageValue); - assertEquals(0, messageValue.value); - assertEquals(0, messageValue.value2); - } - - public void testMapEquals() throws Exception { - TestMap a = new TestMap(); - TestMap b = new TestMap(); - - // empty and null map fields are equal. - assertTestMapEqual(a, b); - a.int32ToBytesField = new HashMap<Integer, byte[]>(); - assertTestMapEqual(a, b); - - a.int32ToInt32Field = new HashMap<Integer, Integer>(); - b.int32ToInt32Field = new HashMap<Integer, Integer>(); - setMap(a.int32ToInt32Field, deepCopy(int32Values), deepCopy(int32Values)); - setMap(b.int32ToInt32Field, deepCopy(int32Values), deepCopy(int32Values)); - assertTestMapEqual(a, b); - - a.int32ToMessageField = - new HashMap<Integer, MapTestProto.TestMap.MessageValue>(); - b.int32ToMessageField = - new HashMap<Integer, MapTestProto.TestMap.MessageValue>(); - setMap(a.int32ToMessageField, - deepCopy(int32Values), deepCopy(messageValues)); - setMap(b.int32ToMessageField, - deepCopy(int32Values), deepCopy(messageValues)); - assertTestMapEqual(a, b); - - a.stringToInt32Field = new HashMap<String, Integer>(); - b.stringToInt32Field = new HashMap<String, Integer>(); - setMap(a.stringToInt32Field, deepCopy(stringValues), deepCopy(int32Values)); - setMap(b.stringToInt32Field, deepCopy(stringValues), deepCopy(int32Values)); - assertTestMapEqual(a, b); - - a.int32ToBytesField = new HashMap<Integer, byte[]>(); - b.int32ToBytesField = new HashMap<Integer, byte[]>(); - setMap(a.int32ToBytesField, deepCopy(int32Values), deepCopy(bytesValues)); - setMap(b.int32ToBytesField, deepCopy(int32Values), deepCopy(bytesValues)); - assertTestMapEqual(a, b); - - // Make sure the map implementation does not matter. - a.int32ToStringField = new TreeMap<Integer, String>(); - b.int32ToStringField = new HashMap<Integer, String>(); - setMap(a.int32ToStringField, deepCopy(int32Values), deepCopy(stringValues)); - setMap(b.int32ToStringField, deepCopy(int32Values), deepCopy(stringValues)); - assertTestMapEqual(a, b); - - a.clear(); - b.clear(); - - // unequal cases: different value - a.int32ToInt32Field = new HashMap<Integer, Integer>(); - b.int32ToInt32Field = new HashMap<Integer, Integer>(); - a.int32ToInt32Field.put(1, 1); - b.int32ToInt32Field.put(1, 2); - assertTestMapUnequal(a, b); - // unequal case: additional entry - b.int32ToInt32Field.put(1, 1); - b.int32ToInt32Field.put(2, 1); - assertTestMapUnequal(a, b); - a.int32ToInt32Field.put(2, 1); - assertTestMapEqual(a, b); - - // unequal case: different message value. - a.int32ToMessageField = - new HashMap<Integer, MapTestProto.TestMap.MessageValue>(); - b.int32ToMessageField = - new HashMap<Integer, MapTestProto.TestMap.MessageValue>(); - MessageValue va = new MessageValue(); - va.value = 1; - MessageValue vb = new MessageValue(); - vb.value = 1; - a.int32ToMessageField.put(1, va); - b.int32ToMessageField.put(1, vb); - assertTestMapEqual(a, b); - vb.value = 2; - assertTestMapUnequal(a, b); - } - - private static void assertTestMapEqual(TestMap a, TestMap b) - throws Exception { - assertEquals(a.hashCode(), b.hashCode()); - assertTrue(a.equals(b)); - assertTrue(b.equals(a)); - } - - private static void assertTestMapUnequal(TestMap a, TestMap b) - throws Exception { - assertFalse(a.equals(b)); - assertFalse(b.equals(a)); - } - - private static final Integer[] int32Values = new Integer[] { - 0, 1, -1, Integer.MAX_VALUE, Integer.MIN_VALUE, - }; - - private static final Long[] int64Values = new Long[] { - 0L, 1L, -1L, Long.MAX_VALUE, Long.MIN_VALUE, - }; - - private static final String[] stringValues = new String[] { - "", "hello", "world", "foo", "bar", - }; - - private static final byte[][] bytesValues = new byte[][] { - new byte[] {}, - new byte[] {0}, - new byte[] {1, -1}, - new byte[] {127, -128}, - new byte[] {'a', 'b', '0', '1'}, - }; - - private static final Boolean[] boolValues = new Boolean[] { - false, true, - }; - - private static final Integer[] enumValues = new Integer[] { - TestMap.FOO, TestMap.BAR, TestMap.BAZ, TestMap.QUX, - Integer.MAX_VALUE /* unknown */, - }; - - private static final TestMap.MessageValue[] messageValues = - new TestMap.MessageValue[] { - newMapValueMessage(0), - newMapValueMessage(1), - newMapValueMessage(-1), - newMapValueMessage(Integer.MAX_VALUE), - newMapValueMessage(Integer.MIN_VALUE), - }; - - private static TestMap.MessageValue newMapValueMessage(int value) { - TestMap.MessageValue result = new TestMap.MessageValue(); - result.value = value; - return result; - } - - @SuppressWarnings("unchecked") - private static <T> T[] deepCopy(T[] orig) throws Exception { - if (orig instanceof MessageValue[]) { - MessageValue[] result = new MessageValue[orig.length]; - for (int i = 0; i < orig.length; i++) { - result[i] = new MessageValue(); - MessageNano.mergeFrom( - result[i], MessageNano.toByteArray((MessageValue) orig[i])); - } - return (T[]) result; - } - if (orig instanceof byte[][]) { - byte[][] result = new byte[orig.length][]; - for (int i = 0; i < orig.length; i++) { - byte[] origBytes = (byte[]) orig[i]; - result[i] = Arrays.copyOf(origBytes, origBytes.length); - } - } - return Arrays.copyOf(orig, orig.length); - } - - private <K, V> void setMap(Map<K, V> map, K[] keys, V[] values) { - assert(keys.length == values.length); - for (int i = 0; i < keys.length; i++) { - map.put(keys[i], values[i]); - } - } - - private <K, V> void assertMapSet( - Map<K, V> map, K[] keys, V[] values) throws Exception { - assert(keys.length == values.length); - for (int i = 0; i < values.length; i++) { - assertEquals(values[i], map.get(keys[i])); - } - assertEquals(keys.length, map.size()); - } - - private void setMapMessage(TestMap testMap) { - testMap.int32ToInt32Field = new HashMap<Integer, Integer>(); - testMap.int32ToBytesField = new HashMap<Integer, byte[]>(); - testMap.int32ToEnumField = new HashMap<Integer, Integer>(); - testMap.int32ToMessageField = - new HashMap<Integer, MapTestProto.TestMap.MessageValue>(); - testMap.int32ToStringField = new HashMap<Integer, String>(); - testMap.stringToInt32Field = new HashMap<String, Integer>(); - testMap.boolToBoolField = new HashMap<Boolean, Boolean>(); - testMap.uint32ToUint32Field = new HashMap<Integer, Integer>(); - testMap.sint32ToSint32Field = new HashMap<Integer, Integer>(); - testMap.fixed32ToFixed32Field = new HashMap<Integer, Integer>(); - testMap.sfixed32ToSfixed32Field = new HashMap<Integer, Integer>(); - testMap.int64ToInt64Field = new HashMap<Long, Long>(); - testMap.uint64ToUint64Field = new HashMap<Long, Long>(); - testMap.sint64ToSint64Field = new HashMap<Long, Long>(); - testMap.fixed64ToFixed64Field = new HashMap<Long, Long>(); - testMap.sfixed64ToSfixed64Field = new HashMap<Long, Long>(); - setMap(testMap.int32ToInt32Field, int32Values, int32Values); - setMap(testMap.int32ToBytesField, int32Values, bytesValues); - setMap(testMap.int32ToEnumField, int32Values, enumValues); - setMap(testMap.int32ToMessageField, int32Values, messageValues); - setMap(testMap.int32ToStringField, int32Values, stringValues); - setMap(testMap.stringToInt32Field, stringValues, int32Values); - setMap(testMap.boolToBoolField, boolValues, boolValues); - setMap(testMap.uint32ToUint32Field, int32Values, int32Values); - setMap(testMap.sint32ToSint32Field, int32Values, int32Values); - setMap(testMap.fixed32ToFixed32Field, int32Values, int32Values); - setMap(testMap.sfixed32ToSfixed32Field, int32Values, int32Values); - setMap(testMap.int64ToInt64Field, int64Values, int64Values); - setMap(testMap.uint64ToUint64Field, int64Values, int64Values); - setMap(testMap.sint64ToSint64Field, int64Values, int64Values); - setMap(testMap.fixed64ToFixed64Field, int64Values, int64Values); - setMap(testMap.sfixed64ToSfixed64Field, int64Values, int64Values); - } - private void assertMapMessageSet(TestMap testMap) throws Exception { - assertMapSet(testMap.int32ToInt32Field, int32Values, int32Values); - assertMapSet(testMap.int32ToBytesField, int32Values, bytesValues); - assertMapSet(testMap.int32ToEnumField, int32Values, enumValues); - assertMapSet(testMap.int32ToMessageField, int32Values, messageValues); - assertMapSet(testMap.int32ToStringField, int32Values, stringValues); - assertMapSet(testMap.stringToInt32Field, stringValues, int32Values); - assertMapSet(testMap.boolToBoolField, boolValues, boolValues); - assertMapSet(testMap.uint32ToUint32Field, int32Values, int32Values); - assertMapSet(testMap.sint32ToSint32Field, int32Values, int32Values); - assertMapSet(testMap.fixed32ToFixed32Field, int32Values, int32Values); - assertMapSet(testMap.sfixed32ToSfixed32Field, int32Values, int32Values); - assertMapSet(testMap.int64ToInt64Field, int64Values, int64Values); - assertMapSet(testMap.uint64ToUint64Field, int64Values, int64Values); - assertMapSet(testMap.sint64ToSint64Field, int64Values, int64Values); - assertMapSet(testMap.fixed64ToFixed64Field, int64Values, int64Values); - assertMapSet(testMap.sfixed64ToSfixed64Field, int64Values, int64Values); - } - - public void testRepeatedFieldInitializedInReftypesCompatMode() { - NanoReferenceTypesCompat.TestAllTypesNano proto = new NanoReferenceTypesCompat.TestAllTypesNano(); - assertNotNull(proto.repeatedString); - } - - private void assertRepeatedPackablesEqual( - NanoRepeatedPackables.NonPacked nonPacked, NanoRepeatedPackables.Packed packed) { - // Not using MessageNano.equals() -- that belongs to a separate test. - assertTrue(Arrays.equals(nonPacked.int32S, packed.int32S)); - assertTrue(Arrays.equals(nonPacked.int64S, packed.int64S)); - assertTrue(Arrays.equals(nonPacked.uint32S, packed.uint32S)); - assertTrue(Arrays.equals(nonPacked.uint64S, packed.uint64S)); - assertTrue(Arrays.equals(nonPacked.sint32S, packed.sint32S)); - assertTrue(Arrays.equals(nonPacked.sint64S, packed.sint64S)); - assertTrue(Arrays.equals(nonPacked.fixed32S, packed.fixed32S)); - assertTrue(Arrays.equals(nonPacked.fixed64S, packed.fixed64S)); - assertTrue(Arrays.equals(nonPacked.sfixed32S, packed.sfixed32S)); - assertTrue(Arrays.equals(nonPacked.sfixed64S, packed.sfixed64S)); - assertTrue(Arrays.equals(nonPacked.floats, packed.floats)); - assertTrue(Arrays.equals(nonPacked.doubles, packed.doubles)); - assertTrue(Arrays.equals(nonPacked.bools, packed.bools)); - assertTrue(Arrays.equals(nonPacked.enums, packed.enums)); - } - - public void testClone() throws Exception { - // A simple message. - AnotherMessage anotherMessage = new AnotherMessage(); - anotherMessage.string = "Hello"; - anotherMessage.value = true; - anotherMessage.integers = new int[] { 1, 2, 3 }; - - AnotherMessage clone = anotherMessage.clone(); - assertEquals(clone, anotherMessage); - - // Verify it was a deep clone - changes to the clone shouldn't affect the - // original. - clone.integers[1] = 100; - assertFalse(clone.equals(anotherMessage)); - } - - private void assertHasWireData(MessageNano message, boolean expected) { - byte[] bytes = MessageNano.toByteArray(message); - int wireLength = bytes.length; - if (expected) { - assertFalse(wireLength == 0); - } else { - if (wireLength != 0) { - fail("Expected no wire data for message \n" + message - + "\nBut got:\n" - + hexDump(bytes)); - } - } - } - - private static String hexDump(byte[] bytes) { - StringBuilder sb = new StringBuilder(); - for (byte b : bytes) { - sb.append(String.format("%02x ", b)); - } - return sb.toString(); - } -} diff --git a/javanano/src/test/java/com/google/protobuf/nano/map_test.proto b/javanano/src/test/java/com/google/protobuf/nano/map_test.proto deleted file mode 100644 index 51498a49..00000000 --- a/javanano/src/test/java/com/google/protobuf/nano/map_test.proto +++ /dev/null @@ -1,70 +0,0 @@ -// 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 map_test; - -option java_package = "com.google.protobuf"; -option java_outer_classname = "MapTestProto"; - -message TestMap { - message MessageValue { - int32 value = 1; - int32 value2 = 2; - } - enum EnumValue { - FOO = 0; - BAR = 1; - BAZ = 2; - QUX = 3; - } - - map<int32, int32> int32_to_int32_field = 1; - map<int32, string> int32_to_string_field = 2; - map<int32, bytes> int32_to_bytes_field = 3; - map<int32, EnumValue> int32_to_enum_field = 4; - map<int32, MessageValue> int32_to_message_field = 5; - map<string, int32> string_to_int32_field = 6; - map<bool, bool> bool_to_bool_field = 7; - - // Test all the other primitive types. As the key and value are not coupled in - // the implementation, we do not test all the combinations of key/value pairs, - // so that we can keep the number of test cases manageable - map<uint32, uint32> uint32_to_uint32_field = 11; - map<sint32, sint32> sint32_to_sint32_field = 12; - map<fixed32, fixed32> fixed32_to_fixed32_field = 13; - map<sfixed32, sfixed32> sfixed32_to_sfixed32_field = 14; - map<int64, int64> int64_to_int64_field = 15; - map<uint64, uint64> uint64_to_uint64_field = 16; - map<sint64, sint64> sint64_to_sint64_field = 17; - map<fixed64, fixed64> fixed64_to_fixed64_field = 18; - map<sfixed64, sfixed64> sfixed64_to_sfixed64_field = 19; -} diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_accessors_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_accessors_nano.proto deleted file mode 100644 index 6511e470..00000000 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_accessors_nano.proto +++ /dev/null @@ -1,118 +0,0 @@ -// 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: maxtroy@google.com (Max Cai) - -package protobuf_unittest; - -option java_package = "com.google.protobuf"; -option java_outer_classname = "NanoAccessorsOuterClass"; - -message TestNanoAccessors { - - message NestedMessage { - optional int32 bb = 1; - } - - enum NestedEnum { - FOO = 1; - BAR = 2; - BAZ = 3; - } - - // Singular - optional int32 optional_int32 = 1; - optional float optional_float = 11; - optional double optional_double = 12; - optional string optional_string = 14; - optional bytes optional_bytes = 15; - - optional NestedMessage optional_nested_message = 18; - - optional NestedEnum optional_nested_enum = 21; - - // Repeated - repeated int32 repeated_int32 = 31; - repeated string repeated_string = 44; - repeated bytes repeated_bytes = 45; - - repeated NestedMessage repeated_nested_message = 48; - - repeated NestedEnum repeated_nested_enum = 51; - - // Singular with defaults - optional int32 default_int32 = 61 [default = 41 ]; - optional string default_string = 74 [default = "hello"]; - optional bytes default_bytes = 75 [default = "world"]; - - optional float default_float_nan = 99 [default = nan]; - - optional NestedEnum default_nested_enum = 81 [default = BAR]; - - // Required - required int32 id = 86; - - // Add enough optional fields to make 2 bit fields in total - optional int32 filler100 = 100; - optional int32 filler101 = 101; - optional int32 filler102 = 102; - optional int32 filler103 = 103; - optional int32 filler104 = 104; - optional int32 filler105 = 105; - optional int32 filler106 = 106; - optional int32 filler107 = 107; - optional int32 filler108 = 108; - optional int32 filler109 = 109; - optional int32 filler110 = 110; - optional int32 filler111 = 111; - optional int32 filler112 = 112; - optional int32 filler113 = 113; - optional int32 filler114 = 114; - optional int32 filler115 = 115; - optional int32 filler116 = 116; - optional int32 filler117 = 117; - optional int32 filler118 = 118; - optional int32 filler119 = 119; - optional int32 filler120 = 120; - optional int32 filler121 = 121; - optional int32 filler122 = 122; - optional int32 filler123 = 123; - optional int32 filler124 = 124; - optional int32 filler125 = 125; - optional int32 filler126 = 126; - optional int32 filler127 = 127; - optional int32 filler128 = 128; - optional int32 filler129 = 129; - optional int32 filler130 = 130; - - optional int32 before_bit_field_check = 139; - optional int32 bit_field_check = 140; - optional int32 after_bit_field_check = 141; -} diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_enum_validity_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_enum_validity_nano.proto deleted file mode 100644 index c0da8b42..00000000 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_enum_validity_nano.proto +++ /dev/null @@ -1,28 +0,0 @@ -package protobuf_unittest; - -option java_package = "com.google.protobuf"; -option java_outer_classname = "EnumValidity"; - -enum E { - default = 1; // test java keyword renaming - FOO = 2; - BAR = 3; - BAZ = 4; -} - -message M { - optional E optional_e = 1; - optional E default_e = 2 [ default = BAZ ]; - repeated E repeated_e = 3; - repeated E packed_e = 4 [ packed = true ]; - repeated E repeated_e2 = 5; - repeated E packed_e2 = 6 [ packed = true ]; - repeated E repeated_e3 = 7; - repeated E packed_e3 = 8 [ packed = true ]; -} - -message Alt { - optional E repeated_e2_as_optional = 5; - repeated E packed_e2_as_non_packed = 6; - repeated E non_packed_e3_as_packed = 7 [ packed = true ]; -} diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_nano.proto deleted file mode 100644 index ca56b3dd..00000000 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_nano.proto +++ /dev/null @@ -1,37 +0,0 @@ -syntax = "proto2"; - -option java_outer_classname = "Extensions"; -option java_package = "com.google.protobuf.nano.testext"; - -message ExtendableMessage { - optional int32 field = 1; - extensions 10 to max; -} - -enum AnEnum { - FIRST_VALUE = 1; - SECOND_VALUE = 2; -} - -message AnotherMessage { - optional string string = 1; - optional bool value = 2; - repeated int32 integers = 3; -} - -message ContainerMessage { - extend ExtendableMessage { - optional bool another_thing = 100; - // The largest permitted field number, per - // https://developers.google.com/protocol-buffers/docs/proto#simple - optional bool large_field_number = 536870911; - } -} - -// For testNanoOptionalGroupWithUnknownFieldsEnabled; -// not part of the extensions tests. -message MessageWithGroup { - optional group Group = 1 { - optional int32 a = 2; - } -} diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_packed_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_packed_nano.proto deleted file mode 100644 index 3b7a004c..00000000 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_packed_nano.proto +++ /dev/null @@ -1,29 +0,0 @@ -syntax = "proto2"; - -option java_multiple_files = true; -option java_package = "com.google.protobuf"; - -import "google/protobuf/nano/unittest_extension_nano.proto"; - -// Must be compiled separately due to extension number reuse. -// The reuse is deliberate, for testing wire compatibility. - -message PackedExtensions { - extend ExtendableMessage { - repeated int32 packed_int32 = 10 [ packed = true ]; - repeated uint32 packed_uint32 = 11 [ packed = true ]; - repeated sint32 packed_sint32 = 12 [ packed = true ]; - repeated int64 packed_int64 = 13 [ packed = true ]; - repeated uint64 packed_uint64 = 14 [ packed = true ]; - repeated sint64 packed_sint64 = 15 [ packed = true ]; - repeated fixed32 packed_fixed32 = 16 [ packed = true ]; - repeated sfixed32 packed_sfixed32 = 17 [ packed = true ]; - repeated fixed64 packed_fixed64 = 18 [ packed = true ]; - repeated sfixed64 packed_sfixed64 = 19 [ packed = true ]; - repeated bool packed_bool = 20 [ packed = true ]; - repeated float packed_float = 21 [ packed = true ]; - repeated double packed_double = 22 [ packed = true ]; - repeated AnEnum packed_enum = 23 [ packed = true ]; - // Non-packable types omitted. - } -} diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_repeated_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_repeated_nano.proto deleted file mode 100644 index e533c65b..00000000 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_repeated_nano.proto +++ /dev/null @@ -1,34 +0,0 @@ -syntax = "proto2"; - -option java_multiple_files = true; -option java_package = "com.google.protobuf"; - -import "google/protobuf/nano/unittest_extension_nano.proto"; - -// Must be compiled separately due to extension number reuse. -// The reuse is deliberate, for testing wire compatibility. - -message RepeatedExtensions { - extend ExtendableMessage { - repeated int32 repeated_int32 = 10; - repeated uint32 repeated_uint32 = 11; - repeated sint32 repeated_sint32 = 12; - repeated int64 repeated_int64 = 13; - repeated uint64 repeated_uint64 = 14; - repeated sint64 repeated_sint64 = 15; - repeated fixed32 repeated_fixed32 = 16; - repeated sfixed32 repeated_sfixed32 = 17; - repeated fixed64 repeated_fixed64 = 18; - repeated sfixed64 repeated_sfixed64 = 19; - repeated bool repeated_bool = 20; - repeated float repeated_float = 21; - repeated double repeated_double = 22; - repeated AnEnum repeated_enum = 23; - repeated string repeated_string = 24; - repeated bytes repeated_bytes = 25; - repeated AnotherMessage repeated_message = 26; - repeated group RepeatedGroup = 27 { - optional int32 a = 1; - } - } -} diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_singular_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_singular_nano.proto deleted file mode 100644 index 8b2d9658..00000000 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_extension_singular_nano.proto +++ /dev/null @@ -1,34 +0,0 @@ -syntax = "proto2"; - -option java_multiple_files = true; -option java_package = "com.google.protobuf"; - -import "google/protobuf/nano/unittest_extension_nano.proto"; - -// Must be compiled separately due to extension number reuse. -// The reuse is deliberate, for testing wire compatibility. - -message SingularExtensions { - extend ExtendableMessage { - optional int32 some_int32 = 10; - optional uint32 some_uint32 = 11; - optional sint32 some_sint32 = 12; - optional int64 some_int64 = 13; - optional uint64 some_uint64 = 14; - optional sint64 some_sint64 = 15; - optional fixed32 some_fixed32 = 16; - optional sfixed32 some_sfixed32 = 17; - optional fixed64 some_fixed64 = 18; - optional sfixed64 some_sfixed64 = 19; - optional bool some_bool = 20; - optional float some_float = 21; - optional double some_double = 22; - optional AnEnum some_enum = 23; - optional string some_string = 24; - optional bytes some_bytes = 25; - optional AnotherMessage some_message = 26; - optional group SomeGroup = 27 { - optional int32 a = 1; - } - } -} diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_has_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_has_nano.proto deleted file mode 100644 index fe7d1794..00000000 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_has_nano.proto +++ /dev/null @@ -1,82 +0,0 @@ -// 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: ulas@google.com (Ulas Kirazci) - -package protobuf_unittest; - -option java_package = "com.google.protobuf"; -option java_outer_classname = "NanoHasOuterClass"; - -message TestAllTypesNanoHas { - - message NestedMessage { - optional int32 bb = 1; - } - - enum NestedEnum { - FOO = 1; - BAR = 2; - BAZ = 3; - } - - // Singular - optional int32 optional_int32 = 1; - optional float optional_float = 11; - optional double optional_double = 12; - optional string optional_string = 14; - optional bytes optional_bytes = 15; - - optional NestedMessage optional_nested_message = 18; - - optional NestedEnum optional_nested_enum = 21; - - // Repeated - repeated int32 repeated_int32 = 31; - repeated string repeated_string = 44; - repeated bytes repeated_bytes = 45; - - repeated NestedMessage repeated_nested_message = 48; - - repeated NestedEnum repeated_nested_enum = 51; - - // Singular with defaults - optional int32 default_int32 = 61 [default = 41 ]; - optional string default_string = 74 [default = "hello"]; - optional bytes default_bytes = 75 [default = "world"]; - - optional float default_float_nan = 99 [default = nan]; - - optional NestedEnum default_nested_enum = 81 [default = BAR]; - - required int32 id = 86; - required NestedEnum required_enum = 87; - -} diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_import_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_import_nano.proto deleted file mode 100644 index 1a3ddc57..00000000 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_import_nano.proto +++ /dev/null @@ -1,48 +0,0 @@ -// 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) -// -// This is like unittest_import.proto but with optimize_for = NANO_RUNTIME. - -package protobuf_unittest_import; - -option java_package = "com.google.protobuf.nano.testimport"; -option java_outer_classname = "UnittestImportNano"; - -message ImportMessageNano { - optional int32 d = 1; -} - -enum ImportEnumNano { - IMPORT_NANO_FOO = 7; - IMPORT_NANO_BAR = 8; - IMPORT_NANO_BAZ = 9; -} diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nano.proto deleted file mode 100644 index 406ab774..00000000 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nano.proto +++ /dev/null @@ -1,63 +0,0 @@ -// 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: maxtroy@google.com (Max Cai) - -package protobuf_unittest_import; - -import "google/protobuf/nano/unittest_import_nano.proto"; - -option java_package = "com.google.protobuf"; -option java_multiple_files = true; - -enum FileScopeEnum { - ONE = 1; - TWO = 2; -} - -message FileScopeEnumRefNano { - optional FileScopeEnum enum_field = 1; -} - -message MessageScopeEnumRefNano { - enum MessageScopeEnum { - ONE = 1; - TWO = 2; - } - optional MessageScopeEnum enum_field = 1; -} - -message MultipleImportingNonMultipleNano1 { - optional ImportMessageNano field = 1; -} - -message MultipleImportingNonMultipleNano2 { - optional MultipleImportingNonMultipleNano1 nano1 = 1; -} diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_nano.proto deleted file mode 100644 index 3fff24c0..00000000 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_nano.proto +++ /dev/null @@ -1,195 +0,0 @@ -// 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: wink@google.com (Wink Saville) - -package protobuf_unittest; - -import "google/protobuf/nano/unittest_import_nano.proto"; - -option java_package = "com.google.protobuf"; -option java_outer_classname = "NanoOuterClass"; - -// Same as TestAllTypes but with the nano runtime. -message TestAllTypesNano { - - message NestedMessage { - optional int32 bb = 1; - } - - enum NestedEnum { - FOO = 1; - BAR = 2; - BAZ = 3; - } - - // 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 ForeignMessageNano optional_foreign_message = 19; - optional protobuf_unittest_import.ImportMessageNano - optional_import_message = 20; - - optional NestedEnum optional_nested_enum = 21; - optional ForeignEnumNano optional_foreign_enum = 22; - optional protobuf_unittest_import.ImportEnumNano optional_import_enum = 23; - - optional string optional_string_piece = 24 [ctype=STRING_PIECE]; - optional string optional_cord = 25 [ctype=CORD]; - - // 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 ForeignMessageNano repeated_foreign_message = 49; - repeated protobuf_unittest_import.ImportMessageNano - repeated_import_message = 50; - - repeated NestedEnum repeated_nested_enum = 51; - repeated ForeignEnumNano repeated_foreign_enum = 52; - repeated protobuf_unittest_import.ImportEnumNano repeated_import_enum = 53; - - repeated string repeated_string_piece = 54 [ctype=STRING_PIECE]; - repeated string repeated_cord = 55 [ctype=CORD]; - - // Repeated packed - repeated int32 repeated_packed_int32 = 87 [packed=true]; - repeated sfixed64 repeated_packed_sfixed64 = 88 [packed=true]; - - repeated NestedEnum repeated_packed_nested_enum = 89 [packed=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 string default_string_nonascii = 76 [default = "dünya"]; - optional bytes default_bytes_nonascii = 77 [default = "dünyab"]; - - optional float default_float_inf = 97 [default = inf]; - optional float default_float_neg_inf = 98 [default = -inf]; - optional float default_float_nan = 99 [default = nan]; - optional double default_double_inf = 100 [default = inf]; - optional double default_double_neg_inf = 101 [default = -inf]; - optional double default_double_nan = 102 [default = nan]; - - optional NestedEnum default_nested_enum = 81 [default = BAR]; - optional ForeignEnumNano default_foreign_enum = 82 - [default = FOREIGN_NANO_BAR]; - optional protobuf_unittest_import.ImportEnumNano - default_import_enum = 83 [default = IMPORT_NANO_BAR]; - - optional string default_string_piece = 84 [ctype=STRING_PIECE,default="abc"]; - optional string default_cord = 85 [ctype=CORD,default="123"]; - - required int32 id = 86; - - // Try to cause conflicts. - optional int32 tag = 93; - optional int32 get_serialized_size = 94; - optional int32 write_to = 95; - - // Try to fail with java reserved keywords - optional int32 synchronized = 96; - - oneof oneof_field { - uint32 oneof_uint32 = 111; - NestedMessage oneof_nested_message = 112; - string oneof_string = 123; - bytes oneof_bytes = 124; - fixed64 oneof_fixed64 = 115; - NestedEnum oneof_enum = 116; - } -} - -message ForeignMessageNano { - optional int32 c = 1; -} - -enum ForeignEnumNano { - FOREIGN_NANO_FOO = 4; - FOREIGN_NANO_BAR = 5; - FOREIGN_NANO_BAZ = 6; -} - -// Test that deprecated fields work. We only verify that they compile (at one -// point this failed). -message TestDeprecatedNano { - optional int32 deprecated_field = 1 [deprecated = true]; -} diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_recursive_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_recursive_nano.proto deleted file mode 100644 index 29b944f0..00000000 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_recursive_nano.proto +++ /dev/null @@ -1,49 +0,0 @@ -// 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: wink@google.com (Wink Saville) -// - -package protobuf_unittest_import; - -option java_package = "com.google.protobuf"; -// Explicit outer classname to suppress legacy info. -option java_outer_classname = "UnittestRecursiveNano"; - -message RecursiveMessageNano { - message NestedMessage { - optional RecursiveMessageNano a = 1; - } - - required int32 id = 1; - optional NestedMessage nested_message = 2; - optional RecursiveMessageNano optional_recursive_message_nano = 3; - repeated RecursiveMessageNano repeated_recursive_message_nano = 4; -} diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_reference_types_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_reference_types_nano.proto deleted file mode 100644 index 82eb8d11..00000000 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_reference_types_nano.proto +++ /dev/null @@ -1,116 +0,0 @@ -package protobuf_unittest; - -option java_package = "com.google.protobuf"; -option java_outer_classname = "NanoReferenceTypes"; - -message TestAllTypesNano { - - enum NestedEnum { - FOO = 1; - BAR = 2; - BAZ = 3; - } - - message NestedMessage { - optional int32 foo = 1; - } - - // 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 NestedEnum optional_nested_enum = 21; - - optional string optional_string_piece = 24 [ctype=STRING_PIECE]; - optional string optional_cord = 25 [ctype=CORD]; - - // 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 NestedEnum repeated_nested_enum = 51; - - repeated string repeated_string_piece = 54 [ctype=STRING_PIECE]; - repeated string repeated_cord = 55 [ctype=CORD]; - - // Repeated packed - repeated int32 repeated_packed_int32 = 87 [packed=true]; - repeated sfixed64 repeated_packed_sfixed64 = 88 [packed=true]; - - repeated NestedEnum repeated_packed_nested_enum = 89 [packed=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 float default_float_inf = 97 [default = inf]; - optional float default_float_neg_inf = 98 [default = -inf]; - optional float default_float_nan = 99 [default = nan]; - optional double default_double_inf = 100 [default = inf]; - optional double default_double_neg_inf = 101 [default = -inf]; - optional double default_double_nan = 102 [default = nan]; - -} - -message ForeignMessageNano { - optional int32 c = 1; -} - -enum ForeignEnumNano { - FOREIGN_NANO_FOO = 4; - FOREIGN_NANO_BAR = 5; - FOREIGN_NANO_BAZ = 6; -} - diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_packables_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_packables_nano.proto deleted file mode 100644 index 96af8856..00000000 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_packables_nano.proto +++ /dev/null @@ -1,95 +0,0 @@ -// 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: maxtroy@google.com (Max Cai) - -package protobuf_unittest; - -option java_package = "com.google.protobuf"; -option java_outer_classname = "NanoRepeatedPackables"; - -enum Enum { - OPTION_ONE = 1; - OPTION_TWO = 2; -} - -// Two almost identical messages with all packable repeated field types. -// One with none marked as packed and the other all packed. For -// compatibility, they should be able to parse each other's serialized -// forms. - -message NonPacked { - - // All packable types, none marked as packed. - - repeated int32 int32s = 1; - repeated int64 int64s = 2; - repeated uint32 uint32s = 3; - repeated uint64 uint64s = 4; - repeated sint32 sint32s = 5; - repeated sint64 sint64s = 6; - repeated fixed32 fixed32s = 7; - repeated fixed64 fixed64s = 8; - repeated sfixed32 sfixed32s = 9; - repeated sfixed64 sfixed64s = 10; - repeated float floats = 11; - repeated double doubles = 12; - repeated bool bools = 13; - repeated Enum enums = 14; - - // Noise for testing merged deserialization. - optional int32 noise = 15; - -} - -message Packed { - - // All packable types, all matching the field numbers in NonPacked, - // all marked as packed. - - repeated int32 int32s = 1 [ packed = true ]; - repeated int64 int64s = 2 [ packed = true ]; - repeated uint32 uint32s = 3 [ packed = true ]; - repeated uint64 uint64s = 4 [ packed = true ]; - repeated sint32 sint32s = 5 [ packed = true ]; - repeated sint64 sint64s = 6 [ packed = true ]; - repeated fixed32 fixed32s = 7 [ packed = true ]; - repeated fixed64 fixed64s = 8 [ packed = true ]; - repeated sfixed32 sfixed32s = 9 [ packed = true ]; - repeated sfixed64 sfixed64s = 10 [ packed = true ]; - repeated float floats = 11 [ packed = true ]; - repeated double doubles = 12 [ packed = true ]; - repeated bool bools = 13 [ packed = true ]; - repeated Enum enums = 14 [ packed = true ]; - - // Noise for testing merged deserialization. - optional int32 noise = 15; - -} diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_simple_nano.proto b/javanano/src/test/java/com/google/protobuf/nano/unittest_simple_nano.proto deleted file mode 100644 index 25786cc2..00000000 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_simple_nano.proto +++ /dev/null @@ -1,54 +0,0 @@ -// 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: wink@google.com (Wink Saville) -// - -package protobuf_unittest_import; - -option java_package = "com.google.protobuf"; -// Explicit outer classname to suppress legacy info. -option java_outer_classname = "UnittestSimpleNano"; - -message SimpleMessageNano { - message NestedMessage { - optional int32 bb = 1; - } - - enum NestedEnum { - FOO = 1; - BAR = 2; - BAZ = 3; - } - - optional int32 d = 1 [default = 123]; - optional NestedMessage nested_msg = 2; - optional NestedEnum default_nested_enum = 3 [default = BAZ]; -} diff --git a/jenkins/README.md b/jenkins/README.md deleted file mode 100644 index 29f664f2..00000000 --- a/jenkins/README.md +++ /dev/null @@ -1,6 +0,0 @@ - -Jenkins Infrastructure ----------------------- - -The scripts in this directory serve as plumbing for running the protobuf -tests under Jenkins. diff --git a/jenkins/build_and_run_docker.sh b/jenkins/build_and_run_docker.sh deleted file mode 100755 index 50e1e8c6..00000000 --- a/jenkins/build_and_run_docker.sh +++ /dev/null @@ -1,57 +0,0 @@ -#!/bin/bash -# -# Builds docker image and runs a command under it. -# This is a generic script that is configured with the following variables: -# -# DOCKERFILE_DIR - Directory in which Dockerfile file is located. -# DOCKER_RUN_SCRIPT - Script to run under docker (relative to protobuf repo root) -# OUTPUT_DIR - Directory that will be copied from inside docker after finishing. -# $@ - Extra args to pass to docker run - - -set -ex - -cd $(dirname $0)/.. -git_root=$(pwd) -cd - - -# Use image name based on Dockerfile location checksum -DOCKER_IMAGE_NAME=$(basename $DOCKERFILE_DIR)_$(sha1sum $DOCKERFILE_DIR/Dockerfile | cut -f1 -d\ ) - -# Make sure docker image has been built. Should be instantaneous if so. -docker build -t $DOCKER_IMAGE_NAME $DOCKERFILE_DIR - -# Ensure existence of ccache directory -CCACHE_DIR=/tmp/protobuf-ccache -mkdir -p $CCACHE_DIR - -# Choose random name for docker container -CONTAINER_NAME="build_and_run_docker_$(uuidgen)" - -# Run command inside docker -docker run \ - "$@" \ - -e CCACHE_DIR=$CCACHE_DIR \ - -e EXTERNAL_GIT_ROOT="/var/local/jenkins/protobuf" \ - -e TEST_SET="$TEST_SET" \ - -e THIS_IS_REALLY_NEEDED='see https://github.com/docker/docker/issues/14203 for why docker is awful' \ - -v "$git_root:/var/local/jenkins/protobuf:ro" \ - -v $CCACHE_DIR:$CCACHE_DIR \ - -w /var/local/git/protobuf \ - --name=$CONTAINER_NAME \ - $DOCKER_IMAGE_NAME \ - bash -l "/var/local/jenkins/protobuf/$DOCKER_RUN_SCRIPT" || FAILED="true" - -# Copy output artifacts -if [ "$OUTPUT_DIR" != "" ] -then - docker cp "$CONTAINER_NAME:/var/local/git/protobuf/$OUTPUT_DIR" "$git_root" || FAILED="true" -fi - -# remove the container, possibly killing it first -docker rm -f $CONTAINER_NAME || true - -if [ "$FAILED" != "" ] -then - exit 1 -fi diff --git a/jenkins/buildcmds/README.md b/jenkins/buildcmds/README.md deleted file mode 100644 index 7a48f2d5..00000000 --- a/jenkins/buildcmds/README.md +++ /dev/null @@ -1,6 +0,0 @@ - -Jenkins Build Commands ----------------------- - -The scripts in this directory are designed to be top-level entry points for -Jenkins projects. diff --git a/jenkins/buildcmds/pull_request.sh b/jenkins/buildcmds/pull_request.sh deleted file mode 100755 index 51e4bfa4..00000000 --- a/jenkins/buildcmds/pull_request.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash -# -# This is the top-level script we give to Jenkins as the entry point for -# running the "pull request" project: -# -# https://grpc-testing.appspot.com/view/Protocol%20Buffers/job/protobuf_pull_request/ -# -# 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. - -export DOCKERFILE_DIR=jenkins/docker -export DOCKER_RUN_SCRIPT=jenkins/pull_request_in_docker.sh -export OUTPUT_DIR=testoutput -export TEST_SET="csharp java_jdk7 javanano_jdk7 java_oracle7 javanano_oracle7 python python_cpp ruby_all javascript golang php_all" -./jenkins/build_and_run_docker.sh diff --git a/jenkins/buildcmds/pull_request_32.sh b/jenkins/buildcmds/pull_request_32.sh deleted file mode 100755 index bf0fb7ff..00000000 --- a/jenkins/buildcmds/pull_request_32.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash -# -# This is the top-level script we give to Jenkins as the entry point for -# running the "pull request 32" project: -# -# https://grpc-testing.appspot.com/view/Protocol%20Buffers/job/Protocol%20Buffers%20Pull%20Request%2032/ -# -# 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. - -export DOCKERFILE_DIR=jenkins/docker32 -export DOCKER_RUN_SCRIPT=jenkins/pull_request_in_docker.sh -export OUTPUT_DIR=testoutput -export TEST_SET="php_all_32" -./jenkins/build_and_run_docker.sh diff --git a/jenkins/docker/Dockerfile b/jenkins/docker/Dockerfile deleted file mode 100644 index 3a279e66..00000000 --- a/jenkins/docker/Dockerfile +++ /dev/null @@ -1,244 +0,0 @@ -# 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 debian:latest - -# Apt source for old Python versions. -RUN echo 'deb http://ppa.launchpad.net/fkrull/deadsnakes/ubuntu trusty main' > /etc/apt/sources.list.d/deadsnakes.list && \ - apt-key adv --keyserver keyserver.ubuntu.com --recv-keys DB82666C - -# Apt source for Oracle Java. -RUN echo 'deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main' > /etc/apt/sources.list.d/webupd8team-java-trusty.list && \ - apt-key adv --keyserver keyserver.ubuntu.com --recv-keys EEA14886 && \ - echo "oracle-java7-installer shared/accepted-oracle-license-v1-1 select true" | debconf-set-selections - -# Apt source for Mono -RUN echo "deb http://download.mono-project.com/repo/debian wheezy main" | tee /etc/apt/sources.list.d/mono-xamarin.list && \ - echo "deb http://download.mono-project.com/repo/debian wheezy-libjpeg62-compat main" | tee -a /etc/apt/sources.list.d/mono-xamarin.list && \ - apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF - -# 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 dotnet SDK based on https://www.microsoft.com/net/core#debian -# (Ubuntu instructions need apt to support https) -RUN apt-get update && apt-get install -y --force-yes curl libunwind8 gettext && \ - curl -sSL -o dotnet.tar.gz https://go.microsoft.com/fwlink/?LinkID=847105 && \ - mkdir -p /opt/dotnet && tar zxf dotnet.tar.gz -C /opt/dotnet && \ - ln -s /opt/dotnet/dotnet /usr/local/bin - -# 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 \ - # -- For csharp -- - mono-devel \ - referenceassemblies-pcl \ - nunit \ - # -- For all Java builds -- \ - maven \ - # -- For java_jdk6 -- \ - # oops! not in jessie. too old? openjdk-6-jdk \ - # -- For java_jdk7 -- \ - openjdk-7-jdk \ - # -- For java_oracle7 -- \ - oracle-java7-installer \ - # -- For python / python_cpp -- \ - python-setuptools \ - python-pip \ - python-dev \ - python2.6-dev \ - python3.3-dev \ - python3.4-dev \ - # -- For Ruby -- - ruby \ - # -- For C++ benchmarks -- - cmake \ - # -- For PHP -- - php5.6 \ - php5.6-dev \ - php5.6-xml \ - php7.0 \ - php7.0-dev \ - php7.0-xml \ - phpunit \ - valgrind \ - libxml2-dev \ - && apt-get clean - -################## -# C# dependencies - -RUN wget www.nuget.org/NuGet.exe -O /usr/local/bin/nuget.exe - -################## -# 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 - -################## -# Ruby dependencies - -# Install rvm -RUN gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 -RUN \curl -sSL https://get.rvm.io | bash -s stable - -# Install Ruby 2.1, Ruby 2.2 and JRuby 1.7 -RUN /bin/bash -l -c "rvm install ruby-2.1" -RUN /bin/bash -l -c "rvm install ruby-2.2" -RUN /bin/bash -l -c "rvm install jruby-1.7" -RUN /bin/bash -l -c "echo 'gem: --no-ri --no-rdoc' > ~/.gemrc" -RUN /bin/bash -l -c "echo 'export PATH=/usr/local/rvm/bin:$PATH' >> ~/.bashrc" -RUN /bin/bash -l -c "gem install bundler --no-ri --no-rdoc" - -################## -# Java dependencies - -# This step requires compiling protoc. :( - -ENV MAVEN_REPO /var/maven_local_repository -ENV MVN mvn --batch-mode - -RUN cd /tmp && \ - git clone https://github.com/google/protobuf.git && \ - cd protobuf && \ - git reset --hard 129a6e2aca95dcfb6c3e717d7b9cca1f104fde39 && \ - ./autogen.sh && \ - ./configure && \ - make -j4 && \ - cd java && \ - $MVN install dependency:go-offline -Dmaven.repo.local=$MAVEN_REPO && \ - cd ../javanano && \ - $MVN install dependency:go-offline -Dmaven.repo.local=$MAVEN_REPO - -################## -# 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 && cd .. -RUN cd php-5.5.38 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-5.5 && \ - make && make install && 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 && \ - rm -rf protobuf && \ - git clone https://github.com/google/protobuf.git && \ - cd protobuf && \ - git reset --hard 49b44bff2b6257a119f9c6a342d6151c736586b8 && \ - cd php && \ - 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 - -################## -# Go dependencies. -RUN apt-get install -y \ - # -- For go -- \ - golang - -################## -# Javascript dependencies. -RUN apt-get install -y \ - # -- For javascript -- \ - npm - -################## -# Python 3.5 3.6 dependencies. -RUN apt-get clean && apt-get update && apt-get install -y --force-yes \ - python3.5-dev \ - python3.6-dev \ - && apt-get clean - -# On Debian/Ubuntu, nodejs binary is named 'nodejs' because the name 'node' -# is taken by another legacy binary. We don't have that legacy binary and -# npm expects the binary to be named 'node', so we just create a symbol -# link here. -RUN ln -s `which nodejs` /usr/bin/node - -################## -# 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/jenkins/docker32/Dockerfile b/jenkins/docker32/Dockerfile deleted file mode 100644 index 1278889f..00000000 --- a/jenkins/docker32/Dockerfile +++ /dev/null @@ -1,143 +0,0 @@ -# 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/jenkins/make_test_output.py b/jenkins/make_test_output.py deleted file mode 100644 index 98536853..00000000 --- a/jenkins/make_test_output.py +++ /dev/null @@ -1,94 +0,0 @@ -"""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/jenkins/pull_request_in_docker.sh b/jenkins/pull_request_in_docker.sh deleted file mode 100755 index 10daf0a5..00000000 --- a/jenkins/pull_request_in_docker.sh +++ /dev/null @@ -1,66 +0,0 @@ -#!/bin/bash -# -# This is the script that runs inside Docker, once the image has been built, -# to execute all tests for the "pull request" project. - -WORKSPACE_BASE=`pwd` -MY_DIR="$(dirname "$0")" -TEST_SCRIPT=$MY_DIR/../tests.sh -BUILD_DIR=/tmp/protobuf - -set -e # exit immediately on error -set -x # display all commands - -# The protobuf repository is mounted into our Docker image, but read-only. -# We clone into a directory inside Docker (this is faster than cp). -rm -rf $BUILD_DIR -mkdir -p $BUILD_DIR -cd $BUILD_DIR -git clone /var/local/jenkins/protobuf -cd protobuf - -# Set up the directory where our test output is going to go. -OUTPUT_DIR=`mktemp -d` -LOG_OUTPUT_DIR=$OUTPUT_DIR/logs -mkdir -p $LOG_OUTPUT_DIR/1/cpp - -################################################################################ -# cpp build needs to run first, non-parallelized, so that protoc is available -# for other builds. - -# Output filenames to follow the overall scheme used by parallel, ie: -# $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 -CPP_STDOUT=$LOG_OUTPUT_DIR/1/cpp/stdout -CPP_STDERR=$LOG_OUTPUT_DIR/1/cpp/stderr - -# Time the C++ build, so we can put this info in the test output. -# It's important that we get /usr/bin/time (which supports -f and -o) and not -# the bash builtin "time" which doesn't. -TIME_CMD="/usr/bin/time -f %e -o $LOG_OUTPUT_DIR/1/cpp/build_time" - -$TIME_CMD $TEST_SCRIPT cpp > >(tee $CPP_STDOUT) 2> >(tee $CPP_STDERR >&2) - -# Other tests are run in parallel. TEST_SET is defined in -# buildcmds/pull_request{_32}.sh - -parallel --results $LOG_OUTPUT_DIR --joblog $OUTPUT_DIR/joblog $TEST_SCRIPT ::: \ - $TEST_SET \ - || true # Process test results even if tests fail. - -cat $OUTPUT_DIR/joblog - -# The directory that is copied from Docker back into the Jenkins workspace. -COPY_FROM_DOCKER=/var/local/git/protobuf/testoutput -mkdir -p $COPY_FROM_DOCKER -TESTOUTPUT_XML_FILE=$COPY_FROM_DOCKER/testresults.xml - -# Process all the output files from "parallel" and package them into a single -# .xml file with detailed, broken-down test output. -python $MY_DIR/make_test_output.py $OUTPUT_DIR > $TESTOUTPUT_XML_FILE - -ls -l $TESTOUTPUT_XML_FILE diff --git a/js/message.js b/js/message.js index 04d43339..86d18295 100644 --- a/js/message.js +++ b/js/message.js @@ -923,6 +923,17 @@ jspb.Message.setProto3IntField = function(msg, fieldNumber, value) { /** + * Sets the value of a non-extension integer, handled as string, field of a proto3 + * @param {!jspb.Message} msg A jspb proto. + * @param {number} fieldNumber The field number. + * @param {number} value New value + * @protected + */ +jspb.Message.setProto3StringIntField = function(msg, fieldNumber, value) { + jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, '0'); +}; + +/** * Sets the value of a non-extension floating point field of a proto3 * @param {!jspb.Message} msg A jspb proto. * @param {number} fieldNumber The field number. diff --git a/js/package.json b/js/package.json index 3c1c2a42..39d99f93 100644 --- a/js/package.json +++ b/js/package.json @@ -1,6 +1,6 @@ { "name": "google-protobuf", - "version": "3.5.1", + "version": "3.5.2", "description": "Protocol Buffers for JavaScript", "main": "google-protobuf.js", "files": [ diff --git a/kokoro/linux/javanano_jdk7/build.sh b/kokoro/linux/javanano_jdk7/build.sh deleted file mode 100755 index 2fc06475..00000000 --- a/kokoro/linux/javanano_jdk7/build.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/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="javanano_jdk7" -./kokoro/linux/build_and_run_docker.sh diff --git a/kokoro/linux/javanano_jdk7/continuous.cfg b/kokoro/linux/javanano_jdk7/continuous.cfg deleted file mode 100644 index 72936484..00000000 --- a/kokoro/linux/javanano_jdk7/continuous.cfg +++ /dev/null @@ -1,11 +0,0 @@ -# Config file for running tests in Kokoro - -# Location of the build script in repository -build_file: "protobuf/kokoro/linux/javanano_jdk7/build.sh" -timeout_mins: 120 - -action { - define_artifacts { - regex: "**/sponge_log.xml" - } -} diff --git a/kokoro/linux/javanano_jdk7/presubmit.cfg b/kokoro/linux/javanano_jdk7/presubmit.cfg deleted file mode 100644 index 72936484..00000000 --- a/kokoro/linux/javanano_jdk7/presubmit.cfg +++ /dev/null @@ -1,11 +0,0 @@ -# Config file for running tests in Kokoro - -# Location of the build script in repository -build_file: "protobuf/kokoro/linux/javanano_jdk7/build.sh" -timeout_mins: 120 - -action { - define_artifacts { - regex: "**/sponge_log.xml" - } -} diff --git a/kokoro/linux/javanano_oracle7/build.sh b/kokoro/linux/javanano_oracle7/build.sh deleted file mode 100755 index 651d17e8..00000000 --- a/kokoro/linux/javanano_oracle7/build.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/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="javanano_oracle7" -./kokoro/linux/build_and_run_docker.sh diff --git a/kokoro/linux/javanano_oracle7/continuous.cfg b/kokoro/linux/javanano_oracle7/continuous.cfg deleted file mode 100644 index 9cac8972..00000000 --- a/kokoro/linux/javanano_oracle7/continuous.cfg +++ /dev/null @@ -1,11 +0,0 @@ -# Config file for running tests in Kokoro - -# Location of the build script in repository -build_file: "protobuf/kokoro/linux/javanano_oracle7/build.sh" -timeout_mins: 120 - -action { - define_artifacts { - regex: "**/sponge_log.xml" - } -} diff --git a/kokoro/linux/javanano_oracle7/presubmit.cfg b/kokoro/linux/javanano_oracle7/presubmit.cfg deleted file mode 100644 index 9cac8972..00000000 --- a/kokoro/linux/javanano_oracle7/presubmit.cfg +++ /dev/null @@ -1,11 +0,0 @@ -# Config file for running tests in Kokoro - -# Location of the build script in repository -build_file: "protobuf/kokoro/linux/javanano_oracle7/build.sh" -timeout_mins: 120 - -action { - define_artifacts { - regex: "**/sponge_log.xml" - } -} diff --git a/kokoro/linux/pull_request_in_docker.sh b/kokoro/linux/pull_request_in_docker.sh index 23e63961..df3636cc 100755 --- a/kokoro/linux/pull_request_in_docker.sh +++ b/kokoro/linux/pull_request_in_docker.sh @@ -19,6 +19,9 @@ cd $BUILD_DIR git clone /var/local/kokoro/protobuf cd protobuf +# Initialize any submodules: +git submodule update --init --recursive + # Set up the directory where our test output is going to go. OUTPUT_DIR=`mktemp -d` LOG_OUTPUT_DIR=$OUTPUT_DIR/logs diff --git a/more_tests/Makefile b/more_tests/Makefile deleted file mode 100755 index 286cf0f1..00000000 --- a/more_tests/Makefile +++ /dev/null @@ -1,41 +0,0 @@ -# Additional tests to run before releasing a package. -# -# Run like: -# make PACKAGE=/path/to/protobuf-VERSION.tar.gz -# -# Some of these tests require tools or make assumptions that may not be -# available on end-user machines, so these cannot be part of "make check". For -# example, we test that the headers compile with strict warning settings, but -# since different compilers produce wildly different warnings we cannot assume -# that this test will pass everywhere. If we ran it as part of "make check", -# it could unnecessarily block users from running the real tests just because -# their compiler produces some extra warnings that probably aren't a big deal. -# So we run it separately. - -all: header_warning_test - -clean: - rm -rf src target header_warning_test.cc header_warning_test.o header_warning_test - -# Unpack the package into src, then install it into target. -PACKAGE=protobuf.tar.gz - -src: $(PACKAGE) - tar zxvf $(PACKAGE) - mv `basename $(PACKAGE) .tar.gz` src - -target: src - (cd src && ./configure --prefix=$$PWD/../target --disable-shared) - (cd src && make -j4 check) - (cd src && make install) - -# Verify that headers produce no warnings even under strict settings. -header_warning_test.cc: target - ( (cd target/include && find google/protobuf -name '*.h') | \ - awk '{print "#include \""$$1"\""} ' > header_warning_test.cc ) - -header_warning_test: header_warning_test.cc - # TODO(kenton): Consider adding -pedantic and -Weffc++. Currently these - # produce tons of extra warnings so we'll need to do some work first. - g++ -Itarget/include -Wall -Werror -Wsign-compare -O2 -c header_warning_test.cc - touch header_warning_test diff --git a/objectivec/GPBProtocolBuffers_RuntimeSupport.h b/objectivec/GPBProtocolBuffers_RuntimeSupport.h index fea75b93..04dde620 100644 --- a/objectivec/GPBProtocolBuffers_RuntimeSupport.h +++ b/objectivec/GPBProtocolBuffers_RuntimeSupport.h @@ -31,7 +31,7 @@ // This header is meant to only be used by the generated source, it should not // be included in code using protocol buffers. -#import "GPBProtocolBuffers.h" +#import "GPBBootstrap.h" #import "GPBDescriptor_PackagePrivate.h" #import "GPBExtensionInternals.h" diff --git a/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj b/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj index 266b05a1..a41be9f2 100644 --- a/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj +++ b/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj @@ -37,6 +37,31 @@ 8BF8193514A0DDA600A2C982 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D30AB110D05D00D00671497 /* Foundation.framework */; }; F401DC2D1A8D444600FCC765 /* GPBArray.m in Sources */ = {isa = PBXBuildFile; fileRef = F401DC2B1A8D444600FCC765 /* GPBArray.m */; }; F401DC331A8E5C0200FCC765 /* GPBArrayTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F401DC321A8E5C0200FCC765 /* GPBArrayTests.m */; }; + F40EE4AB206BF8B90071091A /* GPBCompileTest01.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE488206BF8B00071091A /* GPBCompileTest01.m */; }; + F40EE4AC206BF8B90071091A /* GPBCompileTest02.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE481206BF8AE0071091A /* GPBCompileTest02.m */; }; + F40EE4AD206BF8B90071091A /* GPBCompileTest03.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE491206BF8B10071091A /* GPBCompileTest03.m */; }; + F40EE4AE206BF8B90071091A /* GPBCompileTest04.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE47E206BF8AE0071091A /* GPBCompileTest04.m */; }; + F40EE4AF206BF8B90071091A /* GPBCompileTest05.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE47F206BF8AE0071091A /* GPBCompileTest05.m */; }; + F40EE4B0206BF8B90071091A /* GPBCompileTest06.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE492206BF8B10071091A /* GPBCompileTest06.m */; }; + F40EE4B1206BF8B90071091A /* GPBCompileTest07.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE480206BF8AE0071091A /* GPBCompileTest07.m */; }; + F40EE4B2206BF8B90071091A /* GPBCompileTest08.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE47D206BF8AD0071091A /* GPBCompileTest08.m */; }; + F40EE4B3206BF8B90071091A /* GPBCompileTest09.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE484206BF8AF0071091A /* GPBCompileTest09.m */; }; + F40EE4B4206BF8B90071091A /* GPBCompileTest10.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE48C206BF8B00071091A /* GPBCompileTest10.m */; }; + F40EE4B5206BF8B90071091A /* GPBCompileTest11.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE493206BF8B20071091A /* GPBCompileTest11.m */; }; + F40EE4B6206BF8B90071091A /* GPBCompileTest12.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE490206BF8B10071091A /* GPBCompileTest12.m */; }; + F40EE4B7206BF8B90071091A /* GPBCompileTest13.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE483206BF8AF0071091A /* GPBCompileTest13.m */; }; + F40EE4B8206BF8B90071091A /* GPBCompileTest14.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE48F206BF8B10071091A /* GPBCompileTest14.m */; }; + F40EE4B9206BF8B90071091A /* GPBCompileTest15.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE489206BF8B00071091A /* GPBCompileTest15.m */; }; + F40EE4BA206BF8B90071091A /* GPBCompileTest16.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE48B206BF8B00071091A /* GPBCompileTest16.m */; }; + F40EE4BB206BF8B90071091A /* GPBCompileTest17.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE48D206BF8B00071091A /* GPBCompileTest17.m */; }; + F40EE4BC206BF8B90071091A /* GPBCompileTest18.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE48E206BF8B10071091A /* GPBCompileTest18.m */; }; + F40EE4BD206BF8B90071091A /* GPBCompileTest19.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE482206BF8AF0071091A /* GPBCompileTest19.m */; }; + F40EE4BE206BF8B90071091A /* GPBCompileTest20.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE485206BF8AF0071091A /* GPBCompileTest20.m */; }; + F40EE4BF206BF8B90071091A /* GPBCompileTest21.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE486206BF8AF0071091A /* GPBCompileTest21.m */; }; + F40EE4C0206BF8B90071091A /* GPBCompileTest22.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE48A206BF8B00071091A /* GPBCompileTest22.m */; }; + F40EE4C1206BF8B90071091A /* GPBCompileTest23.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE487206BF8B00071091A /* GPBCompileTest23.m */; }; + F40EE50B206C06640071091A /* GPBCompileTest24.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE508206C06440071091A /* GPBCompileTest24.m */; }; + F40EE50C206C06640071091A /* GPBCompileTest25.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE507206C06440071091A /* GPBCompileTest25.m */; }; F41C175D1833D3310064ED4D /* GPBPerfTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F41C175C1833D3310064ED4D /* GPBPerfTests.m */; }; F4353D1D1AB8822D005A6198 /* GPBDescriptorTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F4353D1C1AB8822D005A6198 /* GPBDescriptorTests.m */; }; F4353D231ABB1537005A6198 /* GPBDictionary.m in Sources */ = {isa = PBXBuildFile; fileRef = F4353D211ABB1537005A6198 /* GPBDictionary.m */; }; @@ -158,6 +183,31 @@ F401DC2A1A8D444600FCC765 /* GPBArray.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBArray.h; sourceTree = "<group>"; }; F401DC2B1A8D444600FCC765 /* GPBArray.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBArray.m; sourceTree = "<group>"; }; F401DC321A8E5C0200FCC765 /* GPBArrayTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBArrayTests.m; sourceTree = "<group>"; }; + F40EE47D206BF8AD0071091A /* GPBCompileTest08.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest08.m; sourceTree = "<group>"; }; + F40EE47E206BF8AE0071091A /* GPBCompileTest04.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest04.m; sourceTree = "<group>"; }; + F40EE47F206BF8AE0071091A /* GPBCompileTest05.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest05.m; sourceTree = "<group>"; }; + F40EE480206BF8AE0071091A /* GPBCompileTest07.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest07.m; sourceTree = "<group>"; }; + F40EE481206BF8AE0071091A /* GPBCompileTest02.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest02.m; sourceTree = "<group>"; }; + F40EE482206BF8AF0071091A /* GPBCompileTest19.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest19.m; sourceTree = "<group>"; }; + F40EE483206BF8AF0071091A /* GPBCompileTest13.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest13.m; sourceTree = "<group>"; }; + F40EE484206BF8AF0071091A /* GPBCompileTest09.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest09.m; sourceTree = "<group>"; }; + F40EE485206BF8AF0071091A /* GPBCompileTest20.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest20.m; sourceTree = "<group>"; }; + F40EE486206BF8AF0071091A /* GPBCompileTest21.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest21.m; sourceTree = "<group>"; }; + F40EE487206BF8B00071091A /* GPBCompileTest23.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest23.m; sourceTree = "<group>"; }; + F40EE488206BF8B00071091A /* GPBCompileTest01.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest01.m; sourceTree = "<group>"; }; + F40EE489206BF8B00071091A /* GPBCompileTest15.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest15.m; sourceTree = "<group>"; }; + F40EE48A206BF8B00071091A /* GPBCompileTest22.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest22.m; sourceTree = "<group>"; }; + F40EE48B206BF8B00071091A /* GPBCompileTest16.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest16.m; sourceTree = "<group>"; }; + F40EE48C206BF8B00071091A /* GPBCompileTest10.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest10.m; sourceTree = "<group>"; }; + F40EE48D206BF8B00071091A /* GPBCompileTest17.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest17.m; sourceTree = "<group>"; }; + F40EE48E206BF8B10071091A /* GPBCompileTest18.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest18.m; sourceTree = "<group>"; }; + F40EE48F206BF8B10071091A /* GPBCompileTest14.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest14.m; sourceTree = "<group>"; }; + F40EE490206BF8B10071091A /* GPBCompileTest12.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest12.m; sourceTree = "<group>"; }; + F40EE491206BF8B10071091A /* GPBCompileTest03.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest03.m; sourceTree = "<group>"; }; + F40EE492206BF8B10071091A /* GPBCompileTest06.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest06.m; sourceTree = "<group>"; }; + F40EE493206BF8B20071091A /* GPBCompileTest11.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest11.m; sourceTree = "<group>"; }; + F40EE507206C06440071091A /* GPBCompileTest25.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest25.m; sourceTree = "<group>"; }; + F40EE508206C06440071091A /* GPBCompileTest24.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest24.m; sourceTree = "<group>"; }; F41C175C1833D3310064ED4D /* GPBPerfTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBPerfTests.m; sourceTree = "<group>"; }; F4353D1C1AB8822D005A6198 /* GPBDescriptorTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBDescriptorTests.m; sourceTree = "<group>"; }; F4353D201ABB1537005A6198 /* GPBDictionary.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBDictionary.h; sourceTree = "<group>"; }; @@ -395,6 +445,31 @@ F401DC321A8E5C0200FCC765 /* GPBArrayTests.m */, 7461B69B0F94FDF800A0C422 /* GPBCodedInputStreamTests.m */, 7461B69D0F94FDF800A0C422 /* GPBCodedOuputStreamTests.m */, + F40EE488206BF8B00071091A /* GPBCompileTest01.m */, + F40EE481206BF8AE0071091A /* GPBCompileTest02.m */, + F40EE491206BF8B10071091A /* GPBCompileTest03.m */, + F40EE47E206BF8AE0071091A /* GPBCompileTest04.m */, + F40EE47F206BF8AE0071091A /* GPBCompileTest05.m */, + F40EE492206BF8B10071091A /* GPBCompileTest06.m */, + F40EE480206BF8AE0071091A /* GPBCompileTest07.m */, + F40EE47D206BF8AD0071091A /* GPBCompileTest08.m */, + F40EE484206BF8AF0071091A /* GPBCompileTest09.m */, + F40EE48C206BF8B00071091A /* GPBCompileTest10.m */, + F40EE493206BF8B20071091A /* GPBCompileTest11.m */, + F40EE490206BF8B10071091A /* GPBCompileTest12.m */, + F40EE483206BF8AF0071091A /* GPBCompileTest13.m */, + F40EE48F206BF8B10071091A /* GPBCompileTest14.m */, + F40EE489206BF8B00071091A /* GPBCompileTest15.m */, + F40EE48B206BF8B00071091A /* GPBCompileTest16.m */, + F40EE48D206BF8B00071091A /* GPBCompileTest17.m */, + F40EE48E206BF8B10071091A /* GPBCompileTest18.m */, + F40EE482206BF8AF0071091A /* GPBCompileTest19.m */, + F40EE485206BF8AF0071091A /* GPBCompileTest20.m */, + F40EE486206BF8AF0071091A /* GPBCompileTest21.m */, + F40EE48A206BF8B00071091A /* GPBCompileTest22.m */, + F40EE487206BF8B00071091A /* GPBCompileTest23.m */, + F40EE508206C06440071091A /* GPBCompileTest24.m */, + F40EE507206C06440071091A /* GPBCompileTest25.m */, 5102DABB1891A052002037B6 /* GPBConcurrencyTests.m */, F4353D1C1AB8822D005A6198 /* GPBDescriptorTests.m */, F4C4B9E21E1D974F00D3B61D /* GPBDictionaryTests.m */, @@ -562,7 +637,7 @@ attributes = { LastSwiftUpdateCheck = 0710; LastTestingUpgradeCheck = 0600; - LastUpgradeCheck = 0900; + LastUpgradeCheck = 0930; TargetAttributes = { 8BBEA4A5147C727100C4ADB7 = { LastSwiftMigration = 0800; @@ -661,28 +736,53 @@ buildActionMask = 2147483647; files = ( 8BBEA4A9147C727D00C4ADB7 /* GPBCodedInputStreamTests.m in Sources */, + F40EE50B206C06640071091A /* GPBCompileTest24.m in Sources */, + F40EE4BE206BF8B90071091A /* GPBCompileTest20.m in Sources */, F401DC331A8E5C0200FCC765 /* GPBArrayTests.m in Sources */, + F40EE4B4206BF8B90071091A /* GPBCompileTest10.m in Sources */, F4353D361AC06F10005A6198 /* GPBDictionaryTests+Int64.m in Sources */, + F40EE4C0206BF8B90071091A /* GPBCompileTest22.m in Sources */, + F40EE4B2206BF8B90071091A /* GPBCompileTest08.m in Sources */, + F40EE4BB206BF8B90071091A /* GPBCompileTest17.m in Sources */, F4353D391AC06F10005A6198 /* GPBDictionaryTests+UInt64.m in Sources */, 8BBEA4AA147C727D00C4ADB7 /* GPBCodedOuputStreamTests.m in Sources */, + F40EE4C1206BF8B90071091A /* GPBCompileTest23.m in Sources */, 8BBEA4AC147C727D00C4ADB7 /* GPBMessageTests.m in Sources */, F4B51B1E1BBC610700744318 /* GPBObjectiveCPlusPlusTest.mm in Sources */, + F40EE4BD206BF8B90071091A /* GPBCompileTest19.m in Sources */, + F40EE4B0206BF8B90071091A /* GPBCompileTest06.m in Sources */, + F40EE4B6206BF8B90071091A /* GPBCompileTest12.m in Sources */, F4487C7F1AAF62CD00531423 /* GPBMessageTests+Serialization.m in Sources */, + F40EE4AD206BF8B90071091A /* GPBCompileTest03.m in Sources */, + F40EE4BC206BF8B90071091A /* GPBCompileTest18.m in Sources */, + F40EE4B7206BF8B90071091A /* GPBCompileTest13.m in Sources */, + F40EE4B9206BF8B90071091A /* GPBCompileTest15.m in Sources */, + F40EE4B1206BF8B90071091A /* GPBCompileTest07.m in Sources */, 8B4248DC1A92933A00BC1EC6 /* GPBWellKnownTypesTest.m in Sources */, + F40EE4BF206BF8B90071091A /* GPBCompileTest21.m in Sources */, + F40EE4B5206BF8B90071091A /* GPBCompileTest11.m in Sources */, F4F8D8831D789FD9002CE128 /* GPBUnittestProtos2.m in Sources */, F4353D1D1AB8822D005A6198 /* GPBDescriptorTests.m in Sources */, 8B4248BB1A8C256A00BC1EC6 /* GPBSwiftTests.swift in Sources */, + F40EE50C206C06640071091A /* GPBCompileTest25.m in Sources */, F4584D821ECCB52A00803AB6 /* GPBExtensionRegistryTest.m in Sources */, 5102DABC1891A073002037B6 /* GPBConcurrencyTests.m in Sources */, F4487C751AADF7F500531423 /* GPBMessageTests+Runtime.m in Sources */, + F40EE4AC206BF8B90071091A /* GPBCompileTest02.m in Sources */, F4353D351AC06F10005A6198 /* GPBDictionaryTests+Int32.m in Sources */, + F40EE4AF206BF8B90071091A /* GPBCompileTest05.m in Sources */, + F40EE4B8206BF8B90071091A /* GPBCompileTest14.m in Sources */, 8BBEA4B0147C727D00C4ADB7 /* GPBTestUtilities.m in Sources */, + F40EE4AE206BF8B90071091A /* GPBCompileTest04.m in Sources */, + F40EE4BA206BF8B90071091A /* GPBCompileTest16.m in Sources */, F41C175D1833D3310064ED4D /* GPBPerfTests.m in Sources */, F4353D341AC06F10005A6198 /* GPBDictionaryTests+Bool.m in Sources */, F4487C831AAF6AB300531423 /* GPBMessageTests+Merge.m in Sources */, + F40EE4AB206BF8B90071091A /* GPBCompileTest01.m in Sources */, 8BBEA4B6147C727D00C4ADB7 /* GPBUnknownFieldSetTest.m in Sources */, F4353D371AC06F10005A6198 /* GPBDictionaryTests+String.m in Sources */, F4353D381AC06F10005A6198 /* GPBDictionaryTests+UInt32.m in Sources */, + F40EE4B3206BF8B90071091A /* GPBCompileTest09.m in Sources */, 8BBEA4B7147C727D00C4ADB7 /* GPBUtilitiesTests.m in Sources */, F4C4B9E41E1D976300D3B61D /* GPBDictionaryTests.m in Sources */, 8BBEA4B8147C727D00C4ADB7 /* GPBWireFormatTests.m in Sources */, @@ -718,6 +818,7 @@ 7461B52F0F94FAFA00A0C422 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; COMBINE_HIDPI_IMAGES = YES; HEADER_SEARCH_PATHS = "$(SRCROOT)"; PRODUCT_NAME = ProtocolBuffers; @@ -727,6 +828,7 @@ 7461B5300F94FAFA00A0C422 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; COMBINE_HIDPI_IMAGES = YES; HEADER_SEARCH_PATHS = "$(SRCROOT)"; PRODUCT_NAME = ProtocolBuffers; @@ -737,6 +839,7 @@ isa = XCBuildConfiguration; buildSettings = { CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_WEAK = YES; COMBINE_HIDPI_IMAGES = YES; HEADER_SEARCH_PATHS = ( "${PROJECT_DERIVED_FILE_DIR}/protos", @@ -763,6 +866,7 @@ isa = XCBuildConfiguration; buildSettings = { CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_WEAK = YES; COMBINE_HIDPI_IMAGES = YES; HEADER_SEARCH_PATHS = ( "${PROJECT_DERIVED_FILE_DIR}/protos", @@ -925,6 +1029,7 @@ F4487C4F1A9F8E0200531423 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; COMBINE_HIDPI_IMAGES = YES; HEADER_SEARCH_PATHS = "$(SRCROOT)"; PRODUCT_NAME = TestSingleSourceBuild; @@ -934,6 +1039,7 @@ F4487C501A9F8E0200531423 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; COMBINE_HIDPI_IMAGES = YES; HEADER_SEARCH_PATHS = "$(SRCROOT)"; PRODUCT_NAME = TestSingleSourceBuild; @@ -943,12 +1049,14 @@ F45BBC151B0CE3C6002D064D /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; }; name = Debug; }; F45BBC161B0CE3C6002D064D /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; }; name = Release; }; diff --git a/objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>IDEDidComputeMac32BitWarning</key> + <true/> +</dict> +</plist> diff --git a/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme b/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme index d3c29389..6653a1b0 100644 --- a/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme +++ b/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?> <Scheme - LastUpgradeVersion = "0900" + LastUpgradeVersion = "0930" version = "1.3"> <BuildAction parallelizeBuildables = "YES" @@ -26,7 +26,6 @@ buildConfiguration = "Release" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - language = "" shouldUseLaunchSchemeArgsEnv = "YES"> <Testables> <TestableReference @@ -301,7 +300,6 @@ buildConfiguration = "Release" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - language = "" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" diff --git a/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme b/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme index e7fb8215..328771b8 100644 --- a/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme +++ b/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?> <Scheme - LastUpgradeVersion = "0900" + LastUpgradeVersion = "0930" version = "1.3"> <BuildAction parallelizeBuildables = "YES" @@ -54,9 +54,8 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - language = "" - shouldUseLaunchSchemeArgsEnv = "YES" - codeCoverageEnabled = "YES"> + codeCoverageEnabled = "YES" + shouldUseLaunchSchemeArgsEnv = "YES"> <Testables> <TestableReference skipped = "NO"> @@ -90,7 +89,6 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - language = "" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" diff --git a/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj b/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj index 9333ea7d..0c0e1810 100644 --- a/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj +++ b/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj @@ -44,6 +44,31 @@ 8BD3981F14BE59D70081D629 /* GPBUnittestProtos.m in Sources */ = {isa = PBXBuildFile; fileRef = 8BD3981E14BE59D70081D629 /* GPBUnittestProtos.m */; }; 8BF8193514A0DDA600A2C982 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D30AB110D05D00D00671497 /* Foundation.framework */; }; F401DC351A8E5C6F00FCC765 /* GPBArrayTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F401DC341A8E5C6F00FCC765 /* GPBArrayTests.m */; }; + F40EE4F0206BF91E0071091A /* GPBCompileTest01.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4CD206BF9170071091A /* GPBCompileTest01.m */; }; + F40EE4F1206BF91E0071091A /* GPBCompileTest02.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4C6206BF9170071091A /* GPBCompileTest02.m */; }; + F40EE4F2206BF91E0071091A /* GPBCompileTest03.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4D6206BF9190071091A /* GPBCompileTest03.m */; }; + F40EE4F3206BF91E0071091A /* GPBCompileTest04.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4C3206BF9160071091A /* GPBCompileTest04.m */; }; + F40EE4F4206BF91E0071091A /* GPBCompileTest05.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4C4206BF9160071091A /* GPBCompileTest05.m */; }; + F40EE4F5206BF91E0071091A /* GPBCompileTest06.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4D7206BF9190071091A /* GPBCompileTest06.m */; }; + F40EE4F6206BF91E0071091A /* GPBCompileTest07.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4C5206BF9170071091A /* GPBCompileTest07.m */; }; + F40EE4F7206BF91E0071091A /* GPBCompileTest08.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4C2206BF9160071091A /* GPBCompileTest08.m */; }; + F40EE4F8206BF91E0071091A /* GPBCompileTest09.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4C9206BF9170071091A /* GPBCompileTest09.m */; }; + F40EE4F9206BF91E0071091A /* GPBCompileTest10.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4D1206BF9180071091A /* GPBCompileTest10.m */; }; + F40EE4FA206BF91E0071091A /* GPBCompileTest11.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4D8206BF9190071091A /* GPBCompileTest11.m */; }; + F40EE4FB206BF91E0071091A /* GPBCompileTest12.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4D5206BF9180071091A /* GPBCompileTest12.m */; }; + F40EE4FC206BF91E0071091A /* GPBCompileTest13.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4C8206BF9170071091A /* GPBCompileTest13.m */; }; + F40EE4FD206BF91E0071091A /* GPBCompileTest14.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4D4206BF9180071091A /* GPBCompileTest14.m */; }; + F40EE4FE206BF91E0071091A /* GPBCompileTest15.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4CE206BF9170071091A /* GPBCompileTest15.m */; }; + F40EE4FF206BF91E0071091A /* GPBCompileTest16.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4D0206BF9180071091A /* GPBCompileTest16.m */; }; + F40EE500206BF91E0071091A /* GPBCompileTest17.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4D2206BF9180071091A /* GPBCompileTest17.m */; }; + F40EE501206BF91E0071091A /* GPBCompileTest18.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4D3206BF9180071091A /* GPBCompileTest18.m */; }; + F40EE502206BF91E0071091A /* GPBCompileTest19.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4C7206BF9170071091A /* GPBCompileTest19.m */; }; + F40EE503206BF91E0071091A /* GPBCompileTest20.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4CA206BF9170071091A /* GPBCompileTest20.m */; }; + F40EE504206BF91E0071091A /* GPBCompileTest21.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4CB206BF9170071091A /* GPBCompileTest21.m */; }; + F40EE505206BF91E0071091A /* GPBCompileTest22.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4CF206BF9170071091A /* GPBCompileTest22.m */; }; + F40EE506206BF91E0071091A /* GPBCompileTest23.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4CC206BF9170071091A /* GPBCompileTest23.m */; }; + F40EE511206C068D0071091A /* GPBCompileTest24.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE50E206C06880071091A /* GPBCompileTest24.m */; }; + F40EE512206C068D0071091A /* GPBCompileTest25.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE50D206C06880071091A /* GPBCompileTest25.m */; }; F41C175D1833D3310064ED4D /* GPBPerfTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F41C175C1833D3310064ED4D /* GPBPerfTests.m */; }; F4353D1F1AB88243005A6198 /* GPBDescriptorTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F4353D1E1AB88243005A6198 /* GPBDescriptorTests.m */; }; F4353D271ABB156F005A6198 /* GPBDictionary.m in Sources */ = {isa = PBXBuildFile; fileRef = F4353D251ABB156F005A6198 /* GPBDictionary.m */; }; @@ -178,6 +203,31 @@ 8BD3981E14BE59D70081D629 /* GPBUnittestProtos.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBUnittestProtos.m; sourceTree = "<group>"; }; 8BEB5AE01498033E0078BF9D /* GPBRuntimeTypes.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBRuntimeTypes.h; sourceTree = "<group>"; }; F401DC341A8E5C6F00FCC765 /* GPBArrayTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBArrayTests.m; sourceTree = "<group>"; }; + F40EE4C2206BF9160071091A /* GPBCompileTest08.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest08.m; sourceTree = "<group>"; }; + F40EE4C3206BF9160071091A /* GPBCompileTest04.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest04.m; sourceTree = "<group>"; }; + F40EE4C4206BF9160071091A /* GPBCompileTest05.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest05.m; sourceTree = "<group>"; }; + F40EE4C5206BF9170071091A /* GPBCompileTest07.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest07.m; sourceTree = "<group>"; }; + F40EE4C6206BF9170071091A /* GPBCompileTest02.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest02.m; sourceTree = "<group>"; }; + F40EE4C7206BF9170071091A /* GPBCompileTest19.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest19.m; sourceTree = "<group>"; }; + F40EE4C8206BF9170071091A /* GPBCompileTest13.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest13.m; sourceTree = "<group>"; }; + F40EE4C9206BF9170071091A /* GPBCompileTest09.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest09.m; sourceTree = "<group>"; }; + F40EE4CA206BF9170071091A /* GPBCompileTest20.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest20.m; sourceTree = "<group>"; }; + F40EE4CB206BF9170071091A /* GPBCompileTest21.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest21.m; sourceTree = "<group>"; }; + F40EE4CC206BF9170071091A /* GPBCompileTest23.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest23.m; sourceTree = "<group>"; }; + F40EE4CD206BF9170071091A /* GPBCompileTest01.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest01.m; sourceTree = "<group>"; }; + F40EE4CE206BF9170071091A /* GPBCompileTest15.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest15.m; sourceTree = "<group>"; }; + F40EE4CF206BF9170071091A /* GPBCompileTest22.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest22.m; sourceTree = "<group>"; }; + F40EE4D0206BF9180071091A /* GPBCompileTest16.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest16.m; sourceTree = "<group>"; }; + F40EE4D1206BF9180071091A /* GPBCompileTest10.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest10.m; sourceTree = "<group>"; }; + F40EE4D2206BF9180071091A /* GPBCompileTest17.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest17.m; sourceTree = "<group>"; }; + F40EE4D3206BF9180071091A /* GPBCompileTest18.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest18.m; sourceTree = "<group>"; }; + F40EE4D4206BF9180071091A /* GPBCompileTest14.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest14.m; sourceTree = "<group>"; }; + F40EE4D5206BF9180071091A /* GPBCompileTest12.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest12.m; sourceTree = "<group>"; }; + F40EE4D6206BF9190071091A /* GPBCompileTest03.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest03.m; sourceTree = "<group>"; }; + F40EE4D7206BF9190071091A /* GPBCompileTest06.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest06.m; sourceTree = "<group>"; }; + F40EE4D8206BF9190071091A /* GPBCompileTest11.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest11.m; sourceTree = "<group>"; }; + F40EE50D206C06880071091A /* GPBCompileTest25.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest25.m; sourceTree = "<group>"; }; + F40EE50E206C06880071091A /* GPBCompileTest24.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest24.m; sourceTree = "<group>"; }; F41C175C1833D3310064ED4D /* GPBPerfTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBPerfTests.m; sourceTree = "<group>"; }; F4353D1E1AB88243005A6198 /* GPBDescriptorTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBDescriptorTests.m; sourceTree = "<group>"; }; F4353D241ABB156F005A6198 /* GPBDictionary.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBDictionary.h; sourceTree = "<group>"; }; @@ -433,6 +483,31 @@ F401DC341A8E5C6F00FCC765 /* GPBArrayTests.m */, 7461B69B0F94FDF800A0C422 /* GPBCodedInputStreamTests.m */, 7461B69D0F94FDF800A0C422 /* GPBCodedOuputStreamTests.m */, + F40EE4CD206BF9170071091A /* GPBCompileTest01.m */, + F40EE4C6206BF9170071091A /* GPBCompileTest02.m */, + F40EE4D6206BF9190071091A /* GPBCompileTest03.m */, + F40EE4C3206BF9160071091A /* GPBCompileTest04.m */, + F40EE4C4206BF9160071091A /* GPBCompileTest05.m */, + F40EE4D7206BF9190071091A /* GPBCompileTest06.m */, + F40EE4C5206BF9170071091A /* GPBCompileTest07.m */, + F40EE4C2206BF9160071091A /* GPBCompileTest08.m */, + F40EE4C9206BF9170071091A /* GPBCompileTest09.m */, + F40EE4D1206BF9180071091A /* GPBCompileTest10.m */, + F40EE4D8206BF9190071091A /* GPBCompileTest11.m */, + F40EE4D5206BF9180071091A /* GPBCompileTest12.m */, + F40EE4C8206BF9170071091A /* GPBCompileTest13.m */, + F40EE4D4206BF9180071091A /* GPBCompileTest14.m */, + F40EE4CE206BF9170071091A /* GPBCompileTest15.m */, + F40EE4D0206BF9180071091A /* GPBCompileTest16.m */, + F40EE4D2206BF9180071091A /* GPBCompileTest17.m */, + F40EE4D3206BF9180071091A /* GPBCompileTest18.m */, + F40EE4C7206BF9170071091A /* GPBCompileTest19.m */, + F40EE4CA206BF9170071091A /* GPBCompileTest20.m */, + F40EE4CB206BF9170071091A /* GPBCompileTest21.m */, + F40EE4CF206BF9170071091A /* GPBCompileTest22.m */, + F40EE4CC206BF9170071091A /* GPBCompileTest23.m */, + F40EE50E206C06880071091A /* GPBCompileTest24.m */, + F40EE50D206C06880071091A /* GPBCompileTest25.m */, 5102DABB1891A052002037B6 /* GPBConcurrencyTests.m */, F4353D1E1AB88243005A6198 /* GPBDescriptorTests.m */, F4C4B9E51E1D97BB00D3B61D /* GPBDictionaryTests.m */, @@ -639,7 +714,7 @@ attributes = { LastSwiftUpdateCheck = 0710; LastTestingUpgradeCheck = 0600; - LastUpgradeCheck = 0900; + LastUpgradeCheck = 0930; TargetAttributes = { 8BBEA4A5147C727100C4ADB7 = { LastSwiftMigration = 0800; @@ -757,28 +832,53 @@ buildActionMask = 2147483647; files = ( 8BBEA4A9147C727D00C4ADB7 /* GPBCodedInputStreamTests.m in Sources */, + F40EE511206C068D0071091A /* GPBCompileTest24.m in Sources */, + F40EE503206BF91E0071091A /* GPBCompileTest20.m in Sources */, F401DC351A8E5C6F00FCC765 /* GPBArrayTests.m in Sources */, + F40EE4F9206BF91E0071091A /* GPBCompileTest10.m in Sources */, F4353D441AC06F31005A6198 /* GPBDictionaryTests+Int64.m in Sources */, + F40EE505206BF91E0071091A /* GPBCompileTest22.m in Sources */, + F40EE4F7206BF91E0071091A /* GPBCompileTest08.m in Sources */, + F40EE500206BF91E0071091A /* GPBCompileTest17.m in Sources */, F4353D471AC06F31005A6198 /* GPBDictionaryTests+UInt64.m in Sources */, 8BBEA4AA147C727D00C4ADB7 /* GPBCodedOuputStreamTests.m in Sources */, + F40EE506206BF91E0071091A /* GPBCompileTest23.m in Sources */, 8BBEA4AC147C727D00C4ADB7 /* GPBMessageTests.m in Sources */, F4487C811AAF62FC00531423 /* GPBMessageTests+Serialization.m in Sources */, + F40EE502206BF91E0071091A /* GPBCompileTest19.m in Sources */, + F40EE4F5206BF91E0071091A /* GPBCompileTest06.m in Sources */, + F40EE4FB206BF91E0071091A /* GPBCompileTest12.m in Sources */, 8B4248E61A929C9900BC1EC6 /* GPBWellKnownTypesTest.m in Sources */, + F40EE4F2206BF91E0071091A /* GPBCompileTest03.m in Sources */, + F40EE501206BF91E0071091A /* GPBCompileTest18.m in Sources */, + F40EE4FC206BF91E0071091A /* GPBCompileTest13.m in Sources */, + F40EE4FE206BF91E0071091A /* GPBCompileTest15.m in Sources */, + F40EE4F6206BF91E0071091A /* GPBCompileTest07.m in Sources */, F4353D1F1AB88243005A6198 /* GPBDescriptorTests.m in Sources */, + F40EE504206BF91E0071091A /* GPBCompileTest21.m in Sources */, + F40EE4FA206BF91E0071091A /* GPBCompileTest11.m in Sources */, F4F8D8861D78A193002CE128 /* GPBUnittestProtos2.m in Sources */, F4B51B1C1BBC5C7100744318 /* GPBObjectiveCPlusPlusTest.mm in Sources */, 8B4248B41A8BD96E00BC1EC6 /* GPBSwiftTests.swift in Sources */, + F40EE512206C068D0071091A /* GPBCompileTest25.m in Sources */, F4584D831ECCB53600803AB6 /* GPBExtensionRegistryTest.m in Sources */, 5102DABC1891A073002037B6 /* GPBConcurrencyTests.m in Sources */, F4487C771AADF84900531423 /* GPBMessageTests+Runtime.m in Sources */, + F40EE4F1206BF91E0071091A /* GPBCompileTest02.m in Sources */, F4353D431AC06F31005A6198 /* GPBDictionaryTests+Int32.m in Sources */, + F40EE4F4206BF91E0071091A /* GPBCompileTest05.m in Sources */, + F40EE4FD206BF91E0071091A /* GPBCompileTest14.m in Sources */, 8BBEA4B0147C727D00C4ADB7 /* GPBTestUtilities.m in Sources */, + F40EE4F3206BF91E0071091A /* GPBCompileTest04.m in Sources */, + F40EE4FF206BF91E0071091A /* GPBCompileTest16.m in Sources */, F41C175D1833D3310064ED4D /* GPBPerfTests.m in Sources */, F4353D421AC06F31005A6198 /* GPBDictionaryTests+Bool.m in Sources */, F4487C851AAF6AC500531423 /* GPBMessageTests+Merge.m in Sources */, + F40EE4F0206BF91E0071091A /* GPBCompileTest01.m in Sources */, 8BBEA4B6147C727D00C4ADB7 /* GPBUnknownFieldSetTest.m in Sources */, F4353D451AC06F31005A6198 /* GPBDictionaryTests+String.m in Sources */, F4353D461AC06F31005A6198 /* GPBDictionaryTests+UInt32.m in Sources */, + F40EE4F8206BF91E0071091A /* GPBCompileTest09.m in Sources */, 8BBEA4B7147C727D00C4ADB7 /* GPBUtilitiesTests.m in Sources */, F4C4B9E71E1D97BF00D3B61D /* GPBDictionaryTests.m in Sources */, 8BBEA4B8147C727D00C4ADB7 /* GPBWireFormatTests.m in Sources */, @@ -830,6 +930,7 @@ 7461B52F0F94FAFA00A0C422 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; HEADER_SEARCH_PATHS = "$(SRCROOT)"; PRODUCT_NAME = ProtocolBuffers; TARGETED_DEVICE_FAMILY = "1,2"; @@ -839,6 +940,7 @@ 7461B5300F94FAFA00A0C422 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; HEADER_SEARCH_PATHS = "$(SRCROOT)"; PRODUCT_NAME = ProtocolBuffers; TARGETED_DEVICE_FAMILY = "1,2"; @@ -879,6 +981,7 @@ isa = XCBuildConfiguration; buildSettings = { CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_WEAK = YES; FRAMEWORK_SEARCH_PATHS = ( "\"$(DEVELOPER_LIBRARY_DIR)/Frameworks\"", "$(inherited)", @@ -914,6 +1017,7 @@ isa = XCBuildConfiguration; buildSettings = { CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_WEAK = YES; FRAMEWORK_SEARCH_PATHS = ( "\"$(DEVELOPER_LIBRARY_DIR)/Frameworks\"", "$(inherited)", @@ -1087,6 +1191,7 @@ F4487C6C1A9F8F8100531423 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; HEADER_SEARCH_PATHS = "$(SRCROOT)"; PRODUCT_NAME = TestSingleSourceBuild; TARGETED_DEVICE_FAMILY = "1,2"; @@ -1096,6 +1201,7 @@ F4487C6D1A9F8F8100531423 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; HEADER_SEARCH_PATHS = "$(SRCROOT)"; PRODUCT_NAME = TestSingleSourceBuild; TARGETED_DEVICE_FAMILY = "1,2"; @@ -1105,12 +1211,14 @@ F45BBC0F1B0CDB50002D064D /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; }; name = Debug; }; F45BBC101B0CDB50002D064D /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; }; name = Release; }; diff --git a/objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>IDEDidComputeMac32BitWarning</key> + <true/> +</dict> +</plist> diff --git a/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme b/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme index 03acb083..77483d38 100644 --- a/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme +++ b/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?> <Scheme - LastUpgradeVersion = "0900" + LastUpgradeVersion = "0930" version = "1.3"> <BuildAction parallelizeBuildables = "YES" @@ -26,7 +26,6 @@ buildConfiguration = "Release" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - language = "" shouldUseLaunchSchemeArgsEnv = "YES"> <Testables> <TestableReference @@ -310,7 +309,6 @@ buildConfiguration = "Release" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - language = "" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" diff --git a/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme b/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme index 98bcd562..69825cc5 100644 --- a/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme +++ b/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?> <Scheme - LastUpgradeVersion = "0900" + LastUpgradeVersion = "0930" version = "1.3"> <BuildAction parallelizeBuildables = "YES" @@ -54,9 +54,8 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - language = "" - shouldUseLaunchSchemeArgsEnv = "YES" - codeCoverageEnabled = "YES"> + codeCoverageEnabled = "YES" + shouldUseLaunchSchemeArgsEnv = "YES"> <Testables> <TestableReference skipped = "NO"> @@ -90,7 +89,6 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - language = "" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nameclash_nano.proto b/objectivec/Tests/GPBCompileTest01.m index b31c4399..c8bc433a 100644 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_multiple_nameclash_nano.proto +++ b/objectivec/Tests/GPBCompileTest01.m @@ -28,14 +28,13 @@ // (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: maxtroy@google.com (Max Cai) -package protobuf_unittest_import; +// This is a test including a single public header to ensure things build. +// It helps test that imports are complete/ordered correctly. -option java_package = "com.google.protobuf"; -option java_outer_classname = "MultipleNameClashNano"; -option java_multiple_files = true; +#import "GPBArray.h" -message MultipleNameClashNano { - optional int32 field = 1; -} + +// 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_1 = 0; diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_enum_class_nano.proto b/objectivec/Tests/GPBCompileTest02.m index 3a1e07f6..c44e201a 100644 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_enum_class_nano.proto +++ b/objectivec/Tests/GPBCompileTest02.m @@ -28,21 +28,13 @@ // (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: maxtroy@google.com (Max Cai) -package protobuf_unittest; +// This is a test including a single public header to ensure things build. +// It helps test that imports are complete/ordered correctly. -option java_package = "com.google.protobuf"; -option java_outer_classname = "EnumClassNanos"; +#import "GPBCodedInputStream.h" -enum FileScopeEnum { - ONE = 1; -} -message EnumClassNano { - enum MessageScopeEnum { - TWO = 2; - } - optional FileScopeEnum one = 1 [ default = ONE ]; - optional MessageScopeEnum two = 2 [ default = TWO ]; -} +// 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_2 = 0; diff --git a/objectivec/Tests/GPBCompileTest03.m b/objectivec/Tests/GPBCompileTest03.m new file mode 100644 index 00000000..41994f94 --- /dev/null +++ b/objectivec/Tests/GPBCompileTest03.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 "GPBCodedOutputStream.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_3 = 0; diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_stringutf8_nano.proto b/objectivec/Tests/GPBCompileTest04.m index bbd677cf..c31498f1 100644 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_stringutf8_nano.proto +++ b/objectivec/Tests/GPBCompileTest04.m @@ -28,16 +28,13 @@ // (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: wink@google.com (Wink Saville) -// -package protobuf_unittest_import; +// This is a test including a single public header to ensure things build. +// It helps test that imports are complete/ordered correctly. + +#import "GPBDescriptor.h" -option java_package = "com.google.protobuf"; -// Explicit outer classname to suppress legacy info. -option java_outer_classname = "UnittestStringutf8Nano"; -message StringUtf8 { - optional string id = 1; - repeated string rs = 2; -} +// 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_4 = 0; diff --git a/objectivec/Tests/GPBCompileTest05.m b/objectivec/Tests/GPBCompileTest05.m new file mode 100644 index 00000000..adb72252 --- /dev/null +++ b/objectivec/Tests/GPBCompileTest05.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 "GPBDictionary.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_5 = 0; diff --git a/objectivec/Tests/GPBCompileTest06.m b/objectivec/Tests/GPBCompileTest06.m new file mode 100644 index 00000000..b7505b02 --- /dev/null +++ b/objectivec/Tests/GPBCompileTest06.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 "GPBExtensionRegistry.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_6 = 0; diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_single_nano.proto b/objectivec/Tests/GPBCompileTest07.m index 7de30c87..939bb709 100644 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_single_nano.proto +++ b/objectivec/Tests/GPBCompileTest07.m @@ -28,11 +28,13 @@ // (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: maxtroy@google.com (Max Cai) -package protobuf_unittest_import; +// This is a test including a single public header to ensure things build. +// It helps test that imports are complete/ordered correctly. -option java_package = "com.google.protobuf"; +#import "GPBMessage.h" -message SingleMessageNano { -} + +// 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_7 = 0; diff --git a/objectivec/Tests/GPBCompileTest08.m b/objectivec/Tests/GPBCompileTest08.m new file mode 100644 index 00000000..a84f38cf --- /dev/null +++ b/objectivec/Tests/GPBCompileTest08.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 "GPBRootObject.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_8 = 0; diff --git a/objectivec/Tests/GPBCompileTest09.m b/objectivec/Tests/GPBCompileTest09.m new file mode 100644 index 00000000..f8ccb4a0 --- /dev/null +++ b/objectivec/Tests/GPBCompileTest09.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 "GPBUnknownField.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_9 = 0; diff --git a/objectivec/Tests/GPBCompileTest10.m b/objectivec/Tests/GPBCompileTest10.m new file mode 100644 index 00000000..d8318678 --- /dev/null +++ b/objectivec/Tests/GPBCompileTest10.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 "GPBUnknownFieldSet.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_10 = 0; diff --git a/objectivec/Tests/GPBCompileTest11.m b/objectivec/Tests/GPBCompileTest11.m new file mode 100644 index 00000000..9f2c6b11 --- /dev/null +++ b/objectivec/Tests/GPBCompileTest11.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 "GPBUtilities.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_11 = 0; diff --git a/objectivec/Tests/GPBCompileTest12.m b/objectivec/Tests/GPBCompileTest12.m new file mode 100644 index 00000000..3aa29b31 --- /dev/null +++ b/objectivec/Tests/GPBCompileTest12.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 "GPBWellKnownTypes.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_12 = 0; diff --git a/objectivec/Tests/GPBCompileTest13.m b/objectivec/Tests/GPBCompileTest13.m new file mode 100644 index 00000000..fef2af5f --- /dev/null +++ b/objectivec/Tests/GPBCompileTest13.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 "GPBWireFormat.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_13 = 0; diff --git a/objectivec/Tests/GPBCompileTest14.m b/objectivec/Tests/GPBCompileTest14.m new file mode 100644 index 00000000..ae04349a --- /dev/null +++ b/objectivec/Tests/GPBCompileTest14.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 "google/protobuf/Any.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_14 = 0; diff --git a/objectivec/Tests/GPBCompileTest15.m b/objectivec/Tests/GPBCompileTest15.m new file mode 100644 index 00000000..889243aa --- /dev/null +++ b/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 "google/protobuf/Api.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/objectivec/Tests/GPBCompileTest16.m b/objectivec/Tests/GPBCompileTest16.m new file mode 100644 index 00000000..c5aaf14f --- /dev/null +++ b/objectivec/Tests/GPBCompileTest16.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 "google/protobuf/Duration.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_16 = 0; diff --git a/objectivec/Tests/GPBCompileTest17.m b/objectivec/Tests/GPBCompileTest17.m new file mode 100644 index 00000000..feb64d66 --- /dev/null +++ b/objectivec/Tests/GPBCompileTest17.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 "google/protobuf/Empty.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_17 = 0; diff --git a/objectivec/Tests/GPBCompileTest18.m b/objectivec/Tests/GPBCompileTest18.m new file mode 100644 index 00000000..66784c4f --- /dev/null +++ b/objectivec/Tests/GPBCompileTest18.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 "google/protobuf/FieldMask.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_18 = 0; diff --git a/objectivec/Tests/GPBCompileTest19.m b/objectivec/Tests/GPBCompileTest19.m new file mode 100644 index 00000000..435dea01 --- /dev/null +++ b/objectivec/Tests/GPBCompileTest19.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 "google/protobuf/SourceContext.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_19 = 0; diff --git a/objectivec/Tests/GPBCompileTest20.m b/objectivec/Tests/GPBCompileTest20.m new file mode 100644 index 00000000..c2da8066 --- /dev/null +++ b/objectivec/Tests/GPBCompileTest20.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 "google/protobuf/Struct.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_20 = 0; diff --git a/objectivec/Tests/GPBCompileTest21.m b/objectivec/Tests/GPBCompileTest21.m new file mode 100644 index 00000000..d7110b93 --- /dev/null +++ b/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 "google/protobuf/Timestamp.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/objectivec/Tests/GPBCompileTest22.m b/objectivec/Tests/GPBCompileTest22.m new file mode 100644 index 00000000..17380618 --- /dev/null +++ b/objectivec/Tests/GPBCompileTest22.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 "google/protobuf/Type.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_22 = 0; diff --git a/objectivec/Tests/GPBCompileTest23.m b/objectivec/Tests/GPBCompileTest23.m new file mode 100644 index 00000000..f22f9bdd --- /dev/null +++ b/objectivec/Tests/GPBCompileTest23.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 "google/protobuf/Wrappers.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_23 = 0; diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_merge_nano.proto b/objectivec/Tests/GPBCompileTest24.m index ef4e2d2f..c81ea732 100644 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_repeated_merge_nano.proto +++ b/objectivec/Tests/GPBCompileTest24.m @@ -28,20 +28,15 @@ // (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: maxtroy@google.com (Max Cai) -package protobuf_unittest; +// This is a test including a single header to ensure things build. This +// is NOT a public header of the library, but uses a file that defines +// proto2 syntax messages that are extendable, so it can need more things +// that the proto3 syntax WKTs bundled with the library. -import "google/protobuf/nano/unittest_nano.proto"; +#import "google/protobuf/Descriptor.pbobjc.h" -option java_package = "com.google.protobuf"; -option java_multiple_files = true; -// A container message for testing the merging of repeated fields at a -// nested level. Other tests will be done using the repeated fields in -// TestAllTypesNano. -message TestRepeatedMergeNano { - - optional TestAllTypesNano contained = 1; - -} +// 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_24 = 0; diff --git a/javanano/src/test/java/com/google/protobuf/nano/unittest_enum_class_multiple_nano.proto b/objectivec/Tests/GPBCompileTest25.m index 958e1f17..7a482b51 100644 --- a/javanano/src/test/java/com/google/protobuf/nano/unittest_enum_class_multiple_nano.proto +++ b/objectivec/Tests/GPBCompileTest25.m @@ -28,21 +28,15 @@ // (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: maxtroy@google.com (Max Cai) -package protobuf_unittest; +// This is a test including a single header to ensure things build. This +// is NOT a public header of the library, but uses a file that defines +// extensions to proto2 syntax messages, so it can need more things +// that the proto3 syntax WKTs bundled with the library. -option java_package = "com.google.protobuf"; -option java_multiple_files = true; +#import "google/protobuf/UnittestCustomOptions.pbobjc.h" -enum FileScopeEnumMultiple { - THREE = 3; -} -message EnumClassNanoMultiple { - enum MessageScopeEnumMultiple { - FOUR = 4; - } - optional FileScopeEnumMultiple three = 3 [ default = THREE ]; - optional MessageScopeEnumMultiple four = 4 [ default = FOUR ]; -} +// 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_25 = 0; diff --git a/objectivec/google/protobuf/Any.pbobjc.h b/objectivec/google/protobuf/Any.pbobjc.h index 89c99bdb..ad261898 100644 --- a/objectivec/google/protobuf/Any.pbobjc.h +++ b/objectivec/google/protobuf/Any.pbobjc.h @@ -8,9 +8,13 @@ #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS - #import <Protobuf/GPBProtocolBuffers.h> + #import <Protobuf/GPBDescriptor.h> + #import <Protobuf/GPBMessage.h> + #import <Protobuf/GPBRootObject.h> #else - #import "GPBProtocolBuffers.h" + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 diff --git a/objectivec/google/protobuf/Api.pbobjc.h b/objectivec/google/protobuf/Api.pbobjc.h index 095fc2cd..c93f3f15 100644 --- a/objectivec/google/protobuf/Api.pbobjc.h +++ b/objectivec/google/protobuf/Api.pbobjc.h @@ -8,9 +8,13 @@ #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS - #import <Protobuf/GPBProtocolBuffers.h> + #import <Protobuf/GPBDescriptor.h> + #import <Protobuf/GPBMessage.h> + #import <Protobuf/GPBRootObject.h> #else - #import "GPBProtocolBuffers.h" + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 diff --git a/objectivec/google/protobuf/Duration.pbobjc.h b/objectivec/google/protobuf/Duration.pbobjc.h index d9a388ac..3e367590 100644 --- a/objectivec/google/protobuf/Duration.pbobjc.h +++ b/objectivec/google/protobuf/Duration.pbobjc.h @@ -8,9 +8,13 @@ #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS - #import <Protobuf/GPBProtocolBuffers.h> + #import <Protobuf/GPBDescriptor.h> + #import <Protobuf/GPBMessage.h> + #import <Protobuf/GPBRootObject.h> #else - #import "GPBProtocolBuffers.h" + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 diff --git a/objectivec/google/protobuf/Empty.pbobjc.h b/objectivec/google/protobuf/Empty.pbobjc.h index bd49cfdb..fdc247ae 100644 --- a/objectivec/google/protobuf/Empty.pbobjc.h +++ b/objectivec/google/protobuf/Empty.pbobjc.h @@ -8,9 +8,13 @@ #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS - #import <Protobuf/GPBProtocolBuffers.h> + #import <Protobuf/GPBDescriptor.h> + #import <Protobuf/GPBMessage.h> + #import <Protobuf/GPBRootObject.h> #else - #import "GPBProtocolBuffers.h" + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 diff --git a/objectivec/google/protobuf/FieldMask.pbobjc.h b/objectivec/google/protobuf/FieldMask.pbobjc.h index 74aa8568..73296d57 100644 --- a/objectivec/google/protobuf/FieldMask.pbobjc.h +++ b/objectivec/google/protobuf/FieldMask.pbobjc.h @@ -8,9 +8,13 @@ #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS - #import <Protobuf/GPBProtocolBuffers.h> + #import <Protobuf/GPBDescriptor.h> + #import <Protobuf/GPBMessage.h> + #import <Protobuf/GPBRootObject.h> #else - #import "GPBProtocolBuffers.h" + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 diff --git a/objectivec/google/protobuf/SourceContext.pbobjc.h b/objectivec/google/protobuf/SourceContext.pbobjc.h index 799d190a..e4923959 100644 --- a/objectivec/google/protobuf/SourceContext.pbobjc.h +++ b/objectivec/google/protobuf/SourceContext.pbobjc.h @@ -8,9 +8,13 @@ #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS - #import <Protobuf/GPBProtocolBuffers.h> + #import <Protobuf/GPBDescriptor.h> + #import <Protobuf/GPBMessage.h> + #import <Protobuf/GPBRootObject.h> #else - #import "GPBProtocolBuffers.h" + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 diff --git a/objectivec/google/protobuf/Struct.pbobjc.h b/objectivec/google/protobuf/Struct.pbobjc.h index 3fc80caa..fb204251 100644 --- a/objectivec/google/protobuf/Struct.pbobjc.h +++ b/objectivec/google/protobuf/Struct.pbobjc.h @@ -8,9 +8,13 @@ #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS - #import <Protobuf/GPBProtocolBuffers.h> + #import <Protobuf/GPBDescriptor.h> + #import <Protobuf/GPBMessage.h> + #import <Protobuf/GPBRootObject.h> #else - #import "GPBProtocolBuffers.h" + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 diff --git a/objectivec/google/protobuf/Timestamp.pbobjc.h b/objectivec/google/protobuf/Timestamp.pbobjc.h index 7e65b15b..2c4b8b20 100644 --- a/objectivec/google/protobuf/Timestamp.pbobjc.h +++ b/objectivec/google/protobuf/Timestamp.pbobjc.h @@ -8,9 +8,13 @@ #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS - #import <Protobuf/GPBProtocolBuffers.h> + #import <Protobuf/GPBDescriptor.h> + #import <Protobuf/GPBMessage.h> + #import <Protobuf/GPBRootObject.h> #else - #import "GPBProtocolBuffers.h" + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 diff --git a/objectivec/google/protobuf/Type.pbobjc.h b/objectivec/google/protobuf/Type.pbobjc.h index 17986970..e14d15df 100644 --- a/objectivec/google/protobuf/Type.pbobjc.h +++ b/objectivec/google/protobuf/Type.pbobjc.h @@ -8,9 +8,13 @@ #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS - #import <Protobuf/GPBProtocolBuffers.h> + #import <Protobuf/GPBDescriptor.h> + #import <Protobuf/GPBMessage.h> + #import <Protobuf/GPBRootObject.h> #else - #import "GPBProtocolBuffers.h" + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 diff --git a/objectivec/google/protobuf/Wrappers.pbobjc.h b/objectivec/google/protobuf/Wrappers.pbobjc.h index 3cb9fe77..0411e1ec 100644 --- a/objectivec/google/protobuf/Wrappers.pbobjc.h +++ b/objectivec/google/protobuf/Wrappers.pbobjc.h @@ -8,9 +8,13 @@ #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS - #import <Protobuf/GPBProtocolBuffers.h> + #import <Protobuf/GPBDescriptor.h> + #import <Protobuf/GPBMessage.h> + #import <Protobuf/GPBRootObject.h> #else - #import "GPBProtocolBuffers.h" + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 diff --git a/php/ext/google/protobuf/package.xml b/php/ext/google/protobuf/package.xml index 626eb46b..3a556acf 100644 --- a/php/ext/google/protobuf/package.xml +++ b/php/ext/google/protobuf/package.xml @@ -10,11 +10,11 @@ <email>protobuf-opensource@google.com</email> <active>yes</active> </lead> - <date>2017-12-11</date> + <date>2018-03-06</date> <time>11:02:07</time> <version> - <release>3.5.1</release> - <api>3.5.1</api> + <release>3.5.2</release> + <api>3.5.2</api> </version> <stability> <release>stable</release> @@ -216,5 +216,21 @@ GA release. GA release. </notes> </release> + <release> + <version> + <release>3.5.2</release> + <api>3.5.2</api> + </version> + <stability> + <release>stable</release> + <api>stable</api> + </stability> + <date>2018-03-06</date> + <time>11:02:07</time> + <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license> + <notes> +G A release. + </notes> + </release> </changelog> </package> diff --git a/php/ext/google/protobuf/protobuf.h b/php/ext/google/protobuf/protobuf.h index be1de5cf..c15bde2d 100644 --- a/php/ext/google/protobuf/protobuf.h +++ b/php/ext/google/protobuf/protobuf.h @@ -37,7 +37,7 @@ #include "upb.h" #define PHP_PROTOBUF_EXTNAME "protobuf" -#define PHP_PROTOBUF_VERSION "3.5.1" +#define PHP_PROTOBUF_VERSION "3.5.2" #define MAX_LENGTH_OF_INT64 20 #define SIZEOF_INT64 8 diff --git a/php/src/Google/Protobuf/Internal/GPBUtil.php b/php/src/Google/Protobuf/Internal/GPBUtil.php index 76f84cbd..05d5c393 100644 --- a/php/src/Google/Protobuf/Internal/GPBUtil.php +++ b/php/src/Google/Protobuf/Internal/GPBUtil.php @@ -194,7 +194,7 @@ class GPBUtil public static function checkMessage(&$var, $klass) { if (!$var instanceof $klass && !is_null($var)) { - throw new \Exception("Expect message."); + throw new \Exception("Expect $klass."); } } diff --git a/php/src/Google/Protobuf/Internal/Message.php b/php/src/Google/Protobuf/Internal/Message.php index b7f83c57..04ee1c34 100644 --- a/php/src/Google/Protobuf/Internal/Message.php +++ b/php/src/Google/Protobuf/Internal/Message.php @@ -1104,7 +1104,7 @@ class Message */ public function parseFromJsonStream($input) { - $array = json_decode($input->getData(), JSON_BIGINT_AS_STRING); + $array = json_decode($input->getData(), true, 512, JSON_BIGINT_AS_STRING); if (is_null($array)) { throw new GPBDecodeException( "Cannot decode json string."); diff --git a/protoc-artifacts/Dockerfile b/protoc-artifacts/Dockerfile index 43e6863c..c346586b 100644 --- a/protoc-artifacts/Dockerfile +++ b/protoc-artifacts/Dockerfile @@ -11,7 +11,9 @@ RUN yum install -y git \ libtool \ glibc-static.i686 \ glibc-devel \ - glibc-devel.i686 + glibc-devel.i686 \ + && \ + yum clean all # Install Java 8 RUN wget -q --no-cookies --no-check-certificate \ @@ -27,15 +29,17 @@ RUN wget -q http://apache.cs.utah.edu/maven/maven-3/3.3.9/binaries/apache-maven- ENV PATH /var/local/apache-maven-3.3.9/bin:$PATH # Install GCC 4.7 to support -static-libstdc++ -RUN wget http://people.centos.org/tru/devtools-1.1/devtools-1.1.repo -P /etc/yum.repos.d -RUN bash -c 'echo "enabled=1" >> /etc/yum.repos.d/devtools-1.1.repo' -RUN bash -c "sed -e 's/\$basearch/i386/g' /etc/yum.repos.d/devtools-1.1.repo > /etc/yum.repos.d/devtools-i386-1.1.repo" -RUN sed -e 's/testing-/testing-i386-/g' -i /etc/yum.repos.d/devtools-i386-1.1.repo -RUN rpm --rebuilddb && yum install -y devtoolset-1.1 \ +RUN wget http://people.centos.org/tru/devtools-1.1/devtools-1.1.repo -P /etc/yum.repos.d && \ + bash -c 'echo "enabled=1" >> /etc/yum.repos.d/devtools-1.1.repo' && \ + bash -c "sed -e 's/\$basearch/i386/g' /etc/yum.repos.d/devtools-1.1.repo > /etc/yum.repos.d/devtools-i386-1.1.repo" && \ + sed -e 's/testing-/testing-i386-/g' -i /etc/yum.repos.d/devtools-i386-1.1.repo && \ + rpm --rebuilddb && \ + yum install -y devtoolset-1.1 \ devtoolset-1.1-libstdc++-devel \ - devtoolset-1.1-libstdc++-devel.i686 + devtoolset-1.1-libstdc++-devel.i686 && \ + yum clean all -RUN git clone --depth 1 https://github.com/google/protobuf.git +COPY scl-enable-devtoolset.sh /var/local/ # Start in devtoolset environment that uses GCC 4.7 -CMD ["scl", "enable", "devtoolset-1.1", "bash"] +ENTRYPOINT ["/var/local/scl-enable-devtoolset.sh"] diff --git a/protoc-artifacts/README.md b/protoc-artifacts/README.md index ba3ca018..dcaec987 100644 --- a/protoc-artifacts/README.md +++ b/protoc-artifacts/README.md @@ -140,10 +140,14 @@ $ docker build -t protoc-artifacts . To run the image: ``` -$ docker run -it --rm=true protoc-artifacts +$ docker run -it --rm=true protoc-artifacts bash ``` -The Protobuf repository has been cloned into ``/protobuf``. +To checkout protobuf (run within the container): +``` +$ # Replace v3.5.1 with the version you want +$ wget -O - https://github.com/google/protobuf/archive/v3.5.1.tar.gz | tar xvzp +``` ### Tips for deploying on Windows Under Windows the following error may occur: ``gpg: cannot open tty `no tty': diff --git a/protoc-artifacts/build-protoc.sh b/protoc-artifacts/build-protoc.sh index fe1dec24..b78abbcf 100755 --- a/protoc-artifacts/build-protoc.sh +++ b/protoc-artifacts/build-protoc.sh @@ -81,6 +81,8 @@ checkArch () assertEq $format "elf64-x86-64" $LINENO elif [[ "$ARCH" == aarch_64 ]]; then assertEq $format "elf64-little" $LINENO + elif [[ "$ARCH" == ppcle_64 ]]; then + assertEq $format "elf64-powerpcle" $LINENO else fail "Unsupported arch: $ARCH" fi @@ -124,6 +126,8 @@ checkDependencies () white_list="linux-gate\.so\.1\|libpthread\.so\.0\|libm\.so\.6\|libc\.so\.6\|ld-linux\.so\.2" elif [[ "$ARCH" == x86_64 ]]; then white_list="linux-vdso\.so\.1\|libpthread\.so\.0\|libm\.so\.6\|libc\.so\.6\|ld-linux-x86-64\.so\.2" + elif [[ "$ARCH" == ppcle_64 ]]; then + white_list="linux-vdso64\.so\.1\|libpthread\.so\.0\|libm\.so\.6\|libc\.so\.6\|libz\.so\.1\|ld64\.so\.2" elif [[ "$ARCH" == aarch_64 ]]; then dump_cmd='objdump -p '"$1"' | grep NEEDED' white_list="libpthread\.so\.0\|libc\.so\.6\|ld-linux-aarch64\.so\.1" @@ -193,6 +197,8 @@ elif [[ "$(uname)" == Linux* ]]; then CXXFLAGS="$CXXFLAGS -m32" elif [[ "$ARCH" == aarch_64 ]]; then CONFIGURE_ARGS="$CONFIGURE_ARGS --host=aarch64-linux-gnu" + elif [[ "$ARCH" == ppcle_64 ]]; then + CXXFLAGS="$CXXFLAGS -m64" else fail "Unsupported arch: $ARCH" fi diff --git a/protoc-artifacts/build-zip.sh b/protoc-artifacts/build-zip.sh index f08e2758..26b6cc93 100755 --- a/protoc-artifacts/build-zip.sh +++ b/protoc-artifacts/build-zip.sh @@ -13,13 +13,14 @@ Example: This script will download pre-built protoc or protoc plugin binaries from maven repository and create .zip packages suitable to be included in the github release page. If the target is protoc, well-known type .proto files will also be -included. Each invocation will create 6 zip packages: +included. Each invocation will create 7 zip packages: dist/<TARGET>-<VERSION_NUMBER>-win32.zip dist/<TARGET>-<VERSION_NUMBER>-osx-x86_32.zip dist/<TARGET>-<VERSION_NUMBER>-osx-x86_64.zip dist/<TARGET>-<VERSION_NUMBER>-linux-x86_32.zip dist/<TARGET>-<VERSION_NUMBER>-linux-x86_64.zip dist/<TARGET>-<VERSION_NUMBER>-linux-aarch_64.zip + dist/<TARGET>-<VERSION_NUMBER>-linux-ppcle_64.zip EOF exit 1 fi @@ -35,6 +36,7 @@ declare -a FILE_NAMES=( \ linux-x86_32.zip linux-x86_32.exe \ linux-x86_64.zip linux-x86_64.exe \ linux-aarch_64.zip linux-aarch_64.exe \ + linux-ppcle_64.zip linux-ppcle_64.exe \ ) # List of all well-known types to be included. diff --git a/protoc-artifacts/pom.xml b/protoc-artifacts/pom.xml index 90323531..298730a6 100644 --- a/protoc-artifacts/pom.xml +++ b/protoc-artifacts/pom.xml @@ -10,7 +10,7 @@ </parent> <groupId>com.google.protobuf</groupId> <artifactId>protoc</artifactId> - <version>3.5.1-1</version> + <version>3.5.2</version> <packaging>pom</packaging> <name>Protobuf Compiler</name> <description> @@ -37,7 +37,7 @@ <extension> <groupId>kr.motd.maven</groupId> <artifactId>os-maven-plugin</artifactId> - <version>1.2.3.Final</version> + <version>1.5.0.Final</version> </extension> </extensions> <plugins> diff --git a/protoc-artifacts/scl-enable-devtoolset.sh b/protoc-artifacts/scl-enable-devtoolset.sh new file mode 100755 index 00000000..8d9585ea --- /dev/null +++ b/protoc-artifacts/scl-enable-devtoolset.sh @@ -0,0 +1,13 @@ +#!/bin/bash +set -eu -o pipefail + +quote() { + local arg + for arg in "$@"; do + printf "'" + printf "%s" "$arg" | sed -e "s/'/'\\\\''/g" + printf "' " + done +} + +exec scl enable devtoolset-1.1 "$(quote "$@")" diff --git a/python/google/protobuf/__init__.py b/python/google/protobuf/__init__.py index 950f9b2d..d4360727 100755 --- a/python/google/protobuf/__init__.py +++ b/python/google/protobuf/__init__.py @@ -30,7 +30,7 @@ # Copyright 2007 Google Inc. All Rights Reserved. -__version__ = '3.5.1' +__version__ = '3.5.2' if __name__ != '__main__': try: diff --git a/python/google/protobuf/compiler/__init__.py b/python/google/protobuf/compiler/__init__.py new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/python/google/protobuf/compiler/__init__.py diff --git a/python/google/protobuf/util/__init__.py b/python/google/protobuf/util/__init__.py new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/python/google/protobuf/util/__init__.py diff --git a/python/setup.py b/python/setup.py index 6f5315f7..bdae6913 100755 --- a/python/setup.py +++ b/python/setup.py @@ -120,9 +120,7 @@ class clean(_clean): 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") or \ - filepath.endswith('google/protobuf/compiler/__init__.py') or \ - filepath.endswith('google/protobuf/util/__init__.py'): + filepath.endswith(".so") or filepath.endswith(".o"): os.remove(filepath) # _clean is an old-style class, so super() doesn't work. _clean.run(self) @@ -144,12 +142,6 @@ class build_py(_build_py): generate_proto("../src/google/protobuf/wrappers.proto") GenerateUnittestProtos() - # Make sure google.protobuf/** are valid packages. - for path in ['', 'internal/', 'compiler/', 'pyext/', 'util/']: - try: - open('google/protobuf/%s__init__.py' % path, 'a').close() - except EnvironmentError: - pass # _build_py is an old-style class, so super() doesn't work. _build_py.run(self) @@ -179,9 +171,6 @@ if __name__ == '__main__': # 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') - extra_compile_args = ['-Wno-write-strings', - '-Wno-invalid-offsetof', - '-Wno-sign-compare'] libraries = ['protobuf'] extra_objects = None if compile_static_ext: @@ -190,6 +179,25 @@ if __name__ == '__main__': '../src/.libs/libprotobuf-lite.a'] test_conformance.target = 'test_python_cpp' + extra_compile_args = [] + + 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') + + # 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') @@ -217,7 +225,7 @@ if __name__ == '__main__': Extension( "google.protobuf.internal._api_implementation", glob.glob('google/protobuf/internal/api_implementation.cc'), - extra_compile_args=['-DPYTHON_PROTO2_CPP_IMPL_V2'], + extra_compile_args=extra_compile_args + ['-DPYTHON_PROTO2_CPP_IMPL_V2'], ), ]) os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'cpp' diff --git a/ruby/google-protobuf.gemspec b/ruby/google-protobuf.gemspec index 8fcf85c7..c09a7f24 100644 --- a/ruby/google-protobuf.gemspec +++ b/ruby/google-protobuf.gemspec @@ -1,6 +1,6 @@ Gem::Specification.new do |s| s.name = "google-protobuf" - s.version = "3.5.1.2" + s.version = "3.5.2" s.licenses = ["BSD-3-Clause"] s.summary = "Protocol Buffers" s.description = "Protocol Buffers are Google's data interchange format." diff --git a/src/Makefile.am b/src/Makefile.am index b8c13274..7310210e 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -81,7 +81,6 @@ nobase_include_HEADERS = \ google/protobuf/stubs/stl_util.h \ google/protobuf/stubs/stringpiece.h \ google/protobuf/stubs/template_util.h \ - google/protobuf/stubs/type_traits.h \ google/protobuf/any.pb.h \ google/protobuf/api.pb.h \ google/protobuf/any.h \ @@ -148,7 +147,6 @@ nobase_include_HEADERS = \ google/protobuf/compiler/csharp/csharp_names.h \ google/protobuf/compiler/java/java_generator.h \ google/protobuf/compiler/java/java_names.h \ - google/protobuf/compiler/javanano/javanano_generator.h \ google/protobuf/compiler/js/js_generator.h \ google/protobuf/compiler/js/well_known_types_embed.h \ google/protobuf/compiler/objectivec/objectivec_generator.h \ @@ -410,29 +408,6 @@ libprotoc_la_SOURCES = \ google/protobuf/compiler/java/java_doc_comment.h \ google/protobuf/compiler/js/js_generator.cc \ google/protobuf/compiler/js/well_known_types_embed.cc \ - google/protobuf/compiler/javanano/javanano_enum.cc \ - google/protobuf/compiler/javanano/javanano_enum.h \ - google/protobuf/compiler/javanano/javanano_enum_field.cc \ - google/protobuf/compiler/javanano/javanano_enum_field.h \ - google/protobuf/compiler/javanano/javanano_extension.cc \ - google/protobuf/compiler/javanano/javanano_extension.h \ - google/protobuf/compiler/javanano/javanano_field.cc \ - google/protobuf/compiler/javanano/javanano_field.h \ - google/protobuf/compiler/javanano/javanano_file.cc \ - google/protobuf/compiler/javanano/javanano_file.h \ - google/protobuf/compiler/javanano/javanano_generator.cc \ - google/protobuf/compiler/javanano/javanano_generator.h \ - google/protobuf/compiler/javanano/javanano_helpers.cc \ - google/protobuf/compiler/javanano/javanano_helpers.h \ - google/protobuf/compiler/javanano/javanano_map_field.cc \ - google/protobuf/compiler/javanano/javanano_map_field.h \ - google/protobuf/compiler/javanano/javanano_message.cc \ - google/protobuf/compiler/javanano/javanano_message.h \ - google/protobuf/compiler/javanano/javanano_message_field.cc \ - google/protobuf/compiler/javanano/javanano_message_field.h \ - google/protobuf/compiler/javanano/javanano_params.h \ - google/protobuf/compiler/javanano/javanano_primitive_field.cc \ - google/protobuf/compiler/javanano/javanano_primitive_field.h \ google/protobuf/compiler/objectivec/objectivec_enum.cc \ google/protobuf/compiler/objectivec/objectivec_enum.h \ google/protobuf/compiler/objectivec/objectivec_enum_field.cc \ @@ -736,15 +711,19 @@ COMMON_TEST_SOURCES = \ google/protobuf/testing/file.cc \ google/protobuf/testing/file.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 \ - ../gmock/gtest/lib/libgtest.la \ - ../gmock/lib/libgmock.la \ - ../gmock/lib/libgmock_main.la -protobuf_test_CPPFLAGS = -I$(srcdir)/../gmock/gtest/include \ - -I$(srcdir)/../gmock/include + $(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. @@ -762,7 +741,6 @@ protobuf_test_SOURCES = \ google/protobuf/stubs/strutil_unittest.cc \ google/protobuf/stubs/template_util_unittest.cc \ google/protobuf/stubs/time_test.cc \ - google/protobuf/stubs/type_traits_unittest.cc \ google/protobuf/any_test.cc \ google/protobuf/arenastring_unittest.cc \ google/protobuf/arena_unittest.cc \ @@ -833,11 +811,11 @@ $(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 \ - ../gmock/gtest/lib/libgtest.la \ - ../gmock/lib/libgmock.la \ - ../gmock/lib/libgmock_main.la -protobuf_lazy_descriptor_test_CPPFLAGS = -I$(srcdir)/../gmock/include \ - -I$(srcdir)/../gmock/gtest/include \ + $(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 = \ @@ -858,12 +836,12 @@ COMMON_LITE_TEST_SOURCES = \ # 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 \ - ../gmock/gtest/lib/libgtest.la \ - ../gmock/lib/libgmock.la \ - ../gmock/lib/libgmock_main.la -protobuf_lite_test_CPPFLAGS= -I$(srcdir)/../gmock/include \ - -I$(srcdir)/../gmock/gtest/include +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 \ @@ -875,11 +853,11 @@ $(am_protobuf_lite_test_OBJECTS): unittest_proto_middleman # 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 \ - ../gmock/gtest/lib/libgtest.la \ - ../gmock/lib/libgmock.la \ - ../gmock/lib/libgmock_main.la -protobuf_lite_arena_test_CPPFLAGS = -I$(srcdir)/../gmock/include \ - -I$(srcdir)/../gmock/gtest/include + $(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 \ @@ -889,8 +867,8 @@ $(am_protobuf_lite_arena_test_OBJECTS): unittest_proto_middleman # Test plugin binary. test_plugin_LDADD = $(PTHREAD_LIBS) libprotobuf.la libprotoc.la \ - ../gmock/gtest/lib/libgtest.la -test_plugin_CPPFLAGS = -I$(srcdir)/../gmock/gtest/include + $(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/testing/file.cc \ diff --git a/src/README.md b/src/README.md index 3ae23fa6..3cbeb3e6 100644 --- a/src/README.md +++ b/src/README.md @@ -15,29 +15,35 @@ To build protobuf from source, the following tools are needed: * autoconf * automake * libtool - * curl (used to download gmock) * make * g++ * unzip -On Ubuntu, you can install them with: +On Ubuntu/Debian, you can install them with: $ sudo apt-get install autoconf automake libtool curl make g++ unzip On other platforms, please use the corresponding package managing tool to install them before proceeding. -If you get the source from github, you need to generate the configure script -first: +To get the source, download one of the release .tar.gz or .zip packages in the +release page: - $ ./autogen.sh + https://github.com/google/protobuf/releases/latest + +For example: if you only need C++, download `protobuf-cpp-[VERSION].tar.gz`; if +you need C++ and Java, download `protobuf-java-[VERSION].tar.gz` (every package +contains C++ source already); if you need C++ and multiple other languages, +download `protobuf-all-[VERSION].tar.gz`. -This will download gmock source (which is used for C++ Protocol Buffer -unit-tests) to the current directory and run automake, autoconf, etc. -to generate the configure script and various template makefiles. +You can also get the source by "git clone" our git repository. Make sure you +have also cloned the submodules and generated the configure script (skip this +if you are using a release .tar.gz or .zip package): -You can skip this step if you are using a release package (which already -contains gmock and the configure script). + $ git clone https://github.com/google/protobuf.git + $ cd protobuf + $ git submodule update --init --recursive + $ ./autogen.sh To build and install the C++ Protocol Buffer runtime and the Protocol Buffer compiler (protoc) execute the following: @@ -55,122 +61,122 @@ Proceed at your own risk. For advanced usage information on configure and make, please refer to the autoconf documentation: - http://www.gnu.org/software/autoconf/manual/autoconf.html#Running-configure-Scripts + http://www.gnu.org/software/autoconf/manual/autoconf.html#Running-configure-Scripts **Hint on install location** - By default, the package will be installed to /usr/local. However, - on many platforms, /usr/local/lib is not part of LD_LIBRARY_PATH. - You can add it, but it may be easier to just install to /usr - instead. To do this, invoke configure as follows: +By default, the package will be installed to /usr/local. However, +on many platforms, /usr/local/lib is not part of LD_LIBRARY_PATH. +You can add it, but it may be easier to just install to /usr +instead. To do this, invoke configure as follows: ./configure --prefix=/usr - If you already built the package with a different prefix, make sure - to run "make clean" before building again. +If you already built the package with a different prefix, make sure +to run "make clean" before building again. **Compiling dependent packages** - To compile a package that uses Protocol Buffers, you need to pass - various flags to your compiler and linker. As of version 2.2.0, - Protocol Buffers integrates with pkg-config to manage this. If you - have pkg-config installed, then you can invoke it to get a list of - flags like so: +To compile a package that uses Protocol Buffers, you need to pass +various flags to your compiler and linker. As of version 2.2.0, +Protocol Buffers integrates with pkg-config to manage this. If you +have pkg-config installed, then you can invoke it to get a list of +flags like so: pkg-config --cflags protobuf # print compiler flags pkg-config --libs protobuf # print linker flags pkg-config --cflags --libs protobuf # print both - For example: +For example: c++ my_program.cc my_proto.pb.cc `pkg-config --cflags --libs protobuf` - Note that packages written prior to the 2.2.0 release of Protocol - Buffers may not yet integrate with pkg-config to get flags, and may - not pass the correct set of flags to correctly link against - libprotobuf. If the package in question uses autoconf, you can - often fix the problem by invoking its configure script like: +Note that packages written prior to the 2.2.0 release of Protocol +Buffers may not yet integrate with pkg-config to get flags, and may +not pass the correct set of flags to correctly link against +libprotobuf. If the package in question uses autoconf, you can +often fix the problem by invoking its configure script like: configure CXXFLAGS="$(pkg-config --cflags protobuf)" \ LIBS="$(pkg-config --libs protobuf)" - This will force it to use the correct flags. +This will force it to use the correct flags. - If you are writing an autoconf-based package that uses Protocol - Buffers, you should probably use the PKG_CHECK_MODULES macro in your - configure script like: +If you are writing an autoconf-based package that uses Protocol +Buffers, you should probably use the PKG_CHECK_MODULES macro in your +configure script like: PKG_CHECK_MODULES([protobuf], [protobuf]) - See the pkg-config man page for more info. +See the pkg-config man page for more info. - If you only want protobuf-lite, substitute "protobuf-lite" in place - of "protobuf" in these examples. +If you only want protobuf-lite, substitute "protobuf-lite" in place +of "protobuf" in these examples. **Note for Mac users** - For a Mac system, Unix tools are not available by default. You will first need - to install Xcode from the Mac AppStore and then run the following command from - a terminal: +For a Mac system, Unix tools are not available by default. You will first need +to install Xcode from the Mac AppStore and then run the following command from +a terminal: $ sudo xcode-select --install - To install Unix tools, you can install "port" following the instructions at - https://www.macports.org . This will reside in /opt/local/bin/port for most - Mac installations. +To install Unix tools, you can install "port" following the instructions at +https://www.macports.org . This will reside in /opt/local/bin/port for most +Mac installations. $ sudo /opt/local/bin/port install autoconf automake libtool - Then follow the Unix instructions above. +Then follow the Unix instructions above. **Note for cross-compiling** - The makefiles normally invoke the protoc executable that they just - built in order to build tests. When cross-compiling, the protoc - executable may not be executable on the host machine. In this case, - you must build a copy of protoc for the host machine first, then use - the --with-protoc option to tell configure to use it instead. For - example: +The makefiles normally invoke the protoc executable that they just +built in order to build tests. When cross-compiling, the protoc +executable may not be executable on the host machine. In this case, +you must build a copy of protoc for the host machine first, then use +the --with-protoc option to tell configure to use it instead. For +example: ./configure --with-protoc=protoc - This will use the installed protoc (found in your $PATH) instead of - trying to execute the one built during the build process. You can - also use an executable that hasn't been installed. For example, if - you built the protobuf package for your host machine in ../host, - you might do: +This will use the installed protoc (found in your $PATH) instead of +trying to execute the one built during the build process. You can +also use an executable that hasn't been installed. For example, if +you built the protobuf package for your host machine in ../host, +you might do: ./configure --with-protoc=../host/src/protoc - Either way, you must make sure that the protoc executable you use - has the same version as the protobuf source code you are trying to - use it with. +Either way, you must make sure that the protoc executable you use +has the same version as the protobuf source code you are trying to +use it with. **Note for Solaris users** - Solaris 10 x86 has a bug that will make linking fail, complaining - about libstdc++.la being invalid. We have included a work-around - in this package. To use the work-around, run configure as follows: +Solaris 10 x86 has a bug that will make linking fail, complaining +about libstdc++.la being invalid. We have included a work-around +in this package. To use the work-around, run configure as follows: ./configure LDFLAGS=-L$PWD/src/solaris - See src/solaris/libstdc++.la for more info on this bug. +See src/solaris/libstdc++.la for more info on this bug. **Note for HP C++ Tru64 users** - To compile invoke configure as follows: +To compile invoke configure as follows: ./configure CXXFLAGS="-O -std ansi -ieee -D__USE_STD_IOSTREAM" - Also, you will need to use gmake instead of make. +Also, you will need to use gmake instead of make. **Note for AIX users** - Compile using the IBM xlC C++ compiler as follows: +Compile using the IBM xlC C++ compiler as follows: ./configure CXX=xlC - Also, you will need to use GNU `make` (`gmake`) instead of AIX `make`. +Also, you will need to use GNU `make` (`gmake`) instead of AIX `make`. C++ Installation - Windows -------------------------- @@ -178,7 +184,7 @@ C++ Installation - Windows If you only need the protoc binary, you can download it from the release page: - https://github.com/google/protobuf/releases + https://github.com/google/protobuf/releases/latest In the downloads section, download the zip file protoc-$VERSION-win32.zip. It contains the protoc binary as well as public proto files of protobuf diff --git a/src/google/protobuf/compiler/javanano/javanano_enum.cc b/src/google/protobuf/compiler/javanano/javanano_enum.cc deleted file mode 100644 index c6e8dfe9..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_enum.cc +++ /dev/null @@ -1,143 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include <map> -#include <string> - -#include <google/protobuf/compiler/javanano/javanano_params.h> -#include <google/protobuf/compiler/javanano/javanano_enum.h> -#include <google/protobuf/compiler/javanano/javanano_helpers.h> -#include <google/protobuf/io/printer.h> -#include <google/protobuf/descriptor.pb.h> -#include <google/protobuf/stubs/strutil.h> - -namespace google { -namespace protobuf { -namespace compiler { -namespace javanano { - -EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor, const Params& params) - : params_(params), descriptor_(descriptor) { - for (int i = 0; i < descriptor_->value_count(); i++) { - const EnumValueDescriptor* value = descriptor_->value(i); - const EnumValueDescriptor* canonical_value = - descriptor_->FindValueByNumber(value->number()); - - if (value == canonical_value) { - canonical_values_.push_back(value); - } else { - Alias alias; - alias.value = value; - alias.canonical_value = canonical_value; - aliases_.push_back(alias); - } - } -} - -EnumGenerator::~EnumGenerator() {} - -void EnumGenerator::Generate(io::Printer* printer) { - printer->Print( - "\n" - "// enum $classname$\n", - "classname", descriptor_->name()); - - const string classname = RenameJavaKeywords(descriptor_->name()); - - // Start of container interface - // If generating intdefs, we use the container interface as the intdef if - // present. Otherwise, we just make an empty @interface parallel to the - // constants. - bool use_intdef = params_.generate_intdefs(); - bool use_shell_class = params_.java_enum_style(); - if (use_intdef) { - // @IntDef annotation so tools can enforce correctness - // Annotations will be discarded by the compiler - printer->Print("@java.lang.annotation.Retention(" - "java.lang.annotation.RetentionPolicy.SOURCE)\n" - "@android.support.annotation.IntDef({\n"); - printer->Indent(); - for (int i = 0; i < canonical_values_.size(); i++) { - const string constant_name = - RenameJavaKeywords(canonical_values_[i]->name()); - if (use_shell_class) { - printer->Print("$classname$.$name$,\n", - "classname", classname, - "name", constant_name); - } else { - printer->Print("$name$,\n", "name", constant_name); - } - } - printer->Outdent(); - printer->Print("})\n"); - } - if (use_shell_class || use_intdef) { - printer->Print( - "public $at_for_intdef$interface $classname$ {\n", - "classname", classname, - "at_for_intdef", use_intdef ? "@" : ""); - if (use_shell_class) { - printer->Indent(); - } else { - printer->Print("}\n\n"); - } - } - - // Canonical values - for (int i = 0; i < canonical_values_.size(); i++) { - printer->Print( - "public static final int $name$ = $canonical_value$;\n", - "name", RenameJavaKeywords(canonical_values_[i]->name()), - "canonical_value", SimpleItoa(canonical_values_[i]->number())); - } - - // Aliases - for (int i = 0; i < aliases_.size(); i++) { - printer->Print( - "public static final int $name$ = $canonical_name$;\n", - "name", RenameJavaKeywords(aliases_[i].value->name()), - "canonical_name", RenameJavaKeywords(aliases_[i].canonical_value->name())); - } - - // End of container interface - if (use_shell_class) { - printer->Outdent(); - printer->Print("}\n"); - } -} - -} // namespace javanano -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/src/google/protobuf/compiler/javanano/javanano_enum.h b/src/google/protobuf/compiler/javanano/javanano_enum.h deleted file mode 100644 index 82e098fc..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_enum.h +++ /dev/null @@ -1,87 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_H__ - -#include <string> -#include <vector> - -#include <google/protobuf/compiler/javanano/javanano_params.h> -#include <google/protobuf/descriptor.h> - -namespace google { -namespace protobuf { - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace javanano { - -class EnumGenerator { - public: - explicit EnumGenerator(const EnumDescriptor* descriptor, const Params& params); - ~EnumGenerator(); - - void Generate(io::Printer* printer); - - private: - const Params& params_; - const EnumDescriptor* descriptor_; - - // The proto language allows multiple enum constants to have the same numeric - // value. Java, however, does not allow multiple enum constants to be - // considered equivalent. We treat the first defined constant for any - // given numeric value as "canonical" and the rest as aliases of that - // canonical value. - std::vector<const EnumValueDescriptor*> canonical_values_; - - struct Alias { - const EnumValueDescriptor* value; - const EnumValueDescriptor* canonical_value; - }; - std::vector<Alias> aliases_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator); -}; - -} // namespace javanano -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_H__ diff --git a/src/google/protobuf/compiler/javanano/javanano_enum_field.cc b/src/google/protobuf/compiler/javanano/javanano_enum_field.cc deleted file mode 100644 index ea67a810..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_enum_field.cc +++ /dev/null @@ -1,544 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include <map> -#include <string> - -#include <google/protobuf/compiler/javanano/javanano_enum_field.h> -#include <google/protobuf/stubs/common.h> -#include <google/protobuf/compiler/javanano/javanano_helpers.h> -#include <google/protobuf/io/printer.h> -#include <google/protobuf/wire_format.h> -#include <google/protobuf/stubs/strutil.h> - -namespace google { -namespace protobuf { -namespace compiler { -namespace javanano { - -namespace { - -// TODO(kenton): Factor out a "SetCommonFieldVariables()" to get rid of -// repeat code between this and the other field types. -void SetEnumVariables(const Params& params, - const FieldDescriptor* descriptor, std::map<string, string>* variables) { - (*variables)["name"] = - RenameJavaKeywords(UnderscoresToCamelCase(descriptor)); - (*variables)["capitalized_name"] = - RenameJavaKeywords(UnderscoresToCapitalizedCamelCase(descriptor)); - (*variables)["number"] = SimpleItoa(descriptor->number()); - if (params.use_reference_types_for_primitives() - && !params.reftypes_primitive_enums() - && !descriptor->is_repeated()) { - (*variables)["type"] = "java.lang.Integer"; - (*variables)["default"] = "null"; - } else { - (*variables)["type"] = "int"; - (*variables)["default"] = DefaultValue(params, descriptor); - } - (*variables)["repeated_default"] = - "com.google.protobuf.nano.WireFormatNano.EMPTY_INT_ARRAY"; - (*variables)["tag"] = SimpleItoa(internal::WireFormat::MakeTag(descriptor)); - (*variables)["tag_size"] = SimpleItoa( - internal::WireFormat::TagSize(descriptor->number(), descriptor->type())); - (*variables)["non_packed_tag"] = SimpleItoa( - internal::WireFormatLite::MakeTag(descriptor->number(), - internal::WireFormat::WireTypeForFieldType(descriptor->type()))); - (*variables)["message_name"] = descriptor->containing_type()->name(); - const EnumDescriptor* enum_type = descriptor->enum_type(); - (*variables)["message_type_intdef"] = "@" - + ToJavaName(params, enum_type->name(), true, - enum_type->containing_type(), enum_type->file()); -} - -void LoadEnumValues(const Params& params, - const EnumDescriptor* enum_descriptor, std::vector<string>* canonical_values) { - string enum_class_name = ClassName(params, enum_descriptor); - for (int i = 0; i < enum_descriptor->value_count(); i++) { - const EnumValueDescriptor* value = enum_descriptor->value(i); - const EnumValueDescriptor* canonical_value = - enum_descriptor->FindValueByNumber(value->number()); - if (value == canonical_value) { - canonical_values->push_back( - enum_class_name + "." + RenameJavaKeywords(value->name())); - } - } -} - -void PrintCaseLabels( - io::Printer* printer, const std::vector<string>& canonical_values) { - for (int i = 0; i < canonical_values.size(); i++) { - printer->Print( - " case $value$:\n", - "value", canonical_values[i]); - } -} - -} // namespace - -// =================================================================== - -EnumFieldGenerator:: -EnumFieldGenerator(const FieldDescriptor* descriptor, const Params& params) - : FieldGenerator(params), descriptor_(descriptor) { - SetEnumVariables(params, descriptor, &variables_); - LoadEnumValues(params, descriptor->enum_type(), &canonical_values_); -} - -EnumFieldGenerator::~EnumFieldGenerator() {} - -void EnumFieldGenerator:: -GenerateMembers(io::Printer* printer, bool /* unused lazy_init */) const { - if (params_.generate_intdefs()) { - printer->Print(variables_, "$message_type_intdef$\n"); - } - printer->Print(variables_, "public $type$ $name$;\n"); - - if (params_.generate_has()) { - printer->Print(variables_, - "public boolean has$capitalized_name$;\n"); - } -} - -void EnumFieldGenerator:: -GenerateClearCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$ = $default$;\n"); - - if (params_.generate_has()) { - printer->Print(variables_, - "has$capitalized_name$ = false;\n"); - } -} - -void EnumFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, - "int value = input.readInt32();\n" - "switch (value) {\n"); - PrintCaseLabels(printer, canonical_values_); - printer->Print(variables_, - " this.$name$ = value;\n"); - if (params_.generate_has()) { - printer->Print(variables_, - " has$capitalized_name$ = true;\n"); - } - printer->Print( - " break;\n" - "}\n"); - // No default case: in case of invalid value from the wire, preserve old - // field value. Also we are not storing the invalid value into the unknown - // fields, because there is no way to get the value out. -} - -void EnumFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - if (descriptor_->is_required() && !params_.generate_has()) { - // Always serialize a required field if we don't have the 'has' signal. - printer->Print(variables_, - "output.writeInt32($number$, this.$name$);\n"); - } else { - if (params_.generate_has()) { - printer->Print(variables_, - "if (this.$name$ != $default$ || has$capitalized_name$) {\n"); - } else { - printer->Print(variables_, - "if (this.$name$ != $default$) {\n"); - } - printer->Print(variables_, - " output.writeInt32($number$, this.$name$);\n" - "}\n"); - } -} - -void EnumFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - if (descriptor_->is_required() && !params_.generate_has()) { - printer->Print(variables_, - "size += com.google.protobuf.nano.CodedOutputByteBufferNano\n" - " .computeInt32Size($number$, this.$name$);\n"); - } else { - if (params_.generate_has()) { - printer->Print(variables_, - "if (this.$name$ != $default$ || has$capitalized_name$) {\n"); - } else { - printer->Print(variables_, - "if (this.$name$ != $default$) {\n"); - } - printer->Print(variables_, - " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n" - " .computeInt32Size($number$, this.$name$);\n" - "}\n"); - } -} - -void EnumFieldGenerator::GenerateEqualsCode(io::Printer* printer) const { - if (params_.use_reference_types_for_primitives() - && !params_.reftypes_primitive_enums()) { - printer->Print(variables_, - "if (this.$name$ == null) {\n" - " if (other.$name$ != null) {\n" - " return false;\n" - " }\n" - "} else if (!this.$name$.equals(other.$name$)) {\n" - " return false;" - "}\n"); - } else { - // We define equality as serialized form equality. If generate_has(), - // then if the field value equals the default value in both messages, - // but one's 'has' field is set and the other's is not, the serialized - // forms are different and we should return false. - printer->Print(variables_, - "if (this.$name$ != other.$name$"); - if (params_.generate_has()) { - printer->Print(variables_, - "\n" - " || (this.$name$ == $default$\n" - " && this.has$capitalized_name$ != other.has$capitalized_name$)"); - } - printer->Print(") {\n" - " return false;\n" - "}\n"); - } -} - -void EnumFieldGenerator::GenerateHashCodeCode(io::Printer* printer) const { - printer->Print( - "result = 31 * result + "); - if (params_.use_reference_types_for_primitives() - && !params_.reftypes_primitive_enums()) { - printer->Print(variables_, - "(this.$name$ == null ? 0 : this.$name$)"); - } else { - printer->Print(variables_, - "this.$name$"); - } - printer->Print(";\n"); -} - -// =================================================================== - -AccessorEnumFieldGenerator:: -AccessorEnumFieldGenerator(const FieldDescriptor* descriptor, - const Params& params, int has_bit_index) - : FieldGenerator(params), descriptor_(descriptor) { - SetEnumVariables(params, descriptor, &variables_); - LoadEnumValues(params, descriptor->enum_type(), &canonical_values_); - SetBitOperationVariables("has", has_bit_index, &variables_); -} - -AccessorEnumFieldGenerator::~AccessorEnumFieldGenerator() {} - -void AccessorEnumFieldGenerator:: -GenerateMembers(io::Printer* printer, bool /* unused lazy_init */) const { - printer->Print(variables_, "private int $name$_;\n"); - if (params_.generate_intdefs()) { - printer->Print(variables_, "$message_type_intdef$\n"); - } - printer->Print(variables_, - "public int get$capitalized_name$() {\n" - " return $name$_;\n" - "}\n" - "public $message_name$ set$capitalized_name$("); - if (params_.generate_intdefs()) { - printer->Print(variables_, - "\n" - " $message_type_intdef$ "); - } - printer->Print(variables_, - "int value) {\n" - " $name$_ = value;\n" - " $set_has$;\n" - " return this;\n" - "}\n" - "public boolean has$capitalized_name$() {\n" - " return $get_has$;\n" - "}\n" - "public $message_name$ clear$capitalized_name$() {\n" - " $name$_ = $default$;\n" - " $clear_has$;\n" - " return this;\n" - "}\n"); -} - -void AccessorEnumFieldGenerator:: -GenerateClearCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_ = $default$;\n"); -} - -void AccessorEnumFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, - "int value = input.readInt32();\n" - "switch (value) {\n"); - PrintCaseLabels(printer, canonical_values_); - printer->Print(variables_, - " $name$_ = value;\n" - " $set_has$;\n" - " break;\n" - "}\n"); - // No default case: in case of invalid value from the wire, preserve old - // field value. Also we are not storing the invalid value into the unknown - // fields, because there is no way to get the value out. -} - -void AccessorEnumFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($get_has$) {\n" - " output.writeInt32($number$, $name$_);\n" - "}\n"); -} - -void AccessorEnumFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($get_has$) {\n" - " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n" - " .computeInt32Size($number$, $name$_);\n" - "}\n"); -} - -void AccessorEnumFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($different_has$\n" - " || $name$_ != other.$name$_) {\n" - " return false;\n" - "}\n"); -} - -void AccessorEnumFieldGenerator:: -GenerateHashCodeCode(io::Printer* printer) const { - printer->Print(variables_, - "result = 31 * result + $name$_;\n"); -} - -// =================================================================== - -RepeatedEnumFieldGenerator:: -RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor, const Params& params) - : FieldGenerator(params), descriptor_(descriptor) { - SetEnumVariables(params, descriptor, &variables_); - LoadEnumValues(params, descriptor->enum_type(), &canonical_values_); -} - -RepeatedEnumFieldGenerator::~RepeatedEnumFieldGenerator() {} - -void RepeatedEnumFieldGenerator:: -GenerateMembers(io::Printer* printer, bool /* unused lazy_init */) const { - printer->Print(variables_, - "public $type$[] $name$;\n"); -} - -void RepeatedEnumFieldGenerator:: -GenerateClearCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$ = $repeated_default$;\n"); -} - -void RepeatedEnumFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - // First, figure out the maximum length of the array, then parse, - // and finally copy the valid values to the field. - printer->Print(variables_, - "int length = com.google.protobuf.nano.WireFormatNano\n" - " .getRepeatedFieldArrayLength(input, $non_packed_tag$);\n" - "int[] validValues = new int[length];\n" - "int validCount = 0;\n" - "for (int i = 0; i < length; i++) {\n" - " if (i != 0) { // tag for first value already consumed.\n" - " input.readTag();\n" - " }\n" - " int value = input.readInt32();\n" - " switch (value) {\n"); - printer->Indent(); - PrintCaseLabels(printer, canonical_values_); - printer->Outdent(); - printer->Print(variables_, - " validValues[validCount++] = value;\n" - " break;\n" - " }\n" - "}\n" - "if (validCount != 0) {\n" - " int i = this.$name$ == null ? 0 : this.$name$.length;\n" - " if (i == 0 && validCount == validValues.length) {\n" - " this.$name$ = validValues;\n" - " } else {\n" - " int[] newArray = new int[i + validCount];\n" - " if (i != 0) {\n" - " java.lang.System.arraycopy(this.$name$, 0, newArray, 0, i);\n" - " }\n" - " java.lang.System.arraycopy(validValues, 0, newArray, i, validCount);\n" - " this.$name$ = newArray;\n" - " }\n" - "}\n"); -} - -void RepeatedEnumFieldGenerator:: -GenerateMergingCodeFromPacked(io::Printer* printer) const { - printer->Print(variables_, - "int bytes = input.readRawVarint32();\n" - "int limit = input.pushLimit(bytes);\n" - "// First pass to compute array length.\n" - "int arrayLength = 0;\n" - "int startPos = input.getPosition();\n" - "while (input.getBytesUntilLimit() > 0) {\n" - " switch (input.readInt32()) {\n"); - printer->Indent(); - PrintCaseLabels(printer, canonical_values_); - printer->Outdent(); - printer->Print(variables_, - " arrayLength++;\n" - " break;\n" - " }\n" - "}\n" - "if (arrayLength != 0) {\n" - " input.rewindToPosition(startPos);\n" - " int i = this.$name$ == null ? 0 : this.$name$.length;\n" - " int[] newArray = new int[i + arrayLength];\n" - " if (i != 0) {\n" - " java.lang.System.arraycopy(this.$name$, 0, newArray, 0, i);\n" - " }\n" - " while (input.getBytesUntilLimit() > 0) {\n" - " int value = input.readInt32();\n" - " switch (value) {\n"); - printer->Indent(); - printer->Indent(); - PrintCaseLabels(printer, canonical_values_); - printer->Outdent(); - printer->Outdent(); - printer->Print(variables_, - " newArray[i++] = value;\n" - " break;\n" - " }\n" - " }\n" - " this.$name$ = newArray;\n" - "}\n" - "input.popLimit(limit);\n"); -} - -void RepeatedEnumFieldGenerator:: -GenerateRepeatedDataSizeCode(io::Printer* printer) const { - // Creates a variable dataSize and puts the serialized size in there. - printer->Print(variables_, - "int dataSize = 0;\n" - "for (int i = 0; i < this.$name$.length; i++) {\n" - " int element = this.$name$[i];\n" - " dataSize += com.google.protobuf.nano.CodedOutputByteBufferNano\n" - " .computeInt32SizeNoTag(element);\n" - "}\n"); -} - -void RepeatedEnumFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if (this.$name$ != null && this.$name$.length > 0) {\n"); - printer->Indent(); - - if (descriptor_->options().packed()) { - GenerateRepeatedDataSizeCode(printer); - printer->Print(variables_, - "output.writeRawVarint32($tag$);\n" - "output.writeRawVarint32(dataSize);\n" - "for (int i = 0; i < this.$name$.length; i++) {\n" - " output.writeRawVarint32(this.$name$[i]);\n" - "}\n"); - } else { - printer->Print(variables_, - "for (int i = 0; i < this.$name$.length; i++) {\n" - " output.writeInt32($number$, this.$name$[i]);\n" - "}\n"); - } - - printer->Outdent(); - printer->Print(variables_, - "}\n"); -} - -void RepeatedEnumFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if (this.$name$ != null && this.$name$.length > 0) {\n"); - printer->Indent(); - - GenerateRepeatedDataSizeCode(printer); - - printer->Print( - "size += dataSize;\n"); - if (descriptor_->options().packed()) { - printer->Print(variables_, - "size += $tag_size$;\n" - "size += com.google.protobuf.nano.CodedOutputByteBufferNano\n" - " .computeRawVarint32Size(dataSize);\n"); - } else { - printer->Print(variables_, - "size += $tag_size$ * this.$name$.length;\n"); - } - - printer->Outdent(); - - printer->Print( - "}\n"); -} - -void RepeatedEnumFieldGenerator:: -GenerateFixClonedCode(io::Printer* printer) const { - printer->Print(variables_, - "if (this.$name$ != null && this.$name$.length > 0) {\n" - " cloned.$name$ = this.$name$.clone();\n" - "}\n"); -} - -void RepeatedEnumFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!com.google.protobuf.nano.InternalNano.equals(\n" - " this.$name$, other.$name$)) {\n" - " return false;\n" - "}\n"); -} - -void RepeatedEnumFieldGenerator:: -GenerateHashCodeCode(io::Printer* printer) const { - printer->Print(variables_, - "result = 31 * result\n" - " + com.google.protobuf.nano.InternalNano.hashCode(this.$name$);\n"); -} - -} // namespace javanano -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/src/google/protobuf/compiler/javanano/javanano_enum_field.h b/src/google/protobuf/compiler/javanano/javanano_enum_field.h deleted file mode 100644 index 8cd0e248..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_enum_field.h +++ /dev/null @@ -1,126 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_FIELD_H__ - -#include <map> -#include <string> -#include <vector> -#include <google/protobuf/compiler/javanano/javanano_field.h> - -namespace google { -namespace protobuf { -namespace compiler { -namespace javanano { - -class EnumFieldGenerator : public FieldGenerator { - public: - explicit EnumFieldGenerator( - const FieldDescriptor* descriptor, const Params& params); - ~EnumFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GenerateMembers(io::Printer* printer, bool lazy_init) const; - void GenerateClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCodeCode(io::Printer* printer) const; - - private: - const FieldDescriptor* descriptor_; - std::map<string, string> variables_; - std::vector<string> canonical_values_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator); -}; - -class AccessorEnumFieldGenerator : public FieldGenerator { - public: - explicit AccessorEnumFieldGenerator(const FieldDescriptor* descriptor, - const Params& params, int has_bit_index); - ~AccessorEnumFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GenerateMembers(io::Printer* printer, bool lazy_init) const; - void GenerateClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCodeCode(io::Printer* printer) const; - - private: - const FieldDescriptor* descriptor_; - std::map<string, string> variables_; - std::vector<string> canonical_values_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(AccessorEnumFieldGenerator); -}; - -class RepeatedEnumFieldGenerator : public FieldGenerator { - public: - explicit RepeatedEnumFieldGenerator( - const FieldDescriptor* descriptor, const Params& params); - ~RepeatedEnumFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GenerateMembers(io::Printer* printer, bool lazy_init) const; - void GenerateClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateMergingCodeFromPacked(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCodeCode(io::Printer* printer) const; - void GenerateFixClonedCode(io::Printer* printer) const; - - private: - void GenerateRepeatedDataSizeCode(io::Printer* printer) const; - - const FieldDescriptor* descriptor_; - std::map<string, string> variables_; - std::vector<string> canonical_values_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator); -}; - -} // namespace javanano -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_FIELD_H__ diff --git a/src/google/protobuf/compiler/javanano/javanano_extension.cc b/src/google/protobuf/compiler/javanano/javanano_extension.cc deleted file mode 100644 index 4c61f915..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_extension.cc +++ /dev/null @@ -1,150 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: bduff@google.com (Brian Duff) - -#include <google/protobuf/compiler/javanano/javanano_extension.h> -#include <google/protobuf/compiler/javanano/javanano_helpers.h> -#include <google/protobuf/io/printer.h> -#include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/wire_format.h> - -namespace google { -namespace protobuf { -namespace compiler { -namespace javanano { - -using internal::WireFormat; -using internal::WireFormatLite; - -namespace { - -const char* GetTypeConstantName(const FieldDescriptor::Type type) { - switch (type) { - case FieldDescriptor::TYPE_INT32 : return "TYPE_INT32" ; - case FieldDescriptor::TYPE_UINT32 : return "TYPE_UINT32" ; - case FieldDescriptor::TYPE_SINT32 : return "TYPE_SINT32" ; - case FieldDescriptor::TYPE_FIXED32 : return "TYPE_FIXED32" ; - case FieldDescriptor::TYPE_SFIXED32: return "TYPE_SFIXED32"; - case FieldDescriptor::TYPE_INT64 : return "TYPE_INT64" ; - case FieldDescriptor::TYPE_UINT64 : return "TYPE_UINT64" ; - case FieldDescriptor::TYPE_SINT64 : return "TYPE_SINT64" ; - case FieldDescriptor::TYPE_FIXED64 : return "TYPE_FIXED64" ; - case FieldDescriptor::TYPE_SFIXED64: return "TYPE_SFIXED64"; - case FieldDescriptor::TYPE_FLOAT : return "TYPE_FLOAT" ; - case FieldDescriptor::TYPE_DOUBLE : return "TYPE_DOUBLE" ; - case FieldDescriptor::TYPE_BOOL : return "TYPE_BOOL" ; - case FieldDescriptor::TYPE_STRING : return "TYPE_STRING" ; - case FieldDescriptor::TYPE_BYTES : return "TYPE_BYTES" ; - case FieldDescriptor::TYPE_ENUM : return "TYPE_ENUM" ; - case FieldDescriptor::TYPE_GROUP : return "TYPE_GROUP" ; - case FieldDescriptor::TYPE_MESSAGE : return "TYPE_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; -} - -} // namespace - -void SetVariables(const FieldDescriptor* descriptor, const Params params, - std::map<string, string>* variables) { - (*variables)["extends"] = ClassName(params, descriptor->containing_type()); - (*variables)["name"] = RenameJavaKeywords(UnderscoresToCamelCase(descriptor)); - bool repeated = descriptor->is_repeated(); - (*variables)["repeated"] = repeated ? "Repeated" : ""; - (*variables)["type"] = GetTypeConstantName(descriptor->type()); - JavaType java_type = GetJavaType(descriptor->type()); - string tag = SimpleItoa(WireFormat::MakeTag(descriptor)); - if (java_type == JAVATYPE_MESSAGE) { - (*variables)["ext_type"] = "MessageTyped"; - string message_type = ClassName(params, descriptor->message_type()); - if (repeated) { - message_type += "[]"; - } - (*variables)["class"] = message_type; - // For message typed extensions, tags_params contains a single tag - // for both singular and repeated cases. - (*variables)["tag_params"] = tag; - } else { - (*variables)["ext_type"] = "PrimitiveTyped"; - if (!repeated) { - (*variables)["class"] = BoxedPrimitiveTypeName(java_type); - (*variables)["tag_params"] = tag; - } else { - (*variables)["class"] = PrimitiveTypeName(java_type) + "[]"; - if (!descriptor->is_packable()) { - // Non-packable: nonPackedTag == tag, packedTag == 0 - (*variables)["tag_params"] = tag + ", " + tag + ", 0"; - } else if (descriptor->options().packed()) { - // Packable and packed: tag == packedTag - string non_packed_tag = SimpleItoa(WireFormatLite::MakeTag( - descriptor->number(), - WireFormat::WireTypeForFieldType(descriptor->type()))); - (*variables)["tag_params"] = tag + ", " + non_packed_tag + ", " + tag; - } else { - // Packable and not packed: tag == nonPackedTag - string packed_tag = SimpleItoa(WireFormatLite::MakeTag( - descriptor->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED)); - (*variables)["tag_params"] = tag + ", " + tag + ", " + packed_tag; - } - } - } -} - -ExtensionGenerator:: -ExtensionGenerator(const FieldDescriptor* descriptor, const Params& params) - : params_(params), descriptor_(descriptor) { - SetVariables(descriptor, params, &variables_); -} - -ExtensionGenerator::~ExtensionGenerator() {} - -void ExtensionGenerator::Generate(io::Printer* printer) const { - printer->Print("\n"); - PrintFieldComment(printer, descriptor_); - printer->Print(variables_, - "public static final com.google.protobuf.nano.Extension<\n" - " $extends$,\n" - " $class$> $name$ =\n" - " com.google.protobuf.nano.Extension.create$repeated$$ext_type$(\n" - " com.google.protobuf.nano.Extension.$type$,\n" - " $class$.class,\n" - " $tag_params$L);\n"); -} - -} // namespace javanano -} // namespace compiler -} // namespace protobuf -} // namespace google - diff --git a/src/google/protobuf/compiler/javanano/javanano_extension.h b/src/google/protobuf/compiler/javanano/javanano_extension.h deleted file mode 100644 index f4e9eb2d..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_extension.h +++ /dev/null @@ -1,74 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: bduff@google.com (Brian Duff) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_EXTENSION_H_ -#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_EXTENSION_H_ - -#include <google/protobuf/stubs/common.h> -#include <google/protobuf/compiler/javanano/javanano_params.h> -#include <google/protobuf/descriptor.pb.h> - - -namespace google { -namespace protobuf { - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace javanano { - -class ExtensionGenerator { - public: - explicit ExtensionGenerator(const FieldDescriptor* descriptor, const Params& params); - ~ExtensionGenerator(); - - void Generate(io::Printer* printer) const; - - private: - const Params& params_; - const FieldDescriptor* descriptor_; - std::map<string, string> variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator); -}; - -} // namespace javanano -} // namespace compiler -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_EXTENSION_H_ diff --git a/src/google/protobuf/compiler/javanano/javanano_field.cc b/src/google/protobuf/compiler/javanano/javanano_field.cc deleted file mode 100644 index 0c134fe1..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_field.cc +++ /dev/null @@ -1,209 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include <google/protobuf/compiler/javanano/javanano_field.h> -#include <google/protobuf/compiler/javanano/javanano_helpers.h> -#include <google/protobuf/compiler/javanano/javanano_primitive_field.h> -#include <google/protobuf/compiler/javanano/javanano_enum_field.h> -#include <google/protobuf/compiler/javanano/javanano_map_field.h> -#include <google/protobuf/compiler/javanano/javanano_message_field.h> -#include <google/protobuf/stubs/common.h> - -namespace google { -namespace protobuf { -namespace compiler { -namespace javanano { - -FieldGenerator::~FieldGenerator() {} - -bool FieldGenerator::SavedDefaultNeeded() const { - // No saved default for this field by default. - // Subclasses whose instances may need saved defaults will override this - // and return the appropriate value. - return false; -} - -void FieldGenerator::GenerateInitSavedDefaultCode(io::Printer* printer) const { - // No saved default for this field by default. - // Subclasses whose instances may need saved defaults will override this - // and generate the appropriate init code to the printer. -} - -void FieldGenerator::GenerateMergingCodeFromPacked(io::Printer* printer) const { - // Reaching here indicates a bug. Cases are: - // - This FieldGenerator should support packing, but this method should be - // overridden. - // - This FieldGenerator doesn't support packing, and this method should - // never have been called. - GOOGLE_LOG(FATAL) << "GenerateParsingCodeFromPacked() " - << "called on field generator that does not support packing."; -} - -// ============================================= - -FieldGeneratorMap::FieldGeneratorMap( - const Descriptor* descriptor, const Params ¶ms) - : descriptor_(descriptor), - field_generators_( - new std::unique_ptr<FieldGenerator>[descriptor->field_count()]) { - - int next_has_bit_index = 0; - bool saved_defaults_needed = false; - // Construct all the FieldGenerators. - for (int i = 0; i < descriptor->field_count(); i++) { - FieldGenerator* field_generator = MakeGenerator( - descriptor->field(i), params, &next_has_bit_index); - saved_defaults_needed = saved_defaults_needed - || field_generator->SavedDefaultNeeded(); - field_generators_[i].reset(field_generator); - } - total_bits_ = next_has_bit_index; - saved_defaults_needed_ = saved_defaults_needed; -} - -FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field, - const Params ¶ms, int* next_has_bit_index) { - JavaType java_type = GetJavaType(field); - if (field->is_repeated()) { - switch (java_type) { - case JAVATYPE_MESSAGE: - if (IsMapEntry(field->message_type())) { - return new MapFieldGenerator(field, params); - } else { - return new RepeatedMessageFieldGenerator(field, params); - } - case JAVATYPE_ENUM: - return new RepeatedEnumFieldGenerator(field, params); - default: - return new RepeatedPrimitiveFieldGenerator(field, params); - } - } else if (field->containing_oneof()) { - switch (java_type) { - case JAVATYPE_MESSAGE: - return new MessageOneofFieldGenerator(field, params); - case JAVATYPE_ENUM: - default: - return new PrimitiveOneofFieldGenerator(field, params); - } - } else if (params.optional_field_accessors() && field->is_optional() - && java_type != JAVATYPE_MESSAGE) { - // We need a has-bit for each primitive/enum field because their default - // values could be same as explicitly set values. But we don't need it - // for a message field because they have no defaults and Nano uses 'null' - // for unset messages, which cannot be set explicitly. - switch (java_type) { - case JAVATYPE_ENUM: - return new AccessorEnumFieldGenerator( - field, params, (*next_has_bit_index)++); - default: - return new AccessorPrimitiveFieldGenerator( - field, params, (*next_has_bit_index)++); - } - } else { - switch (java_type) { - case JAVATYPE_MESSAGE: - return new MessageFieldGenerator(field, params); - case JAVATYPE_ENUM: - return new EnumFieldGenerator(field, params); - default: - return new PrimitiveFieldGenerator(field, params); - } - } -} - -FieldGeneratorMap::~FieldGeneratorMap() {} - -const FieldGenerator& FieldGeneratorMap::get( - const FieldDescriptor* field) const { - GOOGLE_CHECK_EQ(field->containing_type(), descriptor_); - return *field_generators_[field->index()]; -} - -void SetCommonOneofVariables(const FieldDescriptor* descriptor, - std::map<string, string>* variables) { - (*variables)["oneof_name"] = - UnderscoresToCamelCase(descriptor->containing_oneof()); - (*variables)["oneof_capitalized_name"] = - UnderscoresToCapitalizedCamelCase(descriptor->containing_oneof()); - (*variables)["oneof_index"] = - SimpleItoa(descriptor->containing_oneof()->index()); - (*variables)["set_oneof_case"] = - "this." + (*variables)["oneof_name"] + - "Case_ = " + SimpleItoa(descriptor->number()); - (*variables)["clear_oneof_case"] = - "this." + (*variables)["oneof_name"] + "Case_ = 0"; - (*variables)["has_oneof_case"] = - "this." + (*variables)["oneof_name"] + "Case_ == " + - SimpleItoa(descriptor->number()); -} - -void GenerateOneofFieldEquals(const FieldDescriptor* descriptor, - const std::map<string, string>& variables, - io::Printer* printer) { - if (GetJavaType(descriptor) == JAVATYPE_BYTES) { - printer->Print(variables, - "if (this.has$capitalized_name$()) {\n" - " if (!java.util.Arrays.equals((byte[]) this.$oneof_name$_,\n" - " (byte[]) other.$oneof_name$_)) {\n" - " return false;\n" - " }\n" - "}\n"); - } else { - printer->Print(variables, - "if (this.has$capitalized_name$()) {\n" - " if (!this.$oneof_name$_.equals(other.$oneof_name$_)) {\n" - " return false;\n" - " }\n" - "}\n"); - } -} - -void GenerateOneofFieldHashCode(const FieldDescriptor* descriptor, - const std::map<string, string>& variables, - io::Printer* printer) { - if (GetJavaType(descriptor) == JAVATYPE_BYTES) { - printer->Print(variables, - "result = 31 * result + ($has_oneof_case$\n" - " ? java.util.Arrays.hashCode((byte[]) this.$oneof_name$_) : 0);\n"); - } else { - printer->Print(variables, - "result = 31 * result +\n" - " ($has_oneof_case$ ? this.$oneof_name$_.hashCode() : 0);\n"); - } -} - -} // namespace javanano -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/src/google/protobuf/compiler/javanano/javanano_field.h b/src/google/protobuf/compiler/javanano/javanano_field.h deleted file mode 100644 index e3701f10..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_field.h +++ /dev/null @@ -1,130 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_FIELD_H__ - -#include <map> -#include <string> -#include <google/protobuf/stubs/common.h> -#include <google/protobuf/descriptor.h> -#include <google/protobuf/compiler/javanano/javanano_params.h> - -namespace google { -namespace protobuf { - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace javanano { - -class FieldGenerator { - public: - FieldGenerator(const Params& params) : params_(params) {} - virtual ~FieldGenerator(); - - virtual bool SavedDefaultNeeded() const; - virtual void GenerateInitSavedDefaultCode(io::Printer* printer) const; - - // Generates code for Java fields and methods supporting this field. - // If this field needs a saved default (SavedDefaultNeeded() is true), - // then @lazy_init controls how the static field for that default value - // and its initialization code should be generated. If @lazy_init is - // true, the static field is not declared final and the initialization - // code is generated only when GenerateInitSavedDefaultCode is called; - // otherwise, the static field is declared final and initialized inline. - // GenerateInitSavedDefaultCode will not be called in the latter case. - virtual void GenerateMembers( - io::Printer* printer, bool lazy_init) const = 0; - - virtual void GenerateClearCode(io::Printer* printer) const = 0; - virtual void GenerateMergingCode(io::Printer* printer) const = 0; - - // Generates code to merge from packed serialized form. The default - // implementation will fail; subclasses which can handle packed serialized - // forms will override this and print appropriate code to the printer. - virtual void GenerateMergingCodeFromPacked(io::Printer* printer) const; - - virtual void GenerateSerializationCode(io::Printer* printer) const = 0; - virtual void GenerateSerializedSizeCode(io::Printer* printer) const = 0; - virtual void GenerateEqualsCode(io::Printer* printer) const = 0; - virtual void GenerateHashCodeCode(io::Printer* printer) const = 0; - virtual void GenerateFixClonedCode(io::Printer* printer) const {} - - protected: - const Params& params_; - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator); -}; - -// Convenience class which constructs FieldGenerators for a Descriptor. -class FieldGeneratorMap { - public: - explicit FieldGeneratorMap(const Descriptor* descriptor, const Params ¶ms); - ~FieldGeneratorMap(); - - const FieldGenerator& get(const FieldDescriptor* field) const; - int total_bits() const { return total_bits_; } - bool saved_defaults_needed() const { return saved_defaults_needed_; } - - private: - const Descriptor* descriptor_; - std::unique_ptr<std::unique_ptr<FieldGenerator>[]> field_generators_; - int total_bits_; - bool saved_defaults_needed_; - - static FieldGenerator* MakeGenerator(const FieldDescriptor* field, - const Params ¶ms, int* next_has_bit_index); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap); -}; - -void SetCommonOneofVariables(const FieldDescriptor* descriptor, - std::map<string, string>* variables); -void GenerateOneofFieldEquals(const FieldDescriptor* descriptor, - const std::map<string, string>& variables, - io::Printer* printer); -void GenerateOneofFieldHashCode(const FieldDescriptor* descriptor, - const std::map<string, string>& variables, - io::Printer* printer); - -} // namespace javanano -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_FIELD_H__ diff --git a/src/google/protobuf/compiler/javanano/javanano_file.cc b/src/google/protobuf/compiler/javanano/javanano_file.cc deleted file mode 100644 index 9acdc3b5..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_file.cc +++ /dev/null @@ -1,263 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include <iostream> - -#include <google/protobuf/compiler/javanano/javanano_file.h> -#include <google/protobuf/compiler/javanano/javanano_enum.h> -#include <google/protobuf/compiler/javanano/javanano_extension.h> -#include <google/protobuf/compiler/javanano/javanano_helpers.h> -#include <google/protobuf/compiler/javanano/javanano_message.h> -#include <google/protobuf/compiler/code_generator.h> -#include <google/protobuf/io/printer.h> -#include <google/protobuf/io/zero_copy_stream.h> -#include <google/protobuf/descriptor.pb.h> -#include <google/protobuf/stubs/strutil.h> - -namespace google { -namespace protobuf { -namespace compiler { -namespace javanano { - -namespace { - -// Recursively searches the given message to see if it contains any extensions. -bool UsesExtensions(const Message& message) { - const Reflection* reflection = message.GetReflection(); - - // We conservatively assume that unknown fields are extensions. - if (reflection->GetUnknownFields(message).field_count() > 0) return true; - - std::vector<const FieldDescriptor*> fields; - reflection->ListFields(message, &fields); - - for (int i = 0; i < fields.size(); i++) { - if (fields[i]->is_extension()) return true; - - if (fields[i]->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - if (fields[i]->is_repeated()) { - int size = reflection->FieldSize(message, fields[i]); - for (int j = 0; j < size; j++) { - const Message& sub_message = - reflection->GetRepeatedMessage(message, fields[i], j); - if (UsesExtensions(sub_message)) return true; - } - } else { - const Message& sub_message = reflection->GetMessage(message, fields[i]); - if (UsesExtensions(sub_message)) return true; - } - } - } - - return false; -} - -} // namespace - -FileGenerator::FileGenerator(const FileDescriptor* file, const Params& params) - : file_(file), - params_(params), - java_package_(FileJavaPackage(params, file)), - classname_(FileClassName(params, file)) {} - -FileGenerator::~FileGenerator() {} - -bool FileGenerator::Validate(string* error) { - // Check for extensions - FileDescriptorProto file_proto; - file_->CopyTo(&file_proto); - if (UsesExtensions(file_proto) && !params_.store_unknown_fields()) { - error->assign(file_->name()); - error->append( - ": Java NANO_RUNTIME only supports extensions when the " - "'store_unknown_fields' generator option is 'true'."); - return false; - } - - if (file_->service_count() != 0 && !params_.ignore_services()) { - error->assign(file_->name()); - error->append( - ": Java NANO_RUNTIME does not support services\""); - return false; - } - - if (!IsOuterClassNeeded(params_, file_)) { - return true; - } - - // Check whether legacy javanano generator would omit the outer class. - if (!params_.has_java_outer_classname(file_->name()) - && file_->message_type_count() == 1 - && file_->enum_type_count() == 0 && file_->extension_count() == 0) { - std::cout << "INFO: " << file_->name() << ":" << std::endl; - std::cout << "Javanano generator has changed to align with java generator. " - "An outer class will be created for this file and the single message " - "in the file will become a nested class. Use java_multiple_files to " - "skip generating the outer class, or set an explicit " - "java_outer_classname to suppress this message." << std::endl; - } - - // Check that no class name matches the file's class name. This is a common - // problem that leads to Java compile errors that can be hard to understand. - // It's especially bad when using the java_multiple_files, since we would - // end up overwriting the outer class with one of the inner ones. - bool found_conflict = false; - for (int i = 0; !found_conflict && i < file_->message_type_count(); i++) { - if (file_->message_type(i)->name() == classname_) { - found_conflict = true; - } - } - if (params_.java_enum_style()) { - for (int i = 0; !found_conflict && i < file_->enum_type_count(); i++) { - if (file_->enum_type(i)->name() == classname_) { - found_conflict = true; - } - } - } - if (found_conflict) { - error->assign(file_->name()); - error->append( - ": Cannot generate Java output because the file's outer class name, \""); - error->append(classname_); - error->append( - "\", matches the name of one of the types declared inside it. " - "Please either rename the type or use the java_outer_classname " - "option to specify a different outer class name for the .proto file."); - return false; - } - return true; -} - -void FileGenerator::Generate(io::Printer* printer) { - // We don't import anything because we refer to all classes by their - // fully-qualified names in the generated source. - printer->Print( - "// Generated by the protocol buffer compiler. DO NOT EDIT!\n"); - if (!java_package_.empty()) { - printer->Print( - "\n" - "package $package$;\n", - "package", java_package_); - } - - // Note: constants (from enums, emitted in the loop below) may have the same names as constants - // in the nested classes. This causes Java warnings, but is not fatal, so we suppress those - // warnings here in the top-most class declaration. - printer->Print( - "\n" - "@SuppressWarnings(\"hiding\")\n" - "public interface $classname$ {\n", - "classname", classname_); - printer->Indent(); - - // ----------------------------------------------------------------- - - // Extensions. - for (int i = 0; i < file_->extension_count(); i++) { - ExtensionGenerator(file_->extension(i), params_).Generate(printer); - } - - // Enums. - for (int i = 0; i < file_->enum_type_count(); i++) { - EnumGenerator(file_->enum_type(i), params_).Generate(printer); - } - - // Messages. - if (!params_.java_multiple_files(file_->name())) { - for (int i = 0; i < file_->message_type_count(); i++) { - MessageGenerator(file_->message_type(i), params_).Generate(printer); - } - } - - // Static variables. - for (int i = 0; i < file_->message_type_count(); i++) { - // TODO(kenton): Reuse MessageGenerator objects? - MessageGenerator(file_->message_type(i), params_).GenerateStaticVariables(printer); - } - - printer->Outdent(); - printer->Print( - "}\n"); -} - -template<typename GeneratorClass, typename DescriptorClass> -static void GenerateSibling(const string& package_dir, - const string& java_package, - const DescriptorClass* descriptor, - GeneratorContext* output_directory, - std::vector<string>* file_list, - const Params& params) { - string filename = package_dir + descriptor->name() + ".java"; - file_list->push_back(filename); - - std::unique_ptr<io::ZeroCopyOutputStream> output( - output_directory->Open(filename)); - io::Printer printer(output.get(), '$'); - - printer.Print( - "// Generated by the protocol buffer compiler. DO NOT EDIT!\n"); - if (!java_package.empty()) { - printer.Print( - "\n" - "package $package$;\n", - "package", java_package); - } - - GeneratorClass(descriptor, params).Generate(&printer); -} - -void FileGenerator::GenerateSiblings(const string& package_dir, - GeneratorContext* output_directory, - std::vector<string>* file_list) { - if (params_.java_multiple_files(file_->name())) { - for (int i = 0; i < file_->message_type_count(); i++) { - GenerateSibling<MessageGenerator>(package_dir, java_package_, - file_->message_type(i), - output_directory, file_list, params_); - } - - if (params_.java_enum_style()) { - for (int i = 0; i < file_->enum_type_count(); i++) { - GenerateSibling<EnumGenerator>(package_dir, java_package_, - file_->enum_type(i), - output_directory, file_list, params_); - } - } - } -} - -} // namespace javanano -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/src/google/protobuf/compiler/javanano/javanano_file.h b/src/google/protobuf/compiler/javanano/javanano_file.h deleted file mode 100644 index 4ad3868c..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_file.h +++ /dev/null @@ -1,94 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_FILE_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_FILE_H__ - -#include <string> -#include <vector> -#include <google/protobuf/stubs/common.h> -#include <google/protobuf/compiler/javanano/javanano_params.h> - -namespace google { -namespace protobuf { - class FileDescriptor; // descriptor.h - namespace io { - class Printer; // printer.h - } - namespace compiler { - class GeneratorContext; // code_generator.h - } -} - -namespace protobuf { -namespace compiler { -namespace javanano { - -class FileGenerator { - public: - explicit FileGenerator(const FileDescriptor* file, const Params& params); - ~FileGenerator(); - - // Checks for problems that would otherwise lead to cryptic compile errors. - // Returns true if there are no problems, or writes an error description to - // the given string and returns false otherwise. - bool Validate(string* error); - - void Generate(io::Printer* printer); - - // If we aren't putting everything into one file, this will write all the - // files other than the outer file (i.e. one for each message, enum, and - // service type). - void GenerateSiblings(const string& package_dir, - GeneratorContext* output_directory, - std::vector<string>* file_list); - - const string& java_package() { return java_package_; } - const string& classname() { return classname_; } - - private: - const FileDescriptor* file_; - const Params& params_; - string java_package_; - string classname_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileGenerator); -}; - -} // namespace javanano -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_FILE_H__ diff --git a/src/google/protobuf/compiler/javanano/javanano_generator.cc b/src/google/protobuf/compiler/javanano/javanano_generator.cc deleted file mode 100644 index 64ba3336..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_generator.cc +++ /dev/null @@ -1,230 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include <google/protobuf/compiler/javanano/javanano_params.h> -#include <google/protobuf/compiler/javanano/javanano_generator.h> -#include <google/protobuf/compiler/javanano/javanano_file.h> -#include <google/protobuf/compiler/javanano/javanano_helpers.h> -#include <google/protobuf/io/printer.h> -#include <google/protobuf/io/zero_copy_stream.h> -#include <google/protobuf/descriptor.pb.h> -#include <google/protobuf/stubs/strutil.h> - -namespace google { -namespace protobuf { -namespace compiler { -namespace javanano { - -namespace { - -string TrimString(const string& s) { - string::size_type start = s.find_first_not_of(" \n\r\t"); - if (start == string::npos) { - return ""; - } - string::size_type end = s.find_last_not_of(" \n\r\t") + 1; - return s.substr(start, end - start); -} - -} // namespace - -void UpdateParamsRecursively(Params& params, - const FileDescriptor* file) { - // Add any parameters for this file - if (file->options().has_java_outer_classname()) { - params.set_java_outer_classname( - file->name(), file->options().java_outer_classname()); - } - if (file->options().has_java_package()) { - string result = file->options().java_package(); - if (!result.empty()) { - result += "."; - } - result += "nano"; - params.set_java_package( - file->name(), result); - } - if (file->options().has_java_multiple_files()) { - params.set_java_multiple_files( - file->name(), file->options().java_multiple_files()); - } - - // Loop through all dependent files recursively - // adding dep - for (int i = 0; i < file->dependency_count(); i++) { - UpdateParamsRecursively(params, file->dependency(i)); - } -} - -JavaNanoGenerator::JavaNanoGenerator() {} -JavaNanoGenerator::~JavaNanoGenerator() {} - -bool JavaNanoGenerator::Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* output_directory, - string* error) const { - std::vector<std::pair<string, string> > options; - - ParseGeneratorParameter(parameter, &options); - - // ----------------------------------------------------------------- - // parse generator options - - // Name a file where we will write a list of generated file names, one - // per line. - string output_list_file; - Params params(file->name()); - - // Update per file params - UpdateParamsRecursively(params, file); - - // Replace any existing options with ones from command line - for (int i = 0; i < options.size(); i++) { - string option_name = TrimString(options[i].first); - string option_value = TrimString(options[i].second); - if (option_name == "output_list_file") { - output_list_file = option_value; - } else if (option_name == "java_package") { - std::vector<string> parts; - SplitStringUsing(option_value, "|", &parts); - if (parts.size() != 2) { - *error = "Bad java_package, expecting filename|PackageName found '" - + option_value + "'"; - return false; - } - params.set_java_package(parts[0], parts[1]); - } else if (option_name == "java_outer_classname") { - std::vector<string> parts; - SplitStringUsing(option_value, "|", &parts); - if (parts.size() != 2) { - *error = "Bad java_outer_classname, " - "expecting filename|ClassName found '" - + option_value + "'"; - return false; - } - params.set_java_outer_classname(parts[0], parts[1]); - } else if (option_name == "store_unknown_fields") { - params.set_store_unknown_fields(option_value == "true"); - } else if (option_name == "java_multiple_files") { - params.set_override_java_multiple_files(option_value == "true"); - } else if (option_name == "java_nano_generate_has") { - params.set_generate_has(option_value == "true"); - } else if (option_name == "enum_style") { - params.set_java_enum_style(option_value == "java"); - } else if (option_name == "optional_field_style") { - params.set_optional_field_accessors(option_value == "accessors"); - params.set_use_reference_types_for_primitives(option_value == "reftypes" - || option_value == "reftypes_compat_mode"); - params.set_reftypes_primitive_enums( - option_value == "reftypes_compat_mode"); - if (option_value == "reftypes_compat_mode") { - params.set_generate_clear(false); - } - } else if (option_name == "generate_equals") { - params.set_generate_equals(option_value == "true"); - } else if (option_name == "ignore_services") { - params.set_ignore_services(option_value == "true"); - } else if (option_name == "parcelable_messages") { - params.set_parcelable_messages(option_value == "true"); - } else if (option_name == "generate_clone") { - params.set_generate_clone(option_value == "true"); - } else if (option_name == "generate_intdefs") { - params.set_generate_intdefs(option_value == "true"); - } else if (option_name == "generate_clear") { - params.set_generate_clear(option_value == "true"); - } else { - *error = "Ignore unknown javanano generator option: " + option_name; - } - } - - // Check illegal parameter combinations - // Note: the enum-like optional_field_style generator param ensures - // that we can never have illegal combinations of field styles - // (e.g. reftypes and accessors can't be on at the same time). - if (params.generate_has() - && (params.optional_field_accessors() - || params.use_reference_types_for_primitives())) { - error->assign("java_nano_generate_has=true cannot be used in conjunction" - " with optional_field_style=accessors or optional_field_style=reftypes"); - return false; - } - - // ----------------------------------------------------------------- - - FileGenerator file_generator(file, params); - if (!file_generator.Validate(error)) { - return false; - } - - string package_dir = - StringReplace(file_generator.java_package(), ".", "/", true); - if (!package_dir.empty()) package_dir += "/"; - - std::vector<string> all_files; - - if (IsOuterClassNeeded(params, file)) { - string java_filename = package_dir; - java_filename += file_generator.classname(); - java_filename += ".java"; - all_files.push_back(java_filename); - - // Generate main java file. - std::unique_ptr<io::ZeroCopyOutputStream> output( - output_directory->Open(java_filename)); - io::Printer printer(output.get(), '$'); - file_generator.Generate(&printer); - } - - // Generate sibling files. - file_generator.GenerateSiblings(package_dir, output_directory, &all_files); - - // Generate output list if requested. - if (!output_list_file.empty()) { - // Generate output list. This is just a simple text file placed in a - // deterministic location which lists the .java files being generated. - std::unique_ptr<io::ZeroCopyOutputStream> srclist_raw_output( - output_directory->Open(output_list_file)); - io::Printer srclist_printer(srclist_raw_output.get(), '$'); - for (int i = 0; i < all_files.size(); i++) { - srclist_printer.Print("$filename$\n", "filename", all_files[i]); - } - } - - return true; -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/src/google/protobuf/compiler/javanano/javanano_generator.h b/src/google/protobuf/compiler/javanano/javanano_generator.h deleted file mode 100644 index 6f9f7f2a..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_generator.h +++ /dev/null @@ -1,72 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// Generates Java nano code for a given .proto file. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_NANO_GENERATOR_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_NANO_GENERATOR_H__ - -#include <string> -#include <google/protobuf/compiler/code_generator.h> - -namespace google { -namespace protobuf { -namespace compiler { -namespace javanano { - -// CodeGenerator implementation which generates Java nano code. If you create your -// own protocol compiler binary and you want it to support Java output for the -// nano runtime, you can do so by registering an instance of this CodeGenerator with -// the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT JavaNanoGenerator : public CodeGenerator { - public: - JavaNanoGenerator(); - ~JavaNanoGenerator(); - - // implements CodeGenerator ---------------------------------------- - bool Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* output_directory, - string* error) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(JavaNanoGenerator); -}; - -} // namespace javanano -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_NANO_GENERATOR_H__ diff --git a/src/google/protobuf/compiler/javanano/javanano_helpers.cc b/src/google/protobuf/compiler/javanano/javanano_helpers.cc deleted file mode 100644 index 1927ba12..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_helpers.cc +++ /dev/null @@ -1,591 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include <limits> -#include <vector> - -#include <google/protobuf/compiler/javanano/javanano_helpers.h> -#include <google/protobuf/compiler/javanano/javanano_params.h> -#include <google/protobuf/descriptor.pb.h> -#include <google/protobuf/stubs/hash.h> -#include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/stubs/substitute.h> - -namespace google { -namespace protobuf { -namespace compiler { -namespace javanano { - -const char kThickSeparator[] = - "// ===================================================================\n"; -const char kThinSeparator[] = - "// -------------------------------------------------------------------\n"; - -class RenameKeywords { - private: - hash_set<string> java_keywords_set_; - - public: - RenameKeywords() { - static const char* kJavaKeywordsList[] = { - // Reserved Java Keywords - "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", - - // Reserved Keywords for Literals - "false", "null", "true" - }; - - for (int i = 0; i < GOOGLE_ARRAYSIZE(kJavaKeywordsList); i++) { - java_keywords_set_.insert(kJavaKeywordsList[i]); - } - } - - // Used to rename the a field name if it's a java keyword. Specifically - // this is used to rename the ["name"] or ["capitalized_name"] field params. - // (http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html) - string RenameJavaKeywordsImpl(const string& input) { - string result = input; - - if (java_keywords_set_.find(result) != java_keywords_set_.end()) { - result += "_"; - } - - return result; - } - -}; - -static RenameKeywords sRenameKeywords; - -namespace { - -const char* kDefaultPackage = ""; - -const string& FieldName(const FieldDescriptor* field) { - // 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 (field->type() == FieldDescriptor::TYPE_GROUP) { - return field->message_type()->name(); - } else { - return field->name(); - } -} - -string UnderscoresToCamelCaseImpl(const string& input, bool cap_next_letter) { - 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; - } - } - return result; -} - -} // namespace - -string UnderscoresToCamelCase(const FieldDescriptor* field) { - return UnderscoresToCamelCaseImpl(FieldName(field), false); -} - -string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field) { - return UnderscoresToCamelCaseImpl(FieldName(field), true); -} - -string UnderscoresToCamelCase(const MethodDescriptor* method) { - return UnderscoresToCamelCaseImpl(method->name(), false); -} - -string UnderscoresToCamelCase(const OneofDescriptor* oneof) { - return UnderscoresToCamelCaseImpl(oneof->name(), false); -} - -string UnderscoresToCapitalizedCamelCase(const OneofDescriptor* oneof) { - return UnderscoresToCamelCaseImpl(oneof->name(), true); -} - -string RenameJavaKeywords(const string& input) { - return sRenameKeywords.RenameJavaKeywordsImpl(input); -} - -string StripProto(const string& filename) { - if (HasSuffixString(filename, ".protodevel")) { - return StripSuffixString(filename, ".protodevel"); - } else { - return StripSuffixString(filename, ".proto"); - } -} - -string FileClassName(const Params& params, const FileDescriptor* file) { - if (params.has_java_outer_classname(file->name())) { - return params.java_outer_classname(file->name()); - } else { - // Use the filename itself with underscores removed - // and a CamelCase style name. - string basename; - string::size_type last_slash = file->name().find_last_of('/'); - if (last_slash == string::npos) { - basename = file->name(); - } else { - basename = file->name().substr(last_slash + 1); - } - return UnderscoresToCamelCaseImpl(StripProto(basename), true); - } -} - -string FileJavaPackage(const Params& params, const FileDescriptor* file) { - if (params.has_java_package(file->name())) { - return params.java_package(file->name()); - } else { - string result = kDefaultPackage; - if (!file->package().empty()) { - if (!result.empty()) result += '.'; - result += file->package(); - } - - if (!result.empty()) { - result += "."; - } - result += "nano"; - - return result; - } -} - -bool IsOuterClassNeeded(const Params& params, const FileDescriptor* file) { - // If java_multiple_files is false, the outer class is always needed. - if (!params.java_multiple_files(file->name())) { - return true; - } - - // File-scope extensions need the outer class as the scope. - if (file->extension_count() != 0) { - return true; - } - - // If container interfaces are not generated, file-scope enums need the - // outer class as the scope. - if (file->enum_type_count() != 0 && !params.java_enum_style()) { - return true; - } - - return false; -} - -string ToJavaName(const Params& params, const string& name, bool is_class, - const Descriptor* parent, const FileDescriptor* file) { - string result; - if (parent != NULL) { - result.append(ClassName(params, parent)); - } else if (is_class && params.java_multiple_files(file->name())) { - result.append(FileJavaPackage(params, file)); - } else { - result.append(ClassName(params, file)); - } - if (!result.empty()) result.append(1, '.'); - result.append(RenameJavaKeywords(name)); - return result; -} - -string ClassName(const Params& params, const FileDescriptor* descriptor) { - string result = FileJavaPackage(params, descriptor); - if (!result.empty()) result += '.'; - result += FileClassName(params, descriptor); - return result; -} - -string ClassName(const Params& params, const EnumDescriptor* descriptor) { - const Descriptor* parent = descriptor->containing_type(); - // When using Java enum style, an enum's class name contains the enum name. - // Use the standard ToJavaName translation. - if (params.java_enum_style()) { - return ToJavaName(params, descriptor->name(), true, parent, - descriptor->file()); - } - // Otherwise the enum members are accessed from the enclosing class. - if (parent != NULL) { - return ClassName(params, parent); - } else { - return ClassName(params, descriptor->file()); - } -} - -string FieldConstantName(const FieldDescriptor *field) { - string name = field->name() + "_FIELD_NUMBER"; - UpperString(&name); - return name; -} - -string FieldDefaultConstantName(const FieldDescriptor *field) { - return "_" + RenameJavaKeywords(UnderscoresToCamelCase(field)) + "Default"; -} - -void PrintFieldComment(io::Printer* printer, const FieldDescriptor* field) { - // We don't want to print group bodies so we cut off after the first line - // (the second line for extensions). - string def = field->DebugString(); - string::size_type first_line_end = def.find_first_of('\n'); - printer->Print("// $def$\n", - "def", def.substr(0, first_line_end)); - if (field->is_extension()) { - string::size_type second_line_start = first_line_end + 1; - string::size_type second_line_length = - def.find('\n', second_line_start) - second_line_start; - printer->Print("// $def$\n", - "def", def.substr(second_line_start, second_line_length)); - } -} - -JavaType GetJavaType(FieldDescriptor::Type field_type) { - switch (field_type) { - 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; -} - -string 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 "byte[]"; - case JAVATYPE_ENUM : return "int"; - case JAVATYPE_MESSAGE: return ""; - - // No default because we want the compiler to complain if any new - // JavaTypes are added. - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return ""; -} - -string 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 "byte[]"; - case JAVATYPE_ENUM : return "java.lang.Integer"; - case JAVATYPE_MESSAGE: return ""; - - // No default because we want the compiler to complain if any new - // JavaTypes are added. - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return ""; -} - -string EmptyArrayName(const Params& params, const FieldDescriptor* field) { - switch (GetJavaType(field)) { - case JAVATYPE_INT : return "com.google.protobuf.nano.WireFormatNano.EMPTY_INT_ARRAY"; - case JAVATYPE_LONG : return "com.google.protobuf.nano.WireFormatNano.EMPTY_LONG_ARRAY"; - case JAVATYPE_FLOAT : return "com.google.protobuf.nano.WireFormatNano.EMPTY_FLOAT_ARRAY"; - case JAVATYPE_DOUBLE : return "com.google.protobuf.nano.WireFormatNano.EMPTY_DOUBLE_ARRAY"; - case JAVATYPE_BOOLEAN: return "com.google.protobuf.nano.WireFormatNano.EMPTY_BOOLEAN_ARRAY"; - case JAVATYPE_STRING : return "com.google.protobuf.nano.WireFormatNano.EMPTY_STRING_ARRAY"; - case JAVATYPE_BYTES : return "com.google.protobuf.nano.WireFormatNano.EMPTY_BYTES_ARRAY"; - case JAVATYPE_ENUM : return "com.google.protobuf.nano.WireFormatNano.EMPTY_INT_ARRAY"; - case JAVATYPE_MESSAGE: return ClassName(params, field->message_type()) + ".EMPTY_ARRAY"; - - // No default because we want the compiler to complain if any new - // JavaTypes are added. - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return ""; -} - -string DefaultValue(const Params& params, const FieldDescriptor* field) { - if (field->label() == FieldDescriptor::LABEL_REPEATED) { - return EmptyArrayName(params, field); - } - - if (params.use_reference_types_for_primitives()) { - if (params.reftypes_primitive_enums() - && field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { - return "Integer.MIN_VALUE"; - } - return "null"; - } - - // Switch on cpp_type since we need to know which default_value_* method - // of FieldDescriptor to call. - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32: - return SimpleItoa(field->default_value_int32()); - case FieldDescriptor::CPPTYPE_UINT32: - // Need to print as a signed int since Java has no unsigned. - return SimpleItoa(static_cast<int32>(field->default_value_uint32())); - case FieldDescriptor::CPPTYPE_INT64: - return SimpleItoa(field->default_value_int64()) + "L"; - case FieldDescriptor::CPPTYPE_UINT64: - return SimpleItoa(static_cast<int64>(field->default_value_uint64())) + - "L"; - case FieldDescriptor::CPPTYPE_DOUBLE: { - double value = field->default_value_double(); - if (value == std::numeric_limits<double>::infinity()) { - return "Double.POSITIVE_INFINITY"; - } else if (value == -std::numeric_limits<double>::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<float>::infinity()) { - return "Float.POSITIVE_INFINITY"; - } else if (value == -std::numeric_limits<float>::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 (!field->default_value_string().empty()) { - // Point it to the static final in the generated code. - return FieldDefaultConstantName(field); - } else { - if (field->type() == FieldDescriptor::TYPE_BYTES) { - return "com.google.protobuf.nano.WireFormatNano.EMPTY_BYTES"; - } else { - return "\"\""; - } - } - - case FieldDescriptor::CPPTYPE_ENUM: - return ClassName(params, field->enum_type()) + "." + - RenameJavaKeywords(field->default_value_enum()->name()); - - case FieldDescriptor::CPPTYPE_MESSAGE: - return "null"; - - // No default because we want the compiler to complain if any new - // types are added. - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return ""; -} - - -static const char* kBitMasks[] = { - "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", -}; - -string GetBitFieldName(int index) { - string var_name = "bitField"; - var_name += SimpleItoa(index); - var_name += "_"; - return var_name; -} - -string GetBitFieldNameForBit(int bit_index) { - return GetBitFieldName(bit_index / 32); -} - -string GenerateGetBit(int bit_index) { - string var_name = GetBitFieldNameForBit(bit_index); - int bit_in_var_index = bit_index % 32; - - string mask = kBitMasks[bit_in_var_index]; - string result = "((" + var_name + " & " + mask + ") != 0)"; - return result; -} - -string GenerateSetBit(int bit_index) { - string var_name = GetBitFieldNameForBit(bit_index); - int bit_in_var_index = bit_index % 32; - - string mask = kBitMasks[bit_in_var_index]; - string result = var_name + " |= " + mask; - return result; -} - -string GenerateClearBit(int bit_index) { - string var_name = GetBitFieldNameForBit(bit_index); - int bit_in_var_index = bit_index % 32; - - string mask = kBitMasks[bit_in_var_index]; - string result = var_name + " = (" + var_name + " & ~" + mask + ")"; - return result; -} - -string GenerateDifferentBit(int bit_index) { - string var_name = GetBitFieldNameForBit(bit_index); - int bit_in_var_index = bit_index % 32; - - string mask = kBitMasks[bit_in_var_index]; - string result = "((" + var_name + " & " + mask - + ") != (other." + var_name + " & " + mask + "))"; - return result; -} - -void SetBitOperationVariables(const string name, - int bitIndex, std::map<string, string>* variables) { - (*variables)["get_" + name] = GenerateGetBit(bitIndex); - (*variables)["set_" + name] = GenerateSetBit(bitIndex); - (*variables)["clear_" + name] = GenerateClearBit(bitIndex); - (*variables)["different_" + name] = GenerateDifferentBit(bitIndex); -} - -bool HasMapField(const Descriptor* descriptor) { - for (int i = 0; i < descriptor->field_count(); ++i) { - const FieldDescriptor* field = descriptor->field(i); - if (field->type() == FieldDescriptor::TYPE_MESSAGE && - IsMapEntry(field->message_type())) { - return true; - } - } - return false; -} - -} // namespace javanano -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/src/google/protobuf/compiler/javanano/javanano_helpers.h b/src/google/protobuf/compiler/javanano/javanano_helpers.h deleted file mode 100644 index 04b2d633..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_helpers.h +++ /dev/null @@ -1,199 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_HELPERS_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_HELPERS_H__ - -#include <string> -#include <google/protobuf/compiler/javanano/javanano_params.h> -#include <google/protobuf/descriptor.pb.h> -#include <google/protobuf/descriptor.h> -#include <google/protobuf/io/printer.h> - -namespace google { -namespace protobuf { -namespace compiler { -namespace javanano { - -// Commonly-used separator comments. Thick is a line of '=', thin is a line -// of '-'. -extern const char kThickSeparator[]; -extern const char kThinSeparator[]; - -// Converts the field's name to camel-case, e.g. "foo_bar_baz" becomes -// "fooBarBaz" or "FooBarBaz", respectively. -string UnderscoresToCamelCase(const FieldDescriptor* field); -string UnderscoresToCamelCase(const OneofDescriptor* oneof); -string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field); -string UnderscoresToCapitalizedCamelCase(const OneofDescriptor* oneof); - -// Appends an "_" to the end of a field where the name is a reserved java -// keyword. For example int32 public = 1 will generate int public_. -string RenameJavaKeywords(const string& input); - -// Similar, but for method names. (Typically, this merely has the effect -// of lower-casing the first letter of the name.) -string UnderscoresToCamelCase(const MethodDescriptor* method); - -// Strips ".proto" or ".protodevel" from the end of a filename. -string StripProto(const string& filename); - -// Gets the unqualified class name for the file. Each .proto file becomes a -// single Java class, with all its contents nested in that class. -string FileClassName(const Params& params, const FileDescriptor* file); - -// Returns the file's Java package name. -string FileJavaPackage(const Params& params, const FileDescriptor* file); - -// Returns whether the Java outer class is needed, i.e. whether the option -// java_multiple_files is false, or the proto file contains any file-scope -// enums/extensions. -bool IsOuterClassNeeded(const Params& params, const FileDescriptor* file); - -// Converts the given simple name of a proto entity to its fully-qualified name -// in the Java namespace, given that it is in the given file enclosed in the -// given parent message (or NULL for file-scope entities). Whether the file's -// outer class name should be included in the return value depends on factors -// inferrable from the given arguments, including is_class which indicates -// whether the entity translates to a Java class. -string ToJavaName(const Params& params, const string& name, bool is_class, - const Descriptor* parent, const FileDescriptor* file); - -// These return the fully-qualified class name corresponding to the given -// descriptor. -inline string ClassName(const Params& params, const Descriptor* descriptor) { - return ToJavaName(params, descriptor->name(), true, - descriptor->containing_type(), descriptor->file()); -} -string ClassName(const Params& params, const EnumDescriptor* descriptor); -inline string ClassName(const Params& params, - const ServiceDescriptor* descriptor) { - return ToJavaName(params, descriptor->name(), true, NULL, descriptor->file()); -} -inline string ExtensionIdentifierName(const Params& params, - const FieldDescriptor* descriptor) { - return ToJavaName(params, descriptor->name(), false, - descriptor->extension_scope(), descriptor->file()); -} -string ClassName(const Params& params, const FileDescriptor* descriptor); - -// Get the unqualified name that should be used for a field's field -// number constant. -string FieldConstantName(const FieldDescriptor *field); - -string FieldDefaultConstantName(const FieldDescriptor *field); - -// Print the field's proto-syntax definition as a comment. -void PrintFieldComment(io::Printer* printer, 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(FieldDescriptor::Type field_type); - -inline JavaType GetJavaType(const FieldDescriptor* field) { - return GetJavaType(field->type()); -} - -string 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. -string BoxedPrimitiveTypeName(JavaType type); - -string EmptyArrayName(const Params& params, const FieldDescriptor* field); - -string DefaultValue(const Params& params, const FieldDescriptor* field); - - -// Methods for shared bitfields. - -// Gets the name of the shared bitfield for the given field index. -string GetBitFieldName(int index); - -// Gets the name of the shared bitfield for the given bit index. -// Effectively, GetBitFieldName(bit_index / 32) -string GetBitFieldNameForBit(int bit_index); - -// Generates the java code for the expression that returns whether the bit at -// the given bit index is set. -// Example: "((bitField1_ & 0x04000000) != 0)" -string GenerateGetBit(int bit_index); - -// Generates the java code for the expression that sets the bit at the given -// bit index. -// Example: "bitField1_ |= 0x04000000" -string GenerateSetBit(int bit_index); - -// Generates the java code for the expression that clears the bit at the given -// bit index. -// Example: "bitField1_ = (bitField1_ & ~0x04000000)" -string GenerateClearBit(int bit_index); - -// Generates the java code for the expression that returns whether the bit at -// the given bit index contains different values in the current object and -// another object accessible via the variable 'other'. -// Example: "((bitField1_ & 0x04000000) != (other.bitField1_ & 0x04000000))" -string GenerateDifferentBit(int bit_index); - -// Sets the 'get_*', 'set_*', 'clear_*' and 'different_*' variables, where * is -// the given name of the bit, to the appropriate Java expressions for the given -// bit index. -void SetBitOperationVariables(const string name, - int bitIndex, std::map<string, string>* variables); - -inline bool IsMapEntry(const Descriptor* descriptor) { - // TODO(liujisi): Add an option to turn on maps for proto2 syntax as well. - return descriptor->options().map_entry() && - descriptor->file()->syntax() == FileDescriptor::SYNTAX_PROTO3; -} - -bool HasMapField(const Descriptor* descriptor); - -} // namespace javanano -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_HELPERS_H__ diff --git a/src/google/protobuf/compiler/javanano/javanano_map_field.cc b/src/google/protobuf/compiler/javanano/javanano_map_field.cc deleted file mode 100644 index a4ab8858..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_map_field.cc +++ /dev/null @@ -1,186 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -#include <google/protobuf/compiler/javanano/javanano_map_field.h> -#include <google/protobuf/compiler/javanano/javanano_helpers.h> -#include <google/protobuf/stubs/common.h> -#include <google/protobuf/io/printer.h> -#include <google/protobuf/wire_format.h> -#include <google/protobuf/stubs/strutil.h> - -namespace google { -namespace protobuf { -namespace compiler { -namespace javanano { - -namespace { - -string TypeName(const Params& params, const FieldDescriptor* field, - bool boxed) { - JavaType java_type = GetJavaType(field); - switch (java_type) { - case JAVATYPE_MESSAGE: - return ClassName(params, field->message_type()); - case JAVATYPE_INT: - case JAVATYPE_LONG: - case JAVATYPE_FLOAT: - case JAVATYPE_DOUBLE: - case JAVATYPE_BOOLEAN: - case JAVATYPE_STRING: - case JAVATYPE_BYTES: - case JAVATYPE_ENUM: - if (boxed) { - return BoxedPrimitiveTypeName(java_type); - } else { - return PrimitiveTypeName(java_type); - } - // No default because we want the compiler to complain if any new JavaTypes - // are added.. - } - - GOOGLE_LOG(FATAL) << "should not reach here."; - return ""; -} - -const FieldDescriptor* KeyField(const FieldDescriptor* descriptor) { - GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, descriptor->type()); - const Descriptor* message = descriptor->message_type(); - GOOGLE_CHECK(message->options().map_entry()); - return message->FindFieldByName("key"); -} - -const FieldDescriptor* ValueField(const FieldDescriptor* descriptor) { - GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, descriptor->type()); - const Descriptor* message = descriptor->message_type(); - GOOGLE_CHECK(message->options().map_entry()); - return message->FindFieldByName("value"); -} - -void SetMapVariables(const Params& params, - const FieldDescriptor* descriptor, std::map<string, string>* variables) { - const FieldDescriptor* key = KeyField(descriptor); - const FieldDescriptor* value = ValueField(descriptor); - (*variables)["name"] = - RenameJavaKeywords(UnderscoresToCamelCase(descriptor)); - (*variables)["number"] = SimpleItoa(descriptor->number()); - (*variables)["key_type"] = TypeName(params, key, false); - (*variables)["boxed_key_type"] = TypeName(params,key, true); - (*variables)["key_desc_type"] = - "TYPE_" + ToUpper(FieldDescriptor::TypeName(key->type())); - (*variables)["key_tag"] = SimpleItoa(internal::WireFormat::MakeTag(key)); - (*variables)["value_type"] = TypeName(params, value, false); - (*variables)["boxed_value_type"] = TypeName(params, value, true); - (*variables)["value_desc_type"] = - "TYPE_" + ToUpper(FieldDescriptor::TypeName(value->type())); - (*variables)["value_tag"] = SimpleItoa(internal::WireFormat::MakeTag(value)); - (*variables)["type_parameters"] = - (*variables)["boxed_key_type"] + ", " + (*variables)["boxed_value_type"]; - (*variables)["value_default"] = - value->type() == FieldDescriptor::TYPE_MESSAGE - ? "new " + (*variables)["value_type"] + "()" - : "null"; -} -} // namespace - -// =================================================================== -MapFieldGenerator::MapFieldGenerator(const FieldDescriptor* descriptor, - const Params& params) - : FieldGenerator(params), descriptor_(descriptor) { - SetMapVariables(params, descriptor, &variables_); -} - -MapFieldGenerator::~MapFieldGenerator() {} - -void MapFieldGenerator:: -GenerateMembers(io::Printer* printer, bool /* unused lazy_init */) const { - printer->Print(variables_, - "public java.util.Map<$type_parameters$> $name$;\n"); -} - -void MapFieldGenerator:: -GenerateClearCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$ = null;\n"); -} - -void MapFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, - "this.$name$ = com.google.protobuf.nano.InternalNano.mergeMapEntry(\n" - " input, this.$name$, mapFactory,\n" - " com.google.protobuf.nano.InternalNano.$key_desc_type$,\n" - " com.google.protobuf.nano.InternalNano.$value_desc_type$,\n" - " $value_default$,\n" - " $key_tag$, $value_tag$);\n" - "\n"); -} - -void MapFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if (this.$name$ != null) {\n" - " com.google.protobuf.nano.InternalNano.serializeMapField(\n" - " output, this.$name$, $number$,\n" - " com.google.protobuf.nano.InternalNano.$key_desc_type$,\n" - " com.google.protobuf.nano.InternalNano.$value_desc_type$);\n" - "}\n"); -} - -void MapFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if (this.$name$ != null) {\n" - " size += com.google.protobuf.nano.InternalNano.computeMapFieldSize(\n" - " this.$name$, $number$,\n" - " com.google.protobuf.nano.InternalNano.$key_desc_type$,\n" - " com.google.protobuf.nano.InternalNano.$value_desc_type$);\n" - "}\n"); -} - -void MapFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!com.google.protobuf.nano.InternalNano.equals(\n" - " this.$name$, other.$name$)) {\n" - " return false;\n" - "}\n"); -} - -void MapFieldGenerator:: -GenerateHashCodeCode(io::Printer* printer) const { - printer->Print(variables_, - "result = 31 * result +\n" - " com.google.protobuf.nano.InternalNano.hashCode(this.$name$);\n"); -} - -} // namespace javanano -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/src/google/protobuf/compiler/javanano/javanano_map_field.h b/src/google/protobuf/compiler/javanano/javanano_map_field.h deleted file mode 100644 index 81e5915d..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_map_field.h +++ /dev/null @@ -1,70 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_MAP_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_MAP_FIELD_H__ - -#include <map> -#include <string> -#include <vector> -#include <google/protobuf/compiler/javanano/javanano_field.h> - -namespace google { -namespace protobuf { -namespace compiler { -namespace javanano { - -class MapFieldGenerator : public FieldGenerator { - public: - explicit MapFieldGenerator( - const FieldDescriptor* descriptor, const Params& params); - ~MapFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GenerateMembers(io::Printer* printer, bool lazy_init) const; - void GenerateClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCodeCode(io::Printer* printer) const; - - private: - const FieldDescriptor* descriptor_; - std::map<string, string> variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldGenerator); -}; - -} // namespace javanano -} // namespace compiler -} // namespace protobuf -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_MAP_FIELD_H__ diff --git a/src/google/protobuf/compiler/javanano/javanano_message.cc b/src/google/protobuf/compiler/javanano/javanano_message.cc deleted file mode 100644 index e849521b..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_message.cc +++ /dev/null @@ -1,676 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include <algorithm> -#include <google/protobuf/stubs/hash.h> -#include <google/protobuf/compiler/javanano/javanano_message.h> -#include <google/protobuf/compiler/javanano/javanano_enum.h> -#include <google/protobuf/compiler/javanano/javanano_extension.h> -#include <google/protobuf/compiler/javanano/javanano_helpers.h> -#include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/io/printer.h> -#include <google/protobuf/io/coded_stream.h> -#include <google/protobuf/wire_format.h> -#include <google/protobuf/descriptor.pb.h> - -namespace google { -namespace protobuf { -namespace compiler { -namespace javanano { - -using internal::WireFormat; -using internal::WireFormatLite; - -namespace { - -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. -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; -} - -} // namespace - -// =================================================================== - -MessageGenerator::MessageGenerator(const Descriptor* descriptor, const Params& params) - : params_(params), - descriptor_(descriptor), - field_generators_(descriptor, params) { -} - -MessageGenerator::~MessageGenerator() {} - -void MessageGenerator::GenerateStaticVariables(io::Printer* printer) { - // Generate static members for all nested types. - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - // TODO(kenton): Reuse MessageGenerator objects? - if (IsMapEntry(descriptor_->nested_type(i))) continue; - MessageGenerator(descriptor_->nested_type(i), params_) - .GenerateStaticVariables(printer); - } -} - -void MessageGenerator::GenerateStaticVariableInitializers( - io::Printer* printer) { - // Generate static member initializers for all nested types. - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - // TODO(kenton): Reuse MessageGenerator objects? - if (IsMapEntry(descriptor_->nested_type(i))) continue; - MessageGenerator(descriptor_->nested_type(i), params_) - .GenerateStaticVariableInitializers(printer); - } -} - -void MessageGenerator::Generate(io::Printer* printer) { - if (!params_.store_unknown_fields() && - (descriptor_->extension_count() != 0 || descriptor_->extension_range_count() != 0)) { - GOOGLE_LOG(FATAL) << "Extensions are only supported in NANO_RUNTIME if the " - "'store_unknown_fields' generator option is 'true'\n"; - } - - const string& file_name = descriptor_->file()->name(); - bool is_own_file = - params_.java_multiple_files(file_name) - && descriptor_->containing_type() == NULL; - - if (is_own_file) { - // Note: constants (from enums and fields requiring stored defaults, emitted in the loop below) - // may have the same names as constants in the nested classes. This causes Java warnings, but - // is not fatal, so we suppress those warnings here in the top-most class declaration. - printer->Print( - "\n" - "@SuppressWarnings(\"hiding\")\n" - "public final class $classname$ extends\n", - "classname", descriptor_->name()); - } else { - printer->Print( - "\n" - "public static final class $classname$ extends\n", - "classname", descriptor_->name()); - } - if (params_.store_unknown_fields() && params_.parcelable_messages()) { - printer->Print( - " com.google.protobuf.nano.android.ParcelableExtendableMessageNano<$classname$>", - "classname", descriptor_->name()); - } else if (params_.store_unknown_fields()) { - printer->Print( - " com.google.protobuf.nano.ExtendableMessageNano<$classname$>", - "classname", descriptor_->name()); - } else if (params_.parcelable_messages()) { - printer->Print( - " com.google.protobuf.nano.android.ParcelableMessageNano"); - } else { - printer->Print( - " com.google.protobuf.nano.MessageNano"); - } - if (params_.generate_clone()) { - printer->Print(" implements java.lang.Cloneable {\n"); - } else { - printer->Print(" {\n"); - } - printer->Indent(); - - if (params_.parcelable_messages()) { - printer->Print( - "\n" - "// Used by Parcelable\n" - "@SuppressWarnings({\"unused\"})\n" - "public static final android.os.Parcelable.Creator<$classname$> CREATOR =\n" - " new com.google.protobuf.nano.android.ParcelableMessageNanoCreator<\n" - " $classname$>($classname$.class);\n", - "classname", descriptor_->name()); - } - - // Nested types and extensions - for (int i = 0; i < descriptor_->extension_count(); i++) { - ExtensionGenerator(descriptor_->extension(i), params_).Generate(printer); - } - - for (int i = 0; i < descriptor_->enum_type_count(); i++) { - EnumGenerator(descriptor_->enum_type(i), params_).Generate(printer); - } - - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - if (IsMapEntry(descriptor_->nested_type(i))) continue; - MessageGenerator(descriptor_->nested_type(i), params_).Generate(printer); - } - - // oneof - std::map<string, string> vars; - vars["message_name"] = descriptor_->name(); - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - const OneofDescriptor* oneof_desc = descriptor_->oneof_decl(i); - vars["oneof_name"] = UnderscoresToCamelCase(oneof_desc); - vars["oneof_capitalized_name"] = - UnderscoresToCapitalizedCamelCase(oneof_desc); - vars["oneof_index"] = SimpleItoa(oneof_desc->index()); - // Oneof Constants - for (int j = 0; j < oneof_desc->field_count(); j++) { - const FieldDescriptor* field = oneof_desc->field(j); - vars["number"] = SimpleItoa(field->number()); - vars["cap_field_name"] = ToUpper(field->name()); - printer->Print(vars, - "public static final int $cap_field_name$_FIELD_NUMBER = $number$;\n"); - } - // oneofCase_ and oneof_ - printer->Print(vars, - "private int $oneof_name$Case_ = 0;\n" - "private java.lang.Object $oneof_name$_;\n"); - printer->Print(vars, - "public int get$oneof_capitalized_name$Case() {\n" - " return this.$oneof_name$Case_;\n" - "}\n"); - // Oneof clear - printer->Print(vars, - "public $message_name$ clear$oneof_capitalized_name$() {\n" - " this.$oneof_name$Case_ = 0;\n" - " this.$oneof_name$_ = null;\n" - " return this;\n" - "}\n"); - } - - // Lazy initialization of otherwise static final fields can help prevent the - // class initializer from being generated. We want to prevent it because it - // stops ProGuard from inlining any methods in this class into call sites and - // therefore reducing the method count. However, extensions are best kept as - // public static final fields with initializers, so with their existence we - // won't bother with lazy initialization. - bool lazy_init = descriptor_->extension_count() == 0; - - // Empty array - if (lazy_init) { - printer->Print( - "\n" - "private static volatile $classname$[] _emptyArray;\n" - "public static $classname$[] emptyArray() {\n" - " // Lazily initializes the empty array\n" - " if (_emptyArray == null) {\n" - " synchronized (\n" - " com.google.protobuf.nano.InternalNano.LAZY_INIT_LOCK) {\n" - " if (_emptyArray == null) {\n" - " _emptyArray = new $classname$[0];\n" - " }\n" - " }\n" - " }\n" - " return _emptyArray;\n" - "}\n", - "classname", descriptor_->name()); - } else { - printer->Print( - "\n" - "private static final $classname$[] EMPTY_ARRAY = {};\n" - "public static $classname$[] emptyArray() {\n" - " return EMPTY_ARRAY;\n" - "}\n", - "classname", descriptor_->name()); - } - - // Integers for bit fields - int totalInts = (field_generators_.total_bits() + 31) / 32; - if (totalInts > 0) { - printer->Print("\n"); - for (int i = 0; i < totalInts; i++) { - printer->Print("private int $bit_field_name$;\n", - "bit_field_name", GetBitFieldName(i)); - } - } - - // Fields and maybe their default values - for (int i = 0; i < descriptor_->field_count(); i++) { - printer->Print("\n"); - PrintFieldComment(printer, descriptor_->field(i)); - field_generators_.get(descriptor_->field(i)).GenerateMembers( - printer, lazy_init); - } - - // Constructor, with lazy init code if needed - if (lazy_init && field_generators_.saved_defaults_needed()) { - printer->Print( - "\n" - "private static volatile boolean _classInitialized;\n" - "\n" - "public $classname$() {\n" - " // Lazily initializes the field defaults\n" - " if (!_classInitialized) {\n" - " synchronized (\n" - " com.google.protobuf.nano.InternalNano.LAZY_INIT_LOCK) {\n" - " if (!_classInitialized) {\n", - "classname", descriptor_->name()); - printer->Indent(); - printer->Indent(); - printer->Indent(); - printer->Indent(); - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(descriptor_->field(i)) - .GenerateInitSavedDefaultCode(printer); - } - printer->Outdent(); - printer->Outdent(); - printer->Outdent(); - printer->Outdent(); - printer->Print( - " _classInitialized = true;\n" - " }\n" - " }\n" - " }\n"); - if (params_.generate_clear()) { - printer->Print(" clear();\n"); - } - printer->Print("}\n"); - } else { - printer->Print( - "\n" - "public $classname$() {\n", - "classname", descriptor_->name()); - if (params_.generate_clear()) { - printer->Print(" clear();\n"); - } else { - printer->Indent(); - GenerateFieldInitializers(printer); - printer->Outdent(); - } - printer->Print("}\n"); - } - - // Other methods in this class - - GenerateClear(printer); - - if (params_.generate_clone()) { - GenerateClone(printer); - } - - if (params_.generate_equals()) { - GenerateEquals(printer); - GenerateHashCode(printer); - } - - GenerateMessageSerializationMethods(printer); - GenerateMergeFromMethods(printer); - GenerateParseFromMethods(printer); - - printer->Outdent(); - printer->Print("}\n"); -} - -// =================================================================== - -void MessageGenerator:: -GenerateMessageSerializationMethods(io::Printer* printer) { - // Rely on the parent implementations of writeTo() and getSerializedSize() - // if there are no fields to serialize in this message. - if (descriptor_->field_count() == 0) { - return; - } - - std::unique_ptr<const FieldDescriptor*[]> sorted_fields( - SortFieldsByNumber(descriptor_)); - - printer->Print( - "\n" - "@Override\n" - "public void writeTo(com.google.protobuf.nano.CodedOutputByteBufferNano output)\n" - " throws java.io.IOException {\n"); - printer->Indent(); - - // Output the fields in sorted order - for (int i = 0; i < descriptor_->field_count(); i++) { - GenerateSerializeOneField(printer, sorted_fields[i]); - } - - // The parent implementation will write any unknown fields if necessary. - printer->Print( - "super.writeTo(output);\n"); - - printer->Outdent(); - printer->Print("}\n"); - - // The parent implementation will get the serialized size for unknown - // fields if necessary. - printer->Print( - "\n" - "@Override\n" - "protected int computeSerializedSize() {\n" - " int size = super.computeSerializedSize();\n"); - printer->Indent(); - - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(sorted_fields[i]).GenerateSerializedSizeCode(printer); - } - - printer->Outdent(); - printer->Print( - " return size;\n" - "}\n"); -} - -void MessageGenerator::GenerateMergeFromMethods(io::Printer* printer) { - std::unique_ptr<const FieldDescriptor*[]> sorted_fields( - SortFieldsByNumber(descriptor_)); - - printer->Print( - "\n" - "@Override\n" - "public $classname$ mergeFrom(\n" - " com.google.protobuf.nano.CodedInputByteBufferNano input)\n" - " throws java.io.IOException {\n", - "classname", descriptor_->name()); - - printer->Indent(); - if (HasMapField(descriptor_)) { - printer->Print( - "com.google.protobuf.nano.MapFactories.MapFactory mapFactory =\n" - " com.google.protobuf.nano.MapFactories.getMapFactory();\n"); - } - - printer->Print( - "while (true) {\n"); - printer->Indent(); - - printer->Print( - "int tag = input.readTag();\n" - "switch (tag) {\n"); - printer->Indent(); - - printer->Print( - "case 0:\n" // zero signals EOF / limit reached - " return this;\n" - "default: {\n"); - - printer->Indent(); - if (params_.store_unknown_fields()) { - printer->Print( - "if (!storeUnknownField(input, tag)) {\n" - " return this;\n" - "}\n"); - } else { - printer->Print( - "if (!com.google.protobuf.nano.WireFormatNano.parseUnknownField(input, tag)) {\n" - " return this;\n" // it's an endgroup tag - "}\n"); - } - printer->Print("break;\n"); - printer->Outdent(); - printer->Print("}\n"); - - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = sorted_fields[i]; - uint32 tag = WireFormatLite::MakeTag(field->number(), - WireFormat::WireTypeForFieldType(field->type())); - - printer->Print( - "case $tag$: {\n", - "tag", SimpleItoa(tag)); - printer->Indent(); - - field_generators_.get(field).GenerateMergingCode(printer); - - printer->Outdent(); - printer->Print( - " break;\n" - "}\n"); - - if (field->is_packable()) { - // To make packed = true wire compatible, we generate parsing code from a - // packed version of this field regardless of field->options().packed(). - uint32 packed_tag = WireFormatLite::MakeTag(field->number(), - WireFormatLite::WIRETYPE_LENGTH_DELIMITED); - printer->Print( - "case $tag$: {\n", - "tag", SimpleItoa(packed_tag)); - printer->Indent(); - - field_generators_.get(field).GenerateMergingCodeFromPacked(printer); - - printer->Outdent(); - printer->Print( - " break;\n" - "}\n"); - } - } - - printer->Outdent(); - printer->Outdent(); - printer->Outdent(); - printer->Print( - " }\n" // switch (tag) - " }\n" // while (true) - "}\n"); -} - -void MessageGenerator:: -GenerateParseFromMethods(io::Printer* printer) { - // Note: These are separate from GenerateMessageSerializationMethods() - // because they need to be generated even for messages that are optimized - // for code size. - printer->Print( - "\n" - "public static $classname$ parseFrom(byte[] data)\n" - " throws com.google.protobuf.nano.InvalidProtocolBufferNanoException {\n" - " return com.google.protobuf.nano.MessageNano.mergeFrom(new $classname$(), data);\n" - "}\n" - "\n" - "public static $classname$ parseFrom(\n" - " com.google.protobuf.nano.CodedInputByteBufferNano input)\n" - " throws java.io.IOException {\n" - " return new $classname$().mergeFrom(input);\n" - "}\n", - "classname", descriptor_->name()); -} - -void MessageGenerator::GenerateSerializeOneField( - io::Printer* printer, const FieldDescriptor* field) { - field_generators_.get(field).GenerateSerializationCode(printer); -} - -void MessageGenerator::GenerateClear(io::Printer* printer) { - if (!params_.generate_clear()) { - return; - } - printer->Print( - "\n" - "public $classname$ clear() {\n", - "classname", descriptor_->name()); - printer->Indent(); - - GenerateFieldInitializers(printer); - - printer->Outdent(); - printer->Print( - " return this;\n" - "}\n"); -} - -void MessageGenerator::GenerateFieldInitializers(io::Printer* printer) { - // Clear bit fields. - int totalInts = (field_generators_.total_bits() + 31) / 32; - for (int i = 0; i < totalInts; i++) { - printer->Print("$bit_field_name$ = 0;\n", - "bit_field_name", GetBitFieldName(i)); - } - - // Call clear for all of the fields. - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - field_generators_.get(field).GenerateClearCode(printer); - } - - // Clear oneofs. - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "clear$oneof_capitalized_name$();\n", - "oneof_capitalized_name", UnderscoresToCapitalizedCamelCase( - descriptor_->oneof_decl(i))); - } - - // Clear unknown fields. - if (params_.store_unknown_fields()) { - printer->Print("unknownFieldData = null;\n"); - } - printer->Print("cachedSize = -1;\n"); -} - -void MessageGenerator::GenerateClone(io::Printer* printer) { - printer->Print( - "@Override\n" - "public $classname$ clone() {\n", - "classname", descriptor_->name()); - printer->Indent(); - - printer->Print( - "$classname$ cloned;\n" - "try {\n" - " cloned = ($classname$) super.clone();\n" - "} catch (java.lang.CloneNotSupportedException e) {\n" - " throw new java.lang.AssertionError(e);\n" - "}\n", - "classname", descriptor_->name()); - - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(descriptor_->field(i)).GenerateFixClonedCode(printer); - } - - printer->Outdent(); - printer->Print( - " return cloned;\n" - "}\n" - "\n"); -} - -void MessageGenerator::GenerateEquals(io::Printer* printer) { - // Don't override if there are no fields. We could generate an - // equals method that compares types, but often empty messages - // are used as namespaces. - if (descriptor_->field_count() == 0 && !params_.store_unknown_fields()) { - return; - } - - printer->Print( - "\n" - "@Override\n" - "public boolean equals(Object o) {\n"); - printer->Indent(); - printer->Print( - "if (o == this) {\n" - " return true;\n" - "}\n" - "if (!(o instanceof $classname$)) {\n" - " return false;\n" - "}\n" - "$classname$ other = ($classname$) o;\n", - "classname", descriptor_->name()); - - // Checking oneof case before checking each oneof field. - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - const OneofDescriptor* oneof_desc = descriptor_->oneof_decl(i); - printer->Print( - "if (this.$oneof_name$Case_ != other.$oneof_name$Case_) {\n" - " return false;\n" - "}\n", - "oneof_name", UnderscoresToCamelCase(oneof_desc)); - } - - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - field_generators_.get(field).GenerateEqualsCode(printer); - } - - if (params_.store_unknown_fields()) { - printer->Print( - "if (unknownFieldData == null || unknownFieldData.isEmpty()) {\n" - " return other.unknownFieldData == null || other.unknownFieldData.isEmpty();\n" - "} else {\n" - " return unknownFieldData.equals(other.unknownFieldData);\n" - "}"); - } else { - printer->Print( - "return true;\n"); - } - - printer->Outdent(); - printer->Print("}\n"); -} - -void MessageGenerator::GenerateHashCode(io::Printer* printer) { - if (descriptor_->field_count() == 0 && !params_.store_unknown_fields()) { - return; - } - - printer->Print( - "\n" - "@Override\n" - "public int hashCode() {\n"); - printer->Indent(); - - printer->Print("int result = 17;\n"); - printer->Print("result = 31 * result + getClass().getName().hashCode();\n"); - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - field_generators_.get(field).GenerateHashCodeCode(printer); - } - - if (params_.store_unknown_fields()) { - printer->Print( - "result = 31 * result + \n" - " (unknownFieldData == null || unknownFieldData.isEmpty() ? 0 : \n" - " unknownFieldData.hashCode());\n"); - } - - printer->Print("return result;\n"); - - printer->Outdent(); - printer->Print("}\n"); -} - -// =================================================================== - -} // namespace javanano -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/src/google/protobuf/compiler/javanano/javanano_message.h b/src/google/protobuf/compiler/javanano/javanano_message.h deleted file mode 100644 index 281ec64f..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_message.h +++ /dev/null @@ -1,97 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_MESSAGE_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_MESSAGE_H__ - -#include <string> -#include <google/protobuf/compiler/javanano/javanano_helpers.h> -#include <google/protobuf/compiler/javanano/javanano_field.h> -#include <google/protobuf/compiler/javanano/javanano_params.h> -#include <google/protobuf/stubs/common.h> - -namespace google { -namespace protobuf { - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace javanano { - -class MessageGenerator { - public: - explicit MessageGenerator(const Descriptor* descriptor, const Params& params); - ~MessageGenerator(); - - // All static variables have to be declared at the top-level of the file - // so that we can control initialization order, which is important for - // DescriptorProto bootstrapping to work. - void GenerateStaticVariables(io::Printer* printer); - - // Output code which initializes the static variables generated by - // GenerateStaticVariables(). - void GenerateStaticVariableInitializers(io::Printer* printer); - - // Generate the class itself. - void Generate(io::Printer* printer); - - private: - void GenerateMessageSerializationMethods(io::Printer* printer); - void GenerateMergeFromMethods(io::Printer* printer); - void GenerateParseFromMethods(io::Printer* printer); - void GenerateSerializeOneField(io::Printer* printer, - const FieldDescriptor* field); - - void GenerateClear(io::Printer* printer); - void GenerateFieldInitializers(io::Printer* printer); - void GenerateEquals(io::Printer* printer); - void GenerateHashCode(io::Printer* printer); - void GenerateClone(io::Printer* printer); - - const Params& params_; - const Descriptor* descriptor_; - FieldGeneratorMap field_generators_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator); -}; - -} // namespace javanano -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_MESSAGE_H__ diff --git a/src/google/protobuf/compiler/javanano/javanano_message_field.cc b/src/google/protobuf/compiler/javanano/javanano_message_field.cc deleted file mode 100644 index 2ed8a3aa..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_message_field.cc +++ /dev/null @@ -1,363 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include <map> -#include <string> - -#include <google/protobuf/compiler/javanano/javanano_message_field.h> -#include <google/protobuf/compiler/javanano/javanano_helpers.h> -#include <google/protobuf/io/printer.h> -#include <google/protobuf/wire_format.h> -#include <google/protobuf/stubs/strutil.h> - -namespace google { -namespace protobuf { -namespace compiler { -namespace javanano { - -using internal::WireFormat; -using internal::WireFormatLite; - -namespace { - -// TODO(kenton): Factor out a "SetCommonFieldVariables()" to get rid of -// repeat code between this and the other field types. -void SetMessageVariables(const Params& params, - const FieldDescriptor* descriptor, std::map<string, string>* variables) { - (*variables)["name"] = - RenameJavaKeywords(UnderscoresToCamelCase(descriptor)); - (*variables)["capitalized_name"] = - RenameJavaKeywords(UnderscoresToCapitalizedCamelCase(descriptor)); - (*variables)["number"] = SimpleItoa(descriptor->number()); - (*variables)["type"] = ClassName(params, descriptor->message_type()); - (*variables)["group_or_message"] = - (descriptor->type() == FieldDescriptor::TYPE_GROUP) ? - "Group" : "Message"; - (*variables)["message_name"] = descriptor->containing_type()->name(); - //(*variables)["message_type"] = descriptor->message_type()->name(); - (*variables)["tag"] = SimpleItoa(WireFormat::MakeTag(descriptor)); -} - -} // namespace - -// =================================================================== - -MessageFieldGenerator:: -MessageFieldGenerator(const FieldDescriptor* descriptor, const Params& params) - : FieldGenerator(params), descriptor_(descriptor) { - SetMessageVariables(params, descriptor, &variables_); -} - -MessageFieldGenerator::~MessageFieldGenerator() {} - -void MessageFieldGenerator:: -GenerateMembers(io::Printer* printer, bool /* unused lazy_init */) const { - printer->Print(variables_, - "public $type$ $name$;\n"); -} - -void MessageFieldGenerator:: -GenerateClearCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$ = null;\n"); -} - -void MessageFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (this.$name$ == null) {\n" - " this.$name$ = new $type$();\n" - "}\n"); - - if (descriptor_->type() == FieldDescriptor::TYPE_GROUP) { - printer->Print(variables_, - "input.readGroup(this.$name$, $number$);\n"); - } else { - printer->Print(variables_, - "input.readMessage(this.$name$);\n"); - } -} - -void MessageFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if (this.$name$ != null) {\n" - " output.write$group_or_message$($number$, this.$name$);\n" - "}\n"); -} - -void MessageFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if (this.$name$ != null) {\n" - " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n" - " .compute$group_or_message$Size($number$, this.$name$);\n" - "}\n"); -} - -void MessageFieldGenerator:: -GenerateFixClonedCode(io::Printer* printer) const { - printer->Print(variables_, - "if (this.$name$ != null) {\n" - " cloned.$name$ = this.$name$.clone();\n" - "}\n"); -} - -void MessageFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "if (this.$name$ == null) { \n" - " if (other.$name$ != null) {\n" - " return false;\n" - " }\n" - "} else {\n" - " if (!this.$name$.equals(other.$name$)) {\n" - " return false;\n" - " }\n" - "}\n"); -} - -void MessageFieldGenerator:: -GenerateHashCodeCode(io::Printer* printer) const { - printer->Print(variables_, - "result = 31 * result +\n" - " (this.$name$ == null ? 0 : this.$name$.hashCode());\n"); -} -// =================================================================== - -MessageOneofFieldGenerator::MessageOneofFieldGenerator( - const FieldDescriptor* descriptor, const Params& params) - : FieldGenerator(params), descriptor_(descriptor) { - SetMessageVariables(params, descriptor, &variables_); - SetCommonOneofVariables(descriptor, &variables_); -} - -MessageOneofFieldGenerator::~MessageOneofFieldGenerator() {} - -void MessageOneofFieldGenerator:: -GenerateMembers(io::Printer* printer, bool /* unused lazy_init */) const { - printer->Print(variables_, - "public boolean has$capitalized_name$() {\n" - " return $has_oneof_case$;\n" - "}\n" - "public $type$ get$capitalized_name$() {\n" - " if ($has_oneof_case$) {\n" - " return ($type$) this.$oneof_name$_;\n" - " }\n" - " return null;\n" - "}\n" - "public $message_name$ set$capitalized_name$($type$ value) {\n" - " if (value == null) { throw new java.lang.NullPointerException(); }\n" - " $set_oneof_case$;\n" - " this.$oneof_name$_ = value;\n" - " return this;\n" - "}\n"); -} - -void MessageOneofFieldGenerator:: -GenerateClearCode(io::Printer* printer) const { - // No clear method for oneof fields. -} - -void MessageOneofFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!($has_oneof_case$)) {\n" - " this.$oneof_name$_ = new $type$();\n" - "}\n" - "input.readMessage(\n" - " (com.google.protobuf.nano.MessageNano) this.$oneof_name$_);\n" - "$set_oneof_case$;\n"); -} - -void MessageOneofFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case$) {\n" - " output.writeMessage($number$,\n" - " (com.google.protobuf.nano.MessageNano) this.$oneof_name$_);\n" - "}\n"); -} - -void MessageOneofFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case$) {\n" - " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n" - " .computeMessageSize($number$,\n" - " (com.google.protobuf.nano.MessageNano) this.$oneof_name$_);\n" - "}\n"); -} - -void MessageOneofFieldGenerator:: -GenerateFixClonedCode(io::Printer* printer) const { - printer->Print(variables_, - "if (this.$oneof_name$ != null) {\n" - " cloned.$oneof_name$ = this.$oneof_name$.clone();\n" - "}\n"); -} - -void MessageOneofFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - GenerateOneofFieldEquals(descriptor_, variables_, printer); -} - -void MessageOneofFieldGenerator:: -GenerateHashCodeCode(io::Printer* printer) const { - GenerateOneofFieldHashCode(descriptor_, variables_, printer); -} - -// =================================================================== - -RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator( - const FieldDescriptor* descriptor, const Params& params) - : FieldGenerator(params), descriptor_(descriptor) { - SetMessageVariables(params, descriptor, &variables_); -} - -RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() {} - -void RepeatedMessageFieldGenerator:: -GenerateMembers(io::Printer* printer, bool /* unused lazy_init */) const { - printer->Print(variables_, - "public $type$[] $name$;\n"); -} - -void RepeatedMessageFieldGenerator:: -GenerateClearCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$ = $type$.emptyArray();\n"); -} - -void RepeatedMessageFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - // First, figure out the length of the array, then parse. - printer->Print(variables_, - "int arrayLength = com.google.protobuf.nano.WireFormatNano\n" - " .getRepeatedFieldArrayLength(input, $tag$);\n" - "int i = this.$name$ == null ? 0 : this.$name$.length;\n" - "$type$[] newArray =\n" - " new $type$[i + arrayLength];\n" - "if (i != 0) {\n" - " java.lang.System.arraycopy(this.$name$, 0, newArray, 0, i);\n" - "}\n" - "for (; i < newArray.length - 1; i++) {\n" - " newArray[i] = new $type$();\n"); - - if (descriptor_->type() == FieldDescriptor::TYPE_GROUP) { - printer->Print(variables_, - " input.readGroup(newArray[i], $number$);\n"); - } else { - printer->Print(variables_, - " input.readMessage(newArray[i]);\n"); - } - - printer->Print(variables_, - " input.readTag();\n" - "}\n" - "// Last one without readTag.\n" - "newArray[i] = new $type$();\n"); - - if (descriptor_->type() == FieldDescriptor::TYPE_GROUP) { - printer->Print(variables_, - "input.readGroup(newArray[i], $number$);\n"); - } else { - printer->Print(variables_, - "input.readMessage(newArray[i]);\n"); - } - - printer->Print(variables_, - "this.$name$ = newArray;\n"); -} - -void RepeatedMessageFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if (this.$name$ != null && this.$name$.length > 0) {\n" - " for (int i = 0; i < this.$name$.length; i++) {\n" - " $type$ element = this.$name$[i];\n" - " if (element != null) {\n" - " output.write$group_or_message$($number$, element);\n" - " }\n" - " }\n" - "}\n"); -} - -void RepeatedMessageFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if (this.$name$ != null && this.$name$.length > 0) {\n" - " for (int i = 0; i < this.$name$.length; i++) {\n" - " $type$ element = this.$name$[i];\n" - " if (element != null) {\n" - " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n" - " .compute$group_or_message$Size($number$, element);\n" - " }\n" - " }\n" - "}\n"); -} - -void RepeatedMessageFieldGenerator:: -GenerateFixClonedCode(io::Printer* printer) const { - printer->Print(variables_, - "if (this.$name$ != null && this.$name$.length > 0) {\n" - " cloned.$name$ = new $type$[this.$name$.length];\n" - " for (int i = 0; i < this.$name$.length; i++) {\n" - " if (this.$name$[i] != null) {\n" - " cloned.$name$[i] = this.$name$[i].clone();\n" - " }\n" - " }\n" - "}\n"); -} - -void RepeatedMessageFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!com.google.protobuf.nano.InternalNano.equals(\n" - " this.$name$, other.$name$)) {\n" - " return false;\n" - "}\n"); -} - -void RepeatedMessageFieldGenerator:: -GenerateHashCodeCode(io::Printer* printer) const { - printer->Print(variables_, - "result = 31 * result\n" - " + com.google.protobuf.nano.InternalNano.hashCode(this.$name$);\n"); -} - -} // namespace javanano -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/src/google/protobuf/compiler/javanano/javanano_message_field.h b/src/google/protobuf/compiler/javanano/javanano_message_field.h deleted file mode 100644 index 0ae8879b..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_message_field.h +++ /dev/null @@ -1,121 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_MESSAGE_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_MESSAGE_FIELD_H__ - -#include <map> -#include <string> -#include <google/protobuf/compiler/javanano/javanano_field.h> - -namespace google { -namespace protobuf { -namespace compiler { -namespace javanano { - -class MessageFieldGenerator : public FieldGenerator { - public: - explicit MessageFieldGenerator( - const FieldDescriptor* descriptor, const Params& params); - ~MessageFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GenerateMembers(io::Printer* printer, bool lazy_init) const; - void GenerateClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCodeCode(io::Printer* printer) const; - void GenerateFixClonedCode(io::Printer* printer) const; - - private: - const FieldDescriptor* descriptor_; - std::map<string, string> variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator); -}; - -class MessageOneofFieldGenerator : public FieldGenerator { - public: - explicit MessageOneofFieldGenerator(const FieldDescriptor* descriptor, - const Params& params); - ~MessageOneofFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GenerateMembers(io::Printer* printer, bool lazy_init) const; - void GenerateClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCodeCode(io::Printer* printer) const; - void GenerateFixClonedCode(io::Printer* printer) const; - - private: - const FieldDescriptor* descriptor_; - std::map<string, string> variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageOneofFieldGenerator); -}; - -class RepeatedMessageFieldGenerator : public FieldGenerator { - public: - explicit RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor, - const Params& params); - ~RepeatedMessageFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GenerateMembers(io::Printer* printer, bool lazy_init) const; - void GenerateClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCodeCode(io::Printer* printer) const; - void GenerateFixClonedCode(io::Printer* printer) const; - - private: - const FieldDescriptor* descriptor_; - std::map<string, string> variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator); -}; - -} // namespace javanano -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_MESSAGE_FIELD_H__ diff --git a/src/google/protobuf/compiler/javanano/javanano_params.h b/src/google/protobuf/compiler/javanano/javanano_params.h deleted file mode 100644 index 3594767d..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_params.h +++ /dev/null @@ -1,258 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2010 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: wink@google.com (Wink Saville) - -#ifndef PROTOBUF_COMPILER_JAVANANO_JAVANANO_PARAMS_H_ -#define PROTOBUF_COMPILER_JAVANANO_JAVANANO_PARAMS_H_ - -#include <map> -#include <set> -#include <google/protobuf/stubs/strutil.h> - -namespace google { -namespace protobuf { -namespace compiler { -namespace javanano { - -enum eMultipleFiles { JAVANANO_MUL_UNSET, JAVANANO_MUL_FALSE, JAVANANO_MUL_TRUE }; - -// Parameters for used by the generators -class Params { - public: - typedef std::map<string, string> NameMap; - typedef std::set<string> NameSet; - private: - string empty_; - string base_name_; - eMultipleFiles override_java_multiple_files_; - bool store_unknown_fields_; - NameMap java_packages_; - NameMap java_outer_classnames_; - NameSet java_multiple_files_; - bool generate_has_; - bool java_enum_style_; - bool optional_field_accessors_; - bool use_reference_types_for_primitives_; - bool generate_equals_; - bool ignore_services_; - bool parcelable_messages_; - bool reftypes_primitive_enums_; - bool generate_clear_; - bool generate_clone_; - bool generate_intdefs_; - - public: - Params(const string & base_name) : - empty_(""), - base_name_(base_name), - override_java_multiple_files_(JAVANANO_MUL_UNSET), - store_unknown_fields_(false), - generate_has_(false), - java_enum_style_(false), - optional_field_accessors_(false), - use_reference_types_for_primitives_(false), - generate_equals_(false), - ignore_services_(false), - parcelable_messages_(false), - reftypes_primitive_enums_(false), - generate_clear_(true), - generate_clone_(false), - generate_intdefs_(false) { - } - - const string& base_name() const { - return base_name_; - } - - bool has_java_package(const string& file_name) const { - return java_packages_.find(file_name) - != java_packages_.end(); - } - void set_java_package(const string& file_name, - const string& java_package) { - java_packages_[file_name] = java_package; - } - const string& java_package(const string& file_name) const { - NameMap::const_iterator itr; - - itr = java_packages_.find(file_name); - if (itr == java_packages_.end()) { - return empty_; - } else { - return itr->second; - } - } - const NameMap& java_packages() { - return java_packages_; - } - - bool has_java_outer_classname(const string& file_name) const { - return java_outer_classnames_.find(file_name) - != java_outer_classnames_.end(); - } - void set_java_outer_classname(const string& file_name, - const string& java_outer_classname) { - java_outer_classnames_[file_name] = java_outer_classname; - } - const string& java_outer_classname(const string& file_name) const { - NameMap::const_iterator itr; - - itr = java_outer_classnames_.find(file_name); - if (itr == java_outer_classnames_.end()) { - return empty_; - } else { - return itr->second; - } - } - const NameMap& java_outer_classnames() { - return java_outer_classnames_; - } - - void set_override_java_multiple_files(bool java_multiple_files) { - if (java_multiple_files) { - override_java_multiple_files_ = JAVANANO_MUL_TRUE; - } else { - override_java_multiple_files_ = JAVANANO_MUL_FALSE; - } - } - void clear_override_java_multiple_files() { - override_java_multiple_files_ = JAVANANO_MUL_UNSET; - } - - void set_java_multiple_files(const string& file_name, bool value) { - if (value) { - java_multiple_files_.insert(file_name); - } else { - java_multiple_files_.erase(file_name); - } - } - bool java_multiple_files(const string& file_name) const { - switch (override_java_multiple_files_) { - case JAVANANO_MUL_FALSE: - return false; - case JAVANANO_MUL_TRUE: - return true; - default: - return java_multiple_files_.find(file_name) - != java_multiple_files_.end(); - } - } - - void set_store_unknown_fields(bool value) { - store_unknown_fields_ = value; - } - bool store_unknown_fields() const { - return store_unknown_fields_; - } - - void set_generate_has(bool value) { - generate_has_ = value; - } - bool generate_has() const { - return generate_has_; - } - - void set_java_enum_style(bool value) { - java_enum_style_ = value; - } - bool java_enum_style() const { - return java_enum_style_; - } - - void set_optional_field_accessors(bool value) { - optional_field_accessors_ = value; - } - bool optional_field_accessors() const { - return optional_field_accessors_; - } - - void set_use_reference_types_for_primitives(bool value) { - use_reference_types_for_primitives_ = value; - } - bool use_reference_types_for_primitives() const { - return use_reference_types_for_primitives_; - } - - void set_generate_equals(bool value) { - generate_equals_ = value; - } - bool generate_equals() const { - return generate_equals_; - } - - void set_ignore_services(bool value) { - ignore_services_ = value; - } - bool ignore_services() const { - return ignore_services_; - } - - void set_parcelable_messages(bool value) { - parcelable_messages_ = value; - } - bool parcelable_messages() const { - return parcelable_messages_; - } - - void set_reftypes_primitive_enums(bool value) { - reftypes_primitive_enums_ = value; - } - bool reftypes_primitive_enums() const { - return reftypes_primitive_enums_; - } - - void set_generate_clear(bool value) { - generate_clear_ = value; - } - bool generate_clear() const { - return generate_clear_; - } - - void set_generate_clone(bool value) { - generate_clone_ = value; - } - bool generate_clone() const { - return generate_clone_; - } - - void set_generate_intdefs(bool value) { - generate_intdefs_ = value; - } - bool generate_intdefs() const { - return generate_intdefs_; - } -}; - -} // namespace javanano -} // namespace compiler -} // namespace protobuf -} // namespace google -#endif // PROTOBUF_COMPILER_JAVANANO_JAVANANO_PARAMS_H_ diff --git a/src/google/protobuf/compiler/javanano/javanano_primitive_field.cc b/src/google/protobuf/compiler/javanano/javanano_primitive_field.cc deleted file mode 100644 index 66a0ff05..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_primitive_field.cc +++ /dev/null @@ -1,968 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include <map> -#include <math.h> -#include <string> - -#include <google/protobuf/compiler/javanano/javanano_primitive_field.h> -#include <google/protobuf/stubs/common.h> -#include <google/protobuf/compiler/javanano/javanano_helpers.h> -#include <google/protobuf/io/printer.h> -#include <google/protobuf/wire_format.h> -#include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/stubs/substitute.h> - -namespace google { -namespace protobuf { -namespace compiler { -namespace javanano { - -using internal::WireFormat; -using internal::WireFormatLite; - -namespace { - -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 false; - 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; -} - -bool IsArrayType(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 false; - case JAVATYPE_BYTES : return true; - case JAVATYPE_ENUM : return false; - case JAVATYPE_MESSAGE: return false; - - // 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) { - 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; -} - -// 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; -} - -bool AllAscii(const string& text) { - for (int i = 0; i < text.size(); i++) { - if ((text[i] & 0x80) != 0) { - return false; - } - } - return true; -} - - -void SetPrimitiveVariables(const FieldDescriptor* descriptor, const Params params, - std::map<string, string>* variables) { - (*variables)["name"] = - RenameJavaKeywords(UnderscoresToCamelCase(descriptor)); - (*variables)["capitalized_name"] = - RenameJavaKeywords(UnderscoresToCapitalizedCamelCase(descriptor)); - (*variables)["number"] = SimpleItoa(descriptor->number()); - if (params.use_reference_types_for_primitives() - && !descriptor->is_repeated()) { - (*variables)["type"] = BoxedPrimitiveTypeName(GetJavaType(descriptor)); - } else { - (*variables)["type"] = PrimitiveTypeName(GetJavaType(descriptor)); - } - // Deals with defaults. For C++-string types (string and bytes), - // we might need to have the generated code do the unicode decoding - // (see comments in InternalNano.java for gory details.). We would - // like to do this once into a static field and re-use that from - // then on. - if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_STRING && - !descriptor->default_value_string().empty() && - !params.use_reference_types_for_primitives()) { - if (descriptor->type() == FieldDescriptor::TYPE_BYTES) { - (*variables)["default"] = DefaultValue(params, descriptor); - (*variables)["default_constant"] = FieldDefaultConstantName(descriptor); - (*variables)["default_constant_value"] = strings::Substitute( - "com.google.protobuf.nano.InternalNano.bytesDefaultValue(\"$0\")", - CEscape(descriptor->default_value_string())); - (*variables)["default_copy_if_needed"] = - (*variables)["default"] + ".clone()"; - } else if (AllAscii(descriptor->default_value_string())) { - // All chars are ASCII. In this case directly referencing a - // CEscape()'d string literal works fine. - (*variables)["default"] = - "\"" + CEscape(descriptor->default_value_string()) + "\""; - (*variables)["default_copy_if_needed"] = (*variables)["default"]; - } else { - // Strings where some chars are non-ASCII. We need to save the - // default value. - (*variables)["default"] = DefaultValue(params, descriptor); - (*variables)["default_constant"] = FieldDefaultConstantName(descriptor); - (*variables)["default_constant_value"] = strings::Substitute( - "com.google.protobuf.nano.InternalNano.stringDefaultValue(\"$0\")", - CEscape(descriptor->default_value_string())); - (*variables)["default_copy_if_needed"] = (*variables)["default"]; - } - } else { - // Non-string, non-bytes field. Defaults are literals. - (*variables)["default"] = DefaultValue(params, descriptor); - (*variables)["default_copy_if_needed"] = (*variables)["default"]; - } - (*variables)["boxed_type"] = BoxedPrimitiveTypeName(GetJavaType(descriptor)); - (*variables)["capitalized_type"] = GetCapitalizedType(descriptor); - (*variables)["tag"] = SimpleItoa(WireFormat::MakeTag(descriptor)); - (*variables)["tag_size"] = SimpleItoa( - WireFormat::TagSize(descriptor->number(), descriptor->type())); - (*variables)["non_packed_tag"] = SimpleItoa( - internal::WireFormatLite::MakeTag(descriptor->number(), - internal::WireFormat::WireTypeForFieldType(descriptor->type()))); - int fixed_size = FixedSize(descriptor->type()); - if (fixed_size != -1) { - (*variables)["fixed_size"] = SimpleItoa(fixed_size); - } - (*variables)["message_name"] = descriptor->containing_type()->name(); - (*variables)["empty_array_name"] = EmptyArrayName(params, descriptor); -} -} // namespace - -// =================================================================== - -PrimitiveFieldGenerator:: -PrimitiveFieldGenerator(const FieldDescriptor* descriptor, const Params& params) - : FieldGenerator(params), descriptor_(descriptor) { - SetPrimitiveVariables(descriptor, params, &variables_); -} - -PrimitiveFieldGenerator::~PrimitiveFieldGenerator() {} - -bool PrimitiveFieldGenerator::SavedDefaultNeeded() const { - return variables_.find("default_constant") != variables_.end(); -} - -void PrimitiveFieldGenerator::GenerateInitSavedDefaultCode(io::Printer* printer) const { - if (variables_.find("default_constant") != variables_.end()) { - printer->Print(variables_, - "$default_constant$ = $default_constant_value$;\n"); - } -} - -void PrimitiveFieldGenerator:: -GenerateMembers(io::Printer* printer, bool lazy_init) const { - if (variables_.find("default_constant") != variables_.end()) { - // Those primitive types that need a saved default. - if (lazy_init) { - printer->Print(variables_, - "private static $type$ $default_constant$;\n"); - } else { - printer->Print(variables_, - "private static final $type$ $default_constant$ =\n" - " $default_constant_value$;\n"); - } - } - - printer->Print(variables_, - "public $type$ $name$;\n"); - - if (params_.generate_has()) { - printer->Print(variables_, - "public boolean has$capitalized_name$;\n"); - } -} - -void PrimitiveFieldGenerator:: -GenerateClearCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$ = $default_copy_if_needed$;\n"); - - if (params_.generate_has()) { - printer->Print(variables_, - "has$capitalized_name$ = false;\n"); - } -} - -void PrimitiveFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, - "this.$name$ = input.read$capitalized_type$();\n"); - - if (params_.generate_has()) { - printer->Print(variables_, - "has$capitalized_name$ = true;\n"); - } -} - -void PrimitiveFieldGenerator:: -GenerateSerializationConditional(io::Printer* printer) const { - if (params_.use_reference_types_for_primitives()) { - // For reference type mode, serialize based on equality - // to null. - printer->Print(variables_, - "if (this.$name$ != null) {\n"); - return; - } - if (params_.generate_has()) { - printer->Print(variables_, - "if (has$capitalized_name$ || "); - } else { - printer->Print(variables_, - "if ("); - } - JavaType java_type = GetJavaType(descriptor_); - if (IsArrayType(java_type)) { - printer->Print(variables_, - "!java.util.Arrays.equals(this.$name$, $default$)) {\n"); - } else if (IsReferenceType(java_type)) { - printer->Print(variables_, - "!this.$name$.equals($default$)) {\n"); - } else if (java_type == JAVATYPE_FLOAT) { - printer->Print(variables_, - "java.lang.Float.floatToIntBits(this.$name$)\n" - " != java.lang.Float.floatToIntBits($default$)) {\n"); - } else if (java_type == JAVATYPE_DOUBLE) { - printer->Print(variables_, - "java.lang.Double.doubleToLongBits(this.$name$)\n" - " != java.lang.Double.doubleToLongBits($default$)) {\n"); - } else { - printer->Print(variables_, - "this.$name$ != $default$) {\n"); - } -} - -void PrimitiveFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - if (descriptor_->is_required() && !params_.generate_has()) { - // Always serialize a required field if we don't have the 'has' signal. - printer->Print(variables_, - "output.write$capitalized_type$($number$, this.$name$);\n"); - } else { - GenerateSerializationConditional(printer); - printer->Print(variables_, - " output.write$capitalized_type$($number$, this.$name$);\n" - "}\n"); - } -} - -void PrimitiveFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - if (descriptor_->is_required() && !params_.generate_has()) { - printer->Print(variables_, - "size += com.google.protobuf.nano.CodedOutputByteBufferNano\n" - " .compute$capitalized_type$Size($number$, this.$name$);\n"); - } else { - GenerateSerializationConditional(printer); - printer->Print(variables_, - " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n" - " .compute$capitalized_type$Size($number$, this.$name$);\n" - "}\n"); - } -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateFixClonedCode(io::Printer* printer) const { - printer->Print(variables_, - "if (this.$name$ != null && this.$name$.length > 0) {\n" - " cloned.$name$ = this.$name$.clone();\n" - "}\n"); -} - -void PrimitiveFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - // We define equality as serialized form equality. If generate_has(), - // then if the field value equals the default value in both messages, - // but one's 'has' field is set and the other's is not, the serialized - // forms are different and we should return false. - JavaType java_type = GetJavaType(descriptor_); - if (java_type == JAVATYPE_BYTES) { - printer->Print(variables_, - "if (!java.util.Arrays.equals(this.$name$, other.$name$)"); - if (params_.generate_has()) { - printer->Print(variables_, - "\n" - " || (java.util.Arrays.equals(this.$name$, $default$)\n" - " && this.has$capitalized_name$ != other.has$capitalized_name$)"); - } - printer->Print(") {\n" - " return false;\n" - "}\n"); - } else if (java_type == JAVATYPE_STRING - || params_.use_reference_types_for_primitives()) { - printer->Print(variables_, - "if (this.$name$ == null) {\n" - " if (other.$name$ != null) {\n" - " return false;\n" - " }\n" - "} else if (!this.$name$.equals(other.$name$)"); - if (params_.generate_has()) { - printer->Print(variables_, - "\n" - " || (this.$name$.equals($default$)\n" - " && this.has$capitalized_name$ != other.has$capitalized_name$)"); - } - printer->Print(") {\n" - " return false;\n" - "}\n"); - } else if (java_type == JAVATYPE_FLOAT) { - printer->Print(variables_, - "{\n" - " int bits = java.lang.Float.floatToIntBits(this.$name$);\n" - " if (bits != java.lang.Float.floatToIntBits(other.$name$)"); - if (params_.generate_has()) { - printer->Print(variables_, - "\n" - " || (bits == java.lang.Float.floatToIntBits($default$)\n" - " && this.has$capitalized_name$ != other.has$capitalized_name$)"); - } - printer->Print(") {\n" - " return false;\n" - " }\n" - "}\n"); - } else if (java_type == JAVATYPE_DOUBLE) { - printer->Print(variables_, - "{\n" - " long bits = java.lang.Double.doubleToLongBits(this.$name$);\n" - " if (bits != java.lang.Double.doubleToLongBits(other.$name$)"); - if (params_.generate_has()) { - printer->Print(variables_, - "\n" - " || (bits == java.lang.Double.doubleToLongBits($default$)\n" - " && this.has$capitalized_name$ != other.has$capitalized_name$)"); - } - printer->Print(") {\n" - " return false;\n" - " }\n" - "}\n"); - } else { - printer->Print(variables_, - "if (this.$name$ != other.$name$"); - if (params_.generate_has()) { - printer->Print(variables_, - "\n" - " || (this.$name$ == $default$\n" - " && this.has$capitalized_name$ != other.has$capitalized_name$)"); - } - printer->Print(") {\n" - " return false;\n" - "}\n"); - } -} - -void PrimitiveFieldGenerator:: -GenerateHashCodeCode(io::Printer* printer) const { - JavaType java_type = GetJavaType(descriptor_); - if (java_type == JAVATYPE_BYTES) { - printer->Print(variables_, - "result = 31 * result + java.util.Arrays.hashCode(this.$name$);\n"); - } else if (java_type == JAVATYPE_STRING - || params_.use_reference_types_for_primitives()) { - printer->Print(variables_, - "result = 31 * result\n" - " + (this.$name$ == null ? 0 : this.$name$.hashCode());\n"); - } else { - switch (java_type) { - // For all Java primitive types below, the hash codes match the - // results of BoxedType.valueOf(primitiveValue).hashCode(). - case JAVATYPE_INT: - printer->Print(variables_, - "result = 31 * result + this.$name$;\n"); - break; - case JAVATYPE_LONG: - printer->Print(variables_, - "result = 31 * result\n" - " + (int) (this.$name$ ^ (this.$name$ >>> 32));\n"); - break; - case JAVATYPE_FLOAT: - printer->Print(variables_, - "result = 31 * result\n" - " + java.lang.Float.floatToIntBits(this.$name$);\n"); - break; - case JAVATYPE_DOUBLE: - printer->Print(variables_, - "{\n" - " long v = java.lang.Double.doubleToLongBits(this.$name$);\n" - " result = 31 * result + (int) (v ^ (v >>> 32));\n" - "}\n"); - break; - case JAVATYPE_BOOLEAN: - printer->Print(variables_, - "result = 31 * result + (this.$name$ ? 1231 : 1237);\n"); - break; - default: - GOOGLE_LOG(ERROR) << "unknown java type for primitive field"; - break; - } - } -} - -// =================================================================== - -AccessorPrimitiveFieldGenerator:: -AccessorPrimitiveFieldGenerator(const FieldDescriptor* descriptor, - const Params& params, int has_bit_index) - : FieldGenerator(params), descriptor_(descriptor) { - SetPrimitiveVariables(descriptor, params, &variables_); - SetBitOperationVariables("has", has_bit_index, &variables_); -} - -AccessorPrimitiveFieldGenerator::~AccessorPrimitiveFieldGenerator() {} - -bool AccessorPrimitiveFieldGenerator::SavedDefaultNeeded() const { - return variables_.find("default_constant") != variables_.end(); -} - -void AccessorPrimitiveFieldGenerator:: -GenerateInitSavedDefaultCode(io::Printer* printer) const { - if (variables_.find("default_constant") != variables_.end()) { - printer->Print(variables_, - "$default_constant$ = $default_constant_value$;\n"); - } -} - -void AccessorPrimitiveFieldGenerator:: -GenerateMembers(io::Printer* printer, bool lazy_init) const { - if (variables_.find("default_constant") != variables_.end()) { - // Those primitive types that need a saved default. - if (lazy_init) { - printer->Print(variables_, - "private static $type$ $default_constant$;\n"); - } else { - printer->Print(variables_, - "private static final $type$ $default_constant$ =\n" - " $default_constant_value$;\n"); - } - } - printer->Print(variables_, - "private $type$ $name$_;\n" - "public $type$ get$capitalized_name$() {\n" - " return $name$_;\n" - "}\n" - "public $message_name$ set$capitalized_name$($type$ value) {\n"); - if (IsReferenceType(GetJavaType(descriptor_))) { - printer->Print(variables_, - " if (value == null) {\n" - " throw new java.lang.NullPointerException();\n" - " }\n"); - } - printer->Print(variables_, - " $name$_ = value;\n" - " $set_has$;\n" - " return this;\n" - "}\n" - "public boolean has$capitalized_name$() {\n" - " return $get_has$;\n" - "}\n" - "public $message_name$ clear$capitalized_name$() {\n" - " $name$_ = $default_copy_if_needed$;\n" - " $clear_has$;\n" - " return this;\n" - "}\n"); -} - -void AccessorPrimitiveFieldGenerator:: -GenerateClearCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_ = $default_copy_if_needed$;\n"); -} - -void AccessorPrimitiveFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_ = input.read$capitalized_type$();\n" - "$set_has$;\n"); -} - -void AccessorPrimitiveFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($get_has$) {\n" - " output.write$capitalized_type$($number$, $name$_);\n" - "}\n"); -} - -void AccessorPrimitiveFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($get_has$) {\n" - " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n" - " .compute$capitalized_type$Size($number$, $name$_);\n" - "}\n"); -} - -void AccessorPrimitiveFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - switch (GetJavaType(descriptor_)) { - // For all Java primitive types below, the equality checks match the - // results of BoxedType.valueOf(primitiveValue).equals(otherValue). - case JAVATYPE_FLOAT: - printer->Print(variables_, - "if ($different_has$\n" - " || java.lang.Float.floatToIntBits($name$_)\n" - " != java.lang.Float.floatToIntBits(other.$name$_)) {\n" - " return false;\n" - "}\n"); - break; - case JAVATYPE_DOUBLE: - printer->Print(variables_, - "if ($different_has$\n" - " || java.lang.Double.doubleToLongBits($name$_)\n" - " != java.lang.Double.doubleToLongBits(other.$name$_)) {\n" - " return false;\n" - "}\n"); - break; - case JAVATYPE_INT: - case JAVATYPE_LONG: - case JAVATYPE_BOOLEAN: - printer->Print(variables_, - "if ($different_has$\n" - " || $name$_ != other.$name$_) {\n" - " return false;\n" - "}\n"); - break; - case JAVATYPE_STRING: - // Accessor style would guarantee $name$_ non-null - printer->Print(variables_, - "if ($different_has$\n" - " || !$name$_.equals(other.$name$_)) {\n" - " return false;\n" - "}\n"); - break; - case JAVATYPE_BYTES: - // Accessor style would guarantee $name$_ non-null - printer->Print(variables_, - "if ($different_has$\n" - " || !java.util.Arrays.equals($name$_, other.$name$_)) {\n" - " return false;\n" - "}\n"); - break; - default: - GOOGLE_LOG(ERROR) << "unknown java type for primitive field"; - break; - } -} - -void AccessorPrimitiveFieldGenerator:: -GenerateHashCodeCode(io::Printer* printer) const { - switch (GetJavaType(descriptor_)) { - // For all Java primitive types below, the hash codes match the - // results of BoxedType.valueOf(primitiveValue).hashCode(). - case JAVATYPE_INT: - printer->Print(variables_, - "result = 31 * result + $name$_;\n"); - break; - case JAVATYPE_LONG: - printer->Print(variables_, - "result = 31 * result + (int) ($name$_ ^ ($name$_ >>> 32));\n"); - break; - case JAVATYPE_FLOAT: - printer->Print(variables_, - "result = 31 * result +\n" - " java.lang.Float.floatToIntBits($name$_);\n"); - break; - case JAVATYPE_DOUBLE: - printer->Print(variables_, - "{\n" - " long v = java.lang.Double.doubleToLongBits($name$_);\n" - " result = 31 * result + (int) (v ^ (v >>> 32));\n" - "}\n"); - break; - case JAVATYPE_BOOLEAN: - printer->Print(variables_, - "result = 31 * result + ($name$_ ? 1231 : 1237);\n"); - break; - case JAVATYPE_STRING: - // Accessor style would guarantee $name$_ non-null - printer->Print(variables_, - "result = 31 * result + $name$_.hashCode();\n"); - break; - case JAVATYPE_BYTES: - // Accessor style would guarantee $name$_ non-null - printer->Print(variables_, - "result = 31 * result + java.util.Arrays.hashCode($name$_);\n"); - break; - default: - GOOGLE_LOG(ERROR) << "unknown java type for primitive field"; - break; - } -} - -// =================================================================== - -PrimitiveOneofFieldGenerator::PrimitiveOneofFieldGenerator( - const FieldDescriptor* descriptor, const Params& params) - : FieldGenerator(params), descriptor_(descriptor) { - SetPrimitiveVariables(descriptor, params, &variables_); - SetCommonOneofVariables(descriptor, &variables_); -} - -PrimitiveOneofFieldGenerator::~PrimitiveOneofFieldGenerator() {} - -void PrimitiveOneofFieldGenerator::GenerateMembers( - io::Printer* printer, bool /*unused lazy_init*/) const { - printer->Print(variables_, - "public boolean has$capitalized_name$() {\n" - " return $has_oneof_case$;\n" - "}\n" - "public $type$ get$capitalized_name$() {\n" - " if ($has_oneof_case$) {\n" - " return ($type$) ($boxed_type$) this.$oneof_name$_;\n" - " }\n" - " return $default$;\n" - "}\n" - "public $message_name$ set$capitalized_name$($type$ value) {\n" - " $set_oneof_case$;\n" - " this.$oneof_name$_ = value;\n" - " return this;\n" - "}\n"); -} - -void PrimitiveOneofFieldGenerator::GenerateClearCode( - io::Printer* printer) const { - // No clear method for oneof fields. -} - -void PrimitiveOneofFieldGenerator::GenerateMergingCode( - io::Printer* printer) const { - printer->Print(variables_, - "this.$oneof_name$_ = input.read$capitalized_type$();\n" - "$set_oneof_case$;\n"); -} - -void PrimitiveOneofFieldGenerator::GenerateSerializationCode( - io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case$) {\n" - " output.write$capitalized_type$(\n" - " $number$, ($boxed_type$) this.$oneof_name$_);\n" - "}\n"); -} - -void PrimitiveOneofFieldGenerator::GenerateSerializedSizeCode( - io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case$) {\n" - " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n" - " .compute$capitalized_type$Size(\n" - " $number$, ($boxed_type$) this.$oneof_name$_);\n" - "}\n"); -} - -void PrimitiveOneofFieldGenerator::GenerateEqualsCode( - io::Printer* printer) const { - GenerateOneofFieldEquals(descriptor_, variables_, printer); -} - -void PrimitiveOneofFieldGenerator::GenerateHashCodeCode( - io::Printer* printer) const { - GenerateOneofFieldHashCode(descriptor_, variables_, printer); -} - -// =================================================================== - -RepeatedPrimitiveFieldGenerator::RepeatedPrimitiveFieldGenerator( - const FieldDescriptor* descriptor, const Params& params) - : FieldGenerator(params), descriptor_(descriptor) { - SetPrimitiveVariables(descriptor, params, &variables_); -} - -RepeatedPrimitiveFieldGenerator::~RepeatedPrimitiveFieldGenerator() {} - -void RepeatedPrimitiveFieldGenerator:: -GenerateMembers(io::Printer* printer, bool /*unused init_defaults*/) const { - printer->Print(variables_, - "public $type$[] $name$;\n"); -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateClearCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$ = $default$;\n"); -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - // First, figure out the length of the array, then parse. - printer->Print(variables_, - "int arrayLength = com.google.protobuf.nano.WireFormatNano\n" - " .getRepeatedFieldArrayLength(input, $non_packed_tag$);\n" - "int i = this.$name$ == null ? 0 : this.$name$.length;\n"); - - if (GetJavaType(descriptor_) == JAVATYPE_BYTES) { - printer->Print(variables_, - "byte[][] newArray = new byte[i + arrayLength][];\n"); - } else { - printer->Print(variables_, - "$type$[] newArray = new $type$[i + arrayLength];\n"); - } - printer->Print(variables_, - "if (i != 0) {\n" - " java.lang.System.arraycopy(this.$name$, 0, newArray, 0, i);\n" - "}\n" - "for (; i < newArray.length - 1; i++) {\n" - " newArray[i] = input.read$capitalized_type$();\n" - " input.readTag();\n" - "}\n" - "// Last one without readTag.\n" - "newArray[i] = input.read$capitalized_type$();\n" - "this.$name$ = newArray;\n"); -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateMergingCodeFromPacked(io::Printer* printer) const { - printer->Print( - "int length = input.readRawVarint32();\n" - "int limit = input.pushLimit(length);\n"); - - // If we know the elements will all be of the same size, the arrayLength - // can be calculated much more easily. However, FixedSize() returns 1 for - // repeated bool fields, which are guaranteed to have the fixed size of - // 1 byte per value only if we control the output. On the wire they can - // legally appear as variable-size integers, so we need to use the slow - // way for repeated bool fields. - if (descriptor_->type() == FieldDescriptor::TYPE_BOOL - || FixedSize(descriptor_->type()) == -1) { - printer->Print(variables_, - "// First pass to compute array length.\n" - "int arrayLength = 0;\n" - "int startPos = input.getPosition();\n" - "while (input.getBytesUntilLimit() > 0) {\n" - " input.read$capitalized_type$();\n" - " arrayLength++;\n" - "}\n" - "input.rewindToPosition(startPos);\n"); - } else { - printer->Print(variables_, - "int arrayLength = length / $fixed_size$;\n"); - } - - printer->Print(variables_, - "int i = this.$name$ == null ? 0 : this.$name$.length;\n" - "$type$[] newArray = new $type$[i + arrayLength];\n" - "if (i != 0) {\n" - " java.lang.System.arraycopy(this.$name$, 0, newArray, 0, i);\n" - "}\n" - "for (; i < newArray.length; i++) {\n" - " newArray[i] = input.read$capitalized_type$();\n" - "}\n" - "this.$name$ = newArray;\n" - "input.popLimit(limit);\n"); -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateRepeatedDataSizeCode(io::Printer* printer) const { - // Creates a variable dataSize and puts the serialized size in there. - // If the element type is a Java reference type, also generates - // dataCount which stores the number of non-null elements in the field. - if (IsReferenceType(GetJavaType(descriptor_))) { - printer->Print(variables_, - "int dataCount = 0;\n" - "int dataSize = 0;\n" - "for (int i = 0; i < this.$name$.length; i++) {\n" - " $type$ element = this.$name$[i];\n" - " if (element != null) {\n" - " dataCount++;\n" - " dataSize += com.google.protobuf.nano.CodedOutputByteBufferNano\n" - " .compute$capitalized_type$SizeNoTag(element);\n" - " }\n" - "}\n"); - } else if (FixedSize(descriptor_->type()) == -1) { - printer->Print(variables_, - "int dataSize = 0;\n" - "for (int i = 0; i < this.$name$.length; i++) {\n" - " $type$ element = this.$name$[i];\n" - " dataSize += com.google.protobuf.nano.CodedOutputByteBufferNano\n" - " .compute$capitalized_type$SizeNoTag(element);\n" - "}\n"); - } else { - printer->Print(variables_, - "int dataSize = $fixed_size$ * this.$name$.length;\n"); - } -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if (this.$name$ != null && this.$name$.length > 0) {\n"); - printer->Indent(); - - if (descriptor_->is_packable() && descriptor_->options().packed()) { - GenerateRepeatedDataSizeCode(printer); - printer->Print(variables_, - "output.writeRawVarint32($tag$);\n" - "output.writeRawVarint32(dataSize);\n" - "for (int i = 0; i < this.$name$.length; i++) {\n" - " output.write$capitalized_type$NoTag(this.$name$[i]);\n" - "}\n"); - } else if (IsReferenceType(GetJavaType(descriptor_))) { - printer->Print(variables_, - "for (int i = 0; i < this.$name$.length; i++) {\n" - " $type$ element = this.$name$[i];\n" - " if (element != null) {\n" - " output.write$capitalized_type$($number$, element);\n" - " }\n" - "}\n"); - } else { - printer->Print(variables_, - "for (int i = 0; i < this.$name$.length; i++) {\n" - " output.write$capitalized_type$($number$, this.$name$[i]);\n" - "}\n"); - } - - printer->Outdent(); - printer->Print("}\n"); -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if (this.$name$ != null && this.$name$.length > 0) {\n"); - printer->Indent(); - - GenerateRepeatedDataSizeCode(printer); - - printer->Print( - "size += dataSize;\n"); - if (descriptor_->is_packable() && descriptor_->options().packed()) { - printer->Print(variables_, - "size += $tag_size$;\n" - "size += com.google.protobuf.nano.CodedOutputByteBufferNano\n" - " .computeRawVarint32Size(dataSize);\n"); - } else if (IsReferenceType(GetJavaType(descriptor_))) { - printer->Print(variables_, - "size += $tag_size$ * dataCount;\n"); - } else { - printer->Print(variables_, - "size += $tag_size$ * this.$name$.length;\n"); - } - - printer->Outdent(); - - printer->Print( - "}\n"); -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!com.google.protobuf.nano.InternalNano.equals(\n" - " this.$name$, other.$name$)) {\n" - " return false;\n" - "}\n"); -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateHashCodeCode(io::Printer* printer) const { - printer->Print(variables_, - "result = 31 * result\n" - " + com.google.protobuf.nano.InternalNano.hashCode(this.$name$);\n"); -} - -} // namespace javanano -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/src/google/protobuf/compiler/javanano/javanano_primitive_field.h b/src/google/protobuf/compiler/javanano/javanano_primitive_field.h deleted file mode 100644 index d7d72d57..00000000 --- a/src/google/protobuf/compiler/javanano/javanano_primitive_field.h +++ /dev/null @@ -1,150 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_PRIMITIVE_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_PRIMITIVE_FIELD_H__ - -#include <map> -#include <string> -#include <google/protobuf/compiler/javanano/javanano_field.h> - -namespace google { -namespace protobuf { -namespace compiler { -namespace javanano { - -class PrimitiveFieldGenerator : public FieldGenerator { - public: - explicit PrimitiveFieldGenerator( - const FieldDescriptor* descriptor, const Params& params); - ~PrimitiveFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - bool SavedDefaultNeeded() const; - void GenerateInitSavedDefaultCode(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer, bool lazy_init) const; - void GenerateClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCodeCode(io::Printer* printer) const; - - private: - void GenerateSerializationConditional(io::Printer* printer) const; - - const FieldDescriptor* descriptor_; - std::map<string, string> variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator); -}; - -class AccessorPrimitiveFieldGenerator : public FieldGenerator { - public: - explicit AccessorPrimitiveFieldGenerator(const FieldDescriptor* descriptor, - const Params ¶ms, int has_bit_index); - ~AccessorPrimitiveFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - bool SavedDefaultNeeded() const; - void GenerateInitSavedDefaultCode(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer, bool lazy_init) const; - void GenerateClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCodeCode(io::Printer* printer) const; - - private: - const FieldDescriptor* descriptor_; - std::map<string, string> variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(AccessorPrimitiveFieldGenerator); -}; - -class PrimitiveOneofFieldGenerator : public FieldGenerator { - public: - explicit PrimitiveOneofFieldGenerator( - const FieldDescriptor* descriptor, const Params& params); - ~PrimitiveOneofFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GenerateMembers(io::Printer* printer, bool lazy_init) const; - void GenerateClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCodeCode(io::Printer* printer) const; - - private: - const FieldDescriptor* descriptor_; - std::map<string, string> variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveOneofFieldGenerator); -}; - -class RepeatedPrimitiveFieldGenerator : public FieldGenerator { - public: - explicit RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor, - const Params& params); - ~RepeatedPrimitiveFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GenerateMembers(io::Printer* printer, bool lazy_init) const; - void GenerateClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateMergingCodeFromPacked(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCodeCode(io::Printer* printer) const; - void GenerateFixClonedCode(io::Printer* printer) const; - - private: - void GenerateRepeatedDataSizeCode(io::Printer* printer) const; - - const FieldDescriptor* descriptor_; - std::map<string, string> variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator); -}; - -} // namespace javanano -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_PRIMITIVE_FIELD_H__ diff --git a/src/google/protobuf/compiler/main.cc b/src/google/protobuf/compiler/main.cc index 680d6428..1db35441 100644 --- a/src/google/protobuf/compiler/main.cc +++ b/src/google/protobuf/compiler/main.cc @@ -40,7 +40,6 @@ #ifndef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP #include <google/protobuf/compiler/csharp/csharp_generator.h> -#include <google/protobuf/compiler/javanano/javanano_generator.h> #include <google/protobuf/compiler/js/js_generator.h> #include <google/protobuf/compiler/objectivec/objectivec_generator.h> #include <google/protobuf/compiler/php/php_generator.h> @@ -71,11 +70,6 @@ int main(int argc, char* argv[]) { cli.RegisterGenerator("--python_out", &py_generator, "Generate Python source file."); - // Java Nano - google::protobuf::compiler::javanano::JavaNanoGenerator javanano_generator; - cli.RegisterGenerator("--javanano_out", &javanano_generator, - "Generate Java Nano source file."); - // PHP google::protobuf::compiler::php::Generator php_generator; cli.RegisterGenerator("--php_out", &php_generator, diff --git a/src/google/protobuf/compiler/objectivec/objectivec_file.cc b/src/google/protobuf/compiler/objectivec/objectivec_file.cc index 6f80a0de..f0d9b4d5 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_file.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_file.cc @@ -188,6 +188,7 @@ bool IsDirectDependency(const FileDescriptor* dep, const FileDescriptor* file) { FileGenerator::FileGenerator(const FileDescriptor *file, const Options& options) : file_(file), root_class_name_(FileClassName(file)), + is_bundled_proto_(IsProtobufLibraryBundledProtoFile(file)), options_(options) { for (int i = 0; i < file_->enum_type_count(); i++) { EnumGenerator *generator = new EnumGenerator(file_->enum_type(i)); @@ -214,7 +215,17 @@ FileGenerator::~FileGenerator() { } void FileGenerator::GenerateHeader(io::Printer *printer) { - PrintFileRuntimePreamble(printer, "GPBProtocolBuffers.h"); + std::set<string> headers; + // Generated files bundled with the library get minimal imports, everything + // else gets the wrapper so everything is usable. + if (is_bundled_proto_) { + headers.insert("GPBRootObject.h"); + headers.insert("GPBMessage.h"); + headers.insert("GPBDescriptor.h"); + } else { + headers.insert("GPBProtocolBuffers.h"); + } + PrintFileRuntimePreamble(printer, headers); // Add some verification that the generated code matches the source the // code is being compiled with. @@ -236,7 +247,8 @@ void FileGenerator::GenerateHeader(io::Printer *printer) { { ImportWriter import_writer( options_.generate_for_named_framework, - options_.named_framework_to_proto_path_mappings_path); + options_.named_framework_to_proto_path_mappings_path, + is_bundled_proto_); const string header_extension(kHeaderExtension); for (int i = 0; i < file_->public_dependency_count(); i++) { import_writer.AddFile(file_->public_dependency(i), header_extension); @@ -337,7 +349,9 @@ void FileGenerator::GenerateHeader(io::Printer *printer) { void FileGenerator::GenerateSource(io::Printer *printer) { // #import the runtime support. - PrintFileRuntimePreamble(printer, "GPBProtocolBuffers_RuntimeSupport.h"); + std::set<string> headers; + headers.insert("GPBProtocolBuffers_RuntimeSupport.h"); + PrintFileRuntimePreamble(printer, headers); // Enums use atomic in the generated code, so add the system import as needed. if (FileContainsEnums(file_)) { @@ -352,7 +366,8 @@ void FileGenerator::GenerateSource(io::Printer *printer) { { ImportWriter import_writer( options_.generate_for_named_framework, - options_.named_framework_to_proto_path_mappings_path); + options_.named_framework_to_proto_path_mappings_path, + is_bundled_proto_); const string header_extension(kHeaderExtension); // #import the header for this proto file. @@ -566,7 +581,7 @@ void FileGenerator::GenerateSource(io::Printer *printer) { // files. This currently only supports the runtime coming from a framework // as defined by the official CocoaPod. void FileGenerator::PrintFileRuntimePreamble( - io::Printer* printer, const string& header_to_import) const { + io::Printer* printer, const std::set<string>& headers_to_import) const { printer->Print( "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" "// source: $filename$\n" @@ -575,6 +590,7 @@ void FileGenerator::PrintFileRuntimePreamble( const string framework_name(ProtobufLibraryFrameworkName); const string cpp_symbol(ProtobufFrameworkImportSymbol(framework_name)); + printer->Print( "// This CPP symbol can be defined to use imports that match up to the framework\n" "// imports needed when using CocoaPods.\n" @@ -582,15 +598,31 @@ void FileGenerator::PrintFileRuntimePreamble( " #define $cpp_symbol$ 0\n" "#endif\n" "\n" - "#if $cpp_symbol$\n" - " #import <$framework_name$/$header$>\n" - "#else\n" - " #import \"$header$\"\n" + "#if $cpp_symbol$\n", + "cpp_symbol", cpp_symbol); + + + for (std::set<string>::const_iterator iter = headers_to_import.begin(); + iter != headers_to_import.end(); ++iter) { + printer->Print( + " #import <$framework_name$/$header$>\n", + "header", *iter, + "framework_name", framework_name); + } + + printer->Print( + "#else\n"); + + for (std::set<string>::const_iterator iter = headers_to_import.begin(); + iter != headers_to_import.end(); ++iter) { + printer->Print( + " #import \"$header$\"\n", + "header", *iter); + } + + printer->Print( "#endif\n" - "\n", - "cpp_symbol", cpp_symbol, - "header", header_to_import, - "framework_name", framework_name); + "\n"); } } // namespace objectivec diff --git a/src/google/protobuf/compiler/objectivec/objectivec_file.h b/src/google/protobuf/compiler/objectivec/objectivec_file.h index 9c3f0071..1754fc0a 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_file.h +++ b/src/google/protobuf/compiler/objectivec/objectivec_file.h @@ -66,6 +66,7 @@ class FileGenerator { private: const FileDescriptor* file_; string root_class_name_; + bool is_bundled_proto_; std::vector<EnumGenerator*> enum_generators_; std::vector<MessageGenerator*> message_generators_; @@ -74,7 +75,7 @@ class FileGenerator { const Options options_; void PrintFileRuntimePreamble( - io::Printer* printer, const string& header_to_import) const; + io::Printer* printer, const std::set<string>& headers_to_import) const; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileGenerator); }; diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc index 5727dd56..df71c8bb 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc @@ -1504,10 +1504,12 @@ bool ParseSimpleFile( ImportWriter::ImportWriter( const string& generate_for_named_framework, - const string& named_framework_to_proto_path_mappings_path) + const string& named_framework_to_proto_path_mappings_path, + bool include_wkt_imports) : generate_for_named_framework_(generate_for_named_framework), named_framework_to_proto_path_mappings_path_( named_framework_to_proto_path_mappings_path), + include_wkt_imports_(include_wkt_imports), need_to_parse_mapping_file_(true) { } @@ -1518,9 +1520,14 @@ void ImportWriter::AddFile(const FileDescriptor* file, const string file_path(FilePath(file)); if (IsProtobufLibraryBundledProtoFile(file)) { - protobuf_framework_imports_.push_back( - FilePathBasename(file) + header_extension); - protobuf_non_framework_imports_.push_back(file_path + header_extension); + // The imports of the WKTs are only needed within the library itself, + // in other cases, they get skipped because the generated code already + // import GPBProtocolBuffers.h and hence proves them. + if (include_wkt_imports_) { + protobuf_framework_imports_.push_back( + FilePathBasename(file) + header_extension); + protobuf_non_framework_imports_.push_back(file_path + header_extension); + } return; } diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h index f74607c8..8999aa59 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h +++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h @@ -253,7 +253,8 @@ bool LIBPROTOC_EXPORT ParseSimpleFile( class LIBPROTOC_EXPORT ImportWriter { public: ImportWriter(const string& generate_for_named_framework, - const string& named_framework_to_proto_path_mappings_path); + const string& named_framework_to_proto_path_mappings_path, + bool include_wkt_imports); ~ImportWriter(); void AddFile(const FileDescriptor* file, const string& header_extension); @@ -275,6 +276,7 @@ class LIBPROTOC_EXPORT ImportWriter { const string generate_for_named_framework_; const string named_framework_to_proto_path_mappings_path_; + const bool include_wkt_imports_; std::map<string, string> proto_file_to_framework_name_; bool need_to_parse_mapping_file_; diff --git a/src/google/protobuf/compiler/parser.cc b/src/google/protobuf/compiler/parser.cc index df81e55f..5c7047a6 100644 --- a/src/google/protobuf/compiler/parser.cc +++ b/src/google/protobuf/compiler/parser.cc @@ -337,31 +337,42 @@ void Parser::AddError(const string& error) { Parser::LocationRecorder::LocationRecorder(Parser* parser) : parser_(parser), + source_code_info_(parser->source_code_info_), location_(parser_->source_code_info_->add_location()) { location_->add_span(parser_->input_->current().line); location_->add_span(parser_->input_->current().column); } Parser::LocationRecorder::LocationRecorder(const LocationRecorder& parent) { - Init(parent); + Init(parent, parent.source_code_info_); +} + +Parser::LocationRecorder::LocationRecorder(const LocationRecorder& parent, + int path1, + SourceCodeInfo* source_code_info) { + Init(parent, source_code_info); + AddPath(path1); } Parser::LocationRecorder::LocationRecorder(const LocationRecorder& parent, int path1) { - Init(parent); + Init(parent, parent.source_code_info_); AddPath(path1); } Parser::LocationRecorder::LocationRecorder(const LocationRecorder& parent, int path1, int path2) { - Init(parent); + Init(parent, parent.source_code_info_); AddPath(path1); AddPath(path2); } -void Parser::LocationRecorder::Init(const LocationRecorder& parent) { +void Parser::LocationRecorder::Init(const LocationRecorder& parent, + SourceCodeInfo* source_code_info) { parser_ = parent.parser_; - location_ = parser_->source_code_info_->add_location(); + source_code_info_ = source_code_info; + + location_ = source_code_info_->add_location(); location_->mutable_path()->CopyFrom(parent.location_->path()); location_->add_span(parser_->input_->current().line); @@ -403,6 +414,10 @@ void Parser::LocationRecorder::RecordLegacyLocation(const Message* descriptor, } } +int Parser::LocationRecorder::CurrentPathSize() const { + return location_->path_size(); +} + void Parser::LocationRecorder::AttachComments( string* leading, string* trailing, std::vector<string>* detached_comments) const { @@ -1496,21 +1511,30 @@ bool Parser::ParseExtensions(DescriptorProto* message, range->set_end(end); } while (TryConsume(",")); - if (LookingAt("[")) { - LocationRecorder location( - extensions_location, - DescriptorProto::ExtensionRange::kOptionsFieldNumber); - DO(Consume("[")); + if (LookingAt("[")) { + int range_number_index = extensions_location.CurrentPathSize(); + SourceCodeInfo info; // Parse extension range options in the first range. ExtensionRangeOptions* options = message->mutable_extension_range(old_range_size)->mutable_options(); - do { - DO(ParseOption(options, location, containing_file, OPTION_ASSIGNMENT)); - } while (TryConsume(",")); - DO(Consume("]")); + { + LocationRecorder index_location( + extensions_location, 0 /* we fill this in w/ actual index below */, + &info); + LocationRecorder location( + index_location, + DescriptorProto::ExtensionRange::kOptionsFieldNumber); + DO(Consume("[")); + + do { + DO(ParseOption(options, location, containing_file, OPTION_ASSIGNMENT)); + } while (TryConsume(",")); + + DO(Consume("]")); + } // Then copy the extension range options to all of the other ranges we've // parsed. @@ -1518,6 +1542,19 @@ bool Parser::ParseExtensions(DescriptorProto* message, message->mutable_extension_range(i)->mutable_options() ->CopyFrom(*options); } + // and copy source locations to the other ranges, too + for (int i = old_range_size; i < message->extension_range_size(); i++) { + for (int j = 0; j < info.location_size(); j++) { + if (info.location(j).path_size() == range_number_index + 1) { + // this location's path is up to the extension range index, but doesn't + // include options; so it's redundant with location above + continue; + } + SourceCodeInfo_Location* dest = source_code_info_->add_location(); + dest->CopyFrom(info.location(j)); + dest->set_path(range_number_index, i); + } + } } DO(ConsumeEndOfDeclaration(";", &extensions_location)); diff --git a/src/google/protobuf/compiler/parser.h b/src/google/protobuf/compiler/parser.h index 01d8a66b..5d98e5e1 100644 --- a/src/google/protobuf/compiler/parser.h +++ b/src/google/protobuf/compiler/parser.h @@ -224,6 +224,10 @@ class LIBPROTOBUF_EXPORT Parser { LocationRecorder(const LocationRecorder& parent, int path1); LocationRecorder(const LocationRecorder& parent, int path1, int path2); + // Creates a recorder that generates locations into given source code info. + LocationRecorder(const LocationRecorder& parent, int path1, + SourceCodeInfo* source_code_info); + ~LocationRecorder(); // Add a path component. See SourceCodeInfo.Location.path in @@ -250,6 +254,9 @@ class LIBPROTOBUF_EXPORT Parser { void RecordLegacyLocation(const Message* descriptor, DescriptorPool::ErrorCollector::ErrorLocation location); + // Returns the number of path components in the recorder's current location. + int CurrentPathSize() const; + // Attaches leading and trailing comments to the location. The two strings // will be swapped into place, so after this is called *leading and // *trailing will be empty. @@ -264,9 +271,10 @@ class LIBPROTOBUF_EXPORT Parser { // SourceCodeInfo.location repeated field. For top-level elements, // parent_index_ is -1. Parser* parser_; + SourceCodeInfo* source_code_info_; SourceCodeInfo::Location* location_; - void Init(const LocationRecorder& parent); + void Init(const LocationRecorder& parent, SourceCodeInfo* source_code_info); }; // ================================================================= diff --git a/src/google/protobuf/compiler/php/php_generator.h b/src/google/protobuf/compiler/php/php_generator.h index 67e70bc7..54a95ef5 100644 --- a/src/google/protobuf/compiler/php/php_generator.h +++ b/src/google/protobuf/compiler/php/php_generator.h @@ -54,9 +54,12 @@ class LIBPROTOC_EXPORT Generator // To skip reserved keywords in php, some generated classname are prefixed. // Other code generators may need following API to figure out the actual // classname. -std::string GeneratedClassName(const google::protobuf::Descriptor* desc); -std::string GeneratedClassName(const google::protobuf::EnumDescriptor* desc); -std::string GeneratedClassName(const google::protobuf::ServiceDescriptor* desc); +LIBPROTOC_EXPORT std::string GeneratedClassName( + const google::protobuf::Descriptor* desc); +LIBPROTOC_EXPORT std::string GeneratedClassName( + const google::protobuf::EnumDescriptor* desc); +LIBPROTOC_EXPORT std::string GeneratedClassName( + const google::protobuf::ServiceDescriptor* desc); } // namespace php } // namespace compiler diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index bd08581d..d466dd8b 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -3118,15 +3118,18 @@ namespace { struct OptionsToInterpret { OptionsToInterpret(const string& ns, const string& el, + std::vector<int>& path, const Message* orig_opt, Message* opt) : name_scope(ns), element_name(el), + element_path(path), original_options(orig_opt), options(opt) { } string name_scope; string element_name; + std::vector<int> element_path; const Message* original_options; Message* options; }; @@ -3293,7 +3296,7 @@ class DescriptorBuilder { // descriptor.proto. template<class DescriptorT> void AllocateOptions( const typename DescriptorT::OptionsType& orig_options, - DescriptorT* descriptor); + DescriptorT* descriptor, int options_field_tag); // Specialization for FileOptions. void AllocateOptions(const FileOptions& orig_options, FileDescriptor* descriptor); @@ -3303,7 +3306,8 @@ class DescriptorBuilder { const string& name_scope, const string& element_name, const typename DescriptorT::OptionsType& orig_options, - DescriptorT* descriptor); + DescriptorT* descriptor, + std::vector<int>& options_path); // These methods all have the same signature for the sake of the BUILD_ARRAY // macro, below. @@ -3392,13 +3396,21 @@ class DescriptorBuilder { // Otherwise returns true. bool InterpretOptions(OptionsToInterpret* options_to_interpret); + // Updates the given source code info by re-writing uninterpreted option + // locations to refer to the corresponding interpreted option. + void UpdateSourceCodeInfo(SourceCodeInfo* info); + class AggregateOptionFinder; private: // Interprets uninterpreted_option_ on the specified message, which // must be the mutable copy of the original options message to which - // uninterpreted_option_ belongs. - bool InterpretSingleOption(Message* options); + // uninterpreted_option_ belongs. The given src_path is the source + // location path to the uninterpreted option, and options_path is the + // source location path to the options message. The location paths are + // recorded and then used in UpdateSourceCodeInfo. + bool InterpretSingleOption(Message* options, std::vector<int>& src_path, + std::vector<int>& options_path); // Adds the uninterpreted_option to the given options message verbatim. // Used when AllowUnknownDependencies() is in effect and we can't find @@ -3473,6 +3485,16 @@ class DescriptorBuilder { // can use it to find locations recorded by the parser. const UninterpretedOption* uninterpreted_option_; + // This maps the element path of uninterpreted options to the element path + // of the resulting interpreted option. This is used to modify a file's + // source code info to account for option interpretation. + std::map<std::vector<int>, std::vector<int>> interpreted_paths_; + + // This maps the path to a repeated option field to the known number of + // elements the field contains. This is used to track the compute the + // index portion of the element path when interpreting a single option. + std::map<std::vector<int>, int> repeated_option_counts_; + // Factory used to create the dynamic messages we need to parse // any aggregate option values we encounter. DynamicMessageFactory dynamic_factory_; @@ -4090,24 +4112,30 @@ void DescriptorBuilder::ValidateSymbolName( // FileDescriptor. template<class DescriptorT> void DescriptorBuilder::AllocateOptions( const typename DescriptorT::OptionsType& orig_options, - DescriptorT* descriptor) { + DescriptorT* descriptor, int options_field_tag) { + std::vector<int> options_path; + descriptor->GetLocationPath(&options_path); + options_path.push_back(options_field_tag); AllocateOptionsImpl(descriptor->full_name(), descriptor->full_name(), - orig_options, descriptor); + orig_options, descriptor, options_path); } // We specialize for FileDescriptor. void DescriptorBuilder::AllocateOptions(const FileOptions& orig_options, FileDescriptor* descriptor) { + std::vector<int> options_path; + options_path.push_back(FileDescriptorProto::kOptionsFieldNumber); // We add the dummy token so that LookupSymbol does the right thing. AllocateOptionsImpl(descriptor->package() + ".dummy", descriptor->name(), - orig_options, descriptor); + orig_options, descriptor, options_path); } template<class DescriptorT> void DescriptorBuilder::AllocateOptionsImpl( const string& name_scope, const string& element_name, const typename DescriptorT::OptionsType& orig_options, - DescriptorT* descriptor) { + DescriptorT* descriptor, + std::vector<int>& options_path) { // We need to use a dummy pointer to work around a bug in older versions of // GCC. Otherwise, the following two lines could be replaced with: // typename DescriptorT::OptionsType* options = @@ -4130,7 +4158,8 @@ template<class DescriptorT> void DescriptorBuilder::AllocateOptionsImpl( // we're still trying to build it. if (options->uninterpreted_option_size() > 0) { options_to_interpret_.push_back( - OptionsToInterpret(name_scope, element_name, &orig_options, options)); + OptionsToInterpret(name_scope, element_name, options_path, + &orig_options, options)); } } @@ -4268,8 +4297,9 @@ FileDescriptor* DescriptorBuilder::BuildFileImpl( result->is_placeholder_ = false; result->finished_building_ = false; + SourceCodeInfo *info = NULL; if (proto.has_source_code_info()) { - SourceCodeInfo *info = tables_->AllocateMessage<SourceCodeInfo>(); + info = tables_->AllocateMessage<SourceCodeInfo>(); info->CopyFrom(proto.source_code_info()); result->source_code_info_ = info; } else { @@ -4467,6 +4497,10 @@ FileDescriptor* DescriptorBuilder::BuildFileImpl( option_interpreter.InterpretOptions(&(*iter)); } options_to_interpret_.clear(); + + if (info != NULL) { + option_interpreter.UpdateSourceCodeInfo(info); + } } // Validate options. See comments at InternalSetLazilyBuildDependencies about @@ -4538,7 +4572,8 @@ void DescriptorBuilder::BuildMessage(const DescriptorProto& proto, if (!proto.has_options()) { result->options_ = NULL; // Will set to default_instance later. } else { - AllocateOptions(proto.options(), result); + AllocateOptions(proto.options(), result, + DescriptorProto::kOptionsFieldNumber); } AddSymbol(result->full_name(), parent, result->name(), @@ -4918,7 +4953,8 @@ void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto, if (!proto.has_options()) { result->options_ = NULL; // Will set to default_instance later. } else { - AllocateOptions(proto.options(), result); + AllocateOptions(proto.options(), result, + FieldDescriptorProto::kOptionsFieldNumber); } @@ -4952,8 +4988,16 @@ void DescriptorBuilder::BuildExtensionRange( if (!proto.has_options()) { result->options_ = NULL; // Will set to default_instance later. } else { + std::vector<int> options_path; + parent->GetLocationPath(&options_path); + options_path.push_back(DescriptorProto::kExtensionRangeFieldNumber); + // find index of this extension range in order to compute path + int index; + for (index = 0; parent->extension_ranges_ + index != result; index++); + options_path.push_back(index); + options_path.push_back(DescriptorProto_ExtensionRange::kOptionsFieldNumber); AllocateOptionsImpl(parent->full_name(), parent->full_name(), - proto.options(), result); + proto.options(), result, options_path); } } @@ -5005,7 +5049,8 @@ void DescriptorBuilder::BuildOneof(const OneofDescriptorProto& proto, if (!proto.has_options()) { result->options_ = NULL; // Will set to default_instance later. } else { - AllocateOptions(proto.options(), result); + AllocateOptions(proto.options(), result, + OneofDescriptorProto::kOptionsFieldNumber); } AddSymbol(result->full_name(), parent, result->name(), @@ -5122,7 +5167,8 @@ void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto, if (!proto.has_options()) { result->options_ = NULL; // Will set to default_instance later. } else { - AllocateOptions(proto.options(), result); + AllocateOptions(proto.options(), result, + EnumDescriptorProto::kOptionsFieldNumber); } AddSymbol(result->full_name(), parent, result->name(), @@ -5199,7 +5245,8 @@ void DescriptorBuilder::BuildEnumValue(const EnumValueDescriptorProto& proto, if (!proto.has_options()) { result->options_ = NULL; // Will set to default_instance later. } else { - AllocateOptions(proto.options(), result); + AllocateOptions(proto.options(), result, + EnumValueDescriptorProto::kOptionsFieldNumber); } // Again, enum values are weird because we makes them appear as siblings @@ -5266,7 +5313,8 @@ void DescriptorBuilder::BuildService(const ServiceDescriptorProto& proto, if (!proto.has_options()) { result->options_ = NULL; // Will set to default_instance later. } else { - AllocateOptions(proto.options(), result); + AllocateOptions(proto.options(), result, + ServiceDescriptorProto::kOptionsFieldNumber); } AddSymbol(result->full_name(), NULL, result->name(), @@ -5294,7 +5342,8 @@ void DescriptorBuilder::BuildMethod(const MethodDescriptorProto& proto, if (!proto.has_options()) { result->options_ = NULL; // Will set to default_instance later. } else { - AllocateOptions(proto.options(), result); + AllocateOptions(proto.options(), result, + MethodDescriptorProto::kOptionsFieldNumber); } result->client_streaming_ = proto.client_streaming(); @@ -6266,6 +6315,9 @@ bool DescriptorBuilder::OptionInterpreter::InterpretOptions( << "No field named \"uninterpreted_option\" in the Options proto."; options->GetReflection()->ClearField(options, uninterpreted_options_field); + std::vector<int> src_path = options_to_interpret->element_path; + src_path.push_back(uninterpreted_options_field->number()); + // Find the uninterpreted_option field in the original options. const FieldDescriptor* original_uninterpreted_options_field = original_options->GetDescriptor()-> @@ -6276,14 +6328,17 @@ bool DescriptorBuilder::OptionInterpreter::InterpretOptions( const int num_uninterpreted_options = original_options->GetReflection()-> FieldSize(*original_options, original_uninterpreted_options_field); for (int i = 0; i < num_uninterpreted_options; ++i) { + src_path.push_back(i); uninterpreted_option_ = down_cast<const UninterpretedOption*>( &original_options->GetReflection()->GetRepeatedMessage( *original_options, original_uninterpreted_options_field, i)); - if (!InterpretSingleOption(options)) { + if (!InterpretSingleOption(options, src_path, + options_to_interpret->element_path)) { // Error already added by InterpretSingleOption(). failed = true; break; } + src_path.pop_back(); } // Reset these, so we don't have any dangling pointers. uninterpreted_option_ = NULL; @@ -6316,7 +6371,7 @@ bool DescriptorBuilder::OptionInterpreter::InterpretOptions( } bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( - Message* options) { + Message* options, std::vector<int>& src_path, std::vector<int>& opts_path) { // First do some basic validation. if (uninterpreted_option_->name_size() == 0) { // This should never happen unless the parser has gone seriously awry or @@ -6362,6 +6417,8 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( std::vector<const FieldDescriptor*> intermediate_fields; string debug_msg_name = ""; + std::vector<int> dest_path = opts_path; + for (int i = 0; i < uninterpreted_option_->name_size(); ++i) { const string& name_part = uninterpreted_option_->name(i).name_part(); if (debug_msg_name.size() > 0) { @@ -6424,19 +6481,24 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( "\" is not a field or extension of message \"" + descriptor->name() + "\"."); } - } else if (i < uninterpreted_option_->name_size() - 1) { - if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) { - return AddNameError("Option \"" + debug_msg_name + - "\" is an atomic type, not a message."); - } else if (field->is_repeated()) { - return AddNameError("Option field \"" + debug_msg_name + - "\" is a repeated message. Repeated message " - "options must be initialized using an " - "aggregate value."); - } else { - // Drill down into the submessage. - intermediate_fields.push_back(field); - descriptor = field->message_type(); + } else { + // accumulate field numbers to form path to interpreted option + dest_path.push_back(field->number()); + + if (i < uninterpreted_option_->name_size() - 1) { + if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) { + return AddNameError("Option \"" + debug_msg_name + + "\" is an atomic type, not a message."); + } else if (field->is_repeated()) { + return AddNameError("Option field \"" + debug_msg_name + + "\" is a repeated message. Repeated message " + "options must be initialized using an " + "aggregate value."); + } else { + // Drill down into the submessage. + intermediate_fields.push_back(field); + descriptor = field->message_type(); + } } } } @@ -6457,7 +6519,6 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( return false; // ExamineIfOptionIsSet() already added the error. } - // First set the value on the UnknownFieldSet corresponding to the // innermost message. std::unique_ptr<UnknownFieldSet> unknown_fields(new UnknownFieldSet()); @@ -6503,9 +6564,110 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( options->GetReflection()->MutableUnknownFields(options)->MergeFrom( *unknown_fields); + // record the element path of the interpreted option + if (field->is_repeated()) { + int index = repeated_option_counts_[dest_path]++; + dest_path.push_back(index); + } + interpreted_paths_[src_path] = dest_path; + return true; } +void DescriptorBuilder::OptionInterpreter::UpdateSourceCodeInfo( + SourceCodeInfo* info) { + + if (interpreted_paths_.empty()) { + // nothing to do! + return; + } + + // We find locations that match keys in interpreted_paths_ and + // 1) replace the path with the corresponding value in interpreted_paths_ + // 2) remove any subsequent sub-locations (sub-location is one whose path + // has the parent path as a prefix) + // + // To avoid quadratic behavior of removing interior rows as we go, + // we keep a copy. But we don't actually copy anything until we've + // found the first match (so if the source code info has no locations + // that need to be changed, there is zero copy overhead). + + RepeatedPtrField<SourceCodeInfo_Location>* locs = info->mutable_location(); + RepeatedPtrField<SourceCodeInfo_Location> new_locs; + bool copying = false; + + std::vector<int> pathv; + bool matched = false; + + for (RepeatedPtrField<SourceCodeInfo_Location>::iterator loc = locs->begin(); + loc != locs->end(); loc++) { + + if (matched) { + // see if this location is in the range to remove + bool loc_matches = true; + if (loc->path_size() < pathv.size()) { + loc_matches = false; + } else { + for (int j = 0; j < pathv.size(); j++) { + if (loc->path(j) != pathv[j]) { + loc_matches = false; + break; + } + } + } + + if (loc_matches) { + // don't copy this row since it is a sub-location that we're removing + continue; + } + + matched = false; + } + + pathv.clear(); + for (int j = 0; j < loc->path_size(); j++) { + pathv.push_back(loc->path(j)); + } + + std::map<std::vector<int>, std::vector<int>>::iterator entry = + interpreted_paths_.find(pathv); + + if (entry == interpreted_paths_.end()) { + // not a match + if (copying) { + new_locs.Add()->CopyFrom(*loc); + } + continue; + } + + matched = true; + + if (!copying) { + // initialize the copy we are building + copying = true; + new_locs.Reserve(locs->size()); + for (RepeatedPtrField<SourceCodeInfo_Location>::iterator it = + locs->begin(); it != loc; it++) { + new_locs.Add()->CopyFrom(*it); + } + } + + // add replacement and update its path + SourceCodeInfo_Location* replacement = new_locs.Add(); + replacement->CopyFrom(*loc); + replacement->clear_path(); + for (std::vector<int>::iterator rit = entry->second.begin(); + rit != entry->second.end(); rit++) { + replacement->add_path(*rit); + } + } + + // if we made a changed copy, put it in place + if (copying) { + *locs = new_locs; + } +} + void DescriptorBuilder::OptionInterpreter::AddWithoutInterpreting( const UninterpretedOption& uninterpreted_option, Message* options) { const FieldDescriptor* field = diff --git a/src/google/protobuf/descriptor_unittest.cc b/src/google/protobuf/descriptor_unittest.cc index 5f8d445c..54da095a 100644 --- a/src/google/protobuf/descriptor_unittest.cc +++ b/src/google/protobuf/descriptor_unittest.cc @@ -6918,40 +6918,95 @@ class SingletonSourceTree : public compiler::SourceTree { const char *const kSourceLocationTestInput = "syntax = \"proto2\";\n" + "option java_package = \"com.foo.bar\";\n" + "option (test_file_opt) = \"foobar\";\n" "message A {\n" - " optional int32 a = 1;\n" + " option (test_msg_opt) = \"foobar\";\n" + " optional int32 a = 1 [deprecated = true];\n" " message B {\n" - " required double b = 1;\n" + " required double b = 1 [(test_field_opt) = \"foobar\"];\n" + " }\n" + " oneof c {\n" + " option (test_oneof_opt) = \"foobar\";\n" + " string d = 2;\n" + " string e = 3;\n" + " string f = 4;\n" " }\n" "}\n" "enum Indecision {\n" - " YES = 1;\n" - " NO = 2;\n" + " option (test_enum_opt) = 21;\n" + " option (test_enum_opt) = 42;\n" + " option (test_enum_opt) = 63;\n" + " YES = 1 [(test_enumval_opt).a = 100];\n" + " NO = 2 [(test_enumval_opt) = {a:200}];\n" " MAYBE = 3;\n" "}\n" "service S {\n" + " option (test_svc_opt) = {a:100};\n" + " option (test_svc_opt) = {a:200};\n" + " option (test_svc_opt) = {a:300};\n" " rpc Method(A) returns (A.B);\n" // Put an empty line here to make the source location range match. "\n" + " rpc OtherMethod(A) returns (A) {\n" + " option deprecated = true;\n" + " option (test_method_opt) = \"foobar\";\n" + " }\n" "}\n" "message MessageWithExtensions {\n" - " extensions 1000 to max;\n" + " extensions 1000 to 2000, 2001 to max [(test_ext_opt) = \"foobar\"];\n" "}\n" "extend MessageWithExtensions {\n" - " optional int32 int32_extension = 1001;\n" + " repeated int32 int32_extension = 1001 [packed=true];\n" "}\n" "message C {\n" " extend MessageWithExtensions {\n" " optional C message_extension = 1002;\n" " }\n" - "}\n"; + "}\n" + "import \"google/protobuf/descriptor.proto\";\n" + "extend google.protobuf.FileOptions {\n" + " optional string test_file_opt = 10101;\n" + "}\n" + "extend google.protobuf.MessageOptions {\n" + " optional string test_msg_opt = 10101;\n" + "}\n" + "extend google.protobuf.FieldOptions {\n" + " optional string test_field_opt = 10101;\n" + "}\n" + "extend google.protobuf.EnumOptions {\n" + " repeated int32 test_enum_opt = 10101;\n" + "}\n" + "extend google.protobuf.EnumValueOptions {\n" + " optional A test_enumval_opt = 10101;\n" + "}\n" + "extend google.protobuf.ServiceOptions {\n" + " repeated A test_svc_opt = 10101;\n" + "}\n" + "extend google.protobuf.MethodOptions {\n" + " optional string test_method_opt = 10101;\n" + "}\n" + "extend google.protobuf.OneofOptions {\n" + " optional string test_oneof_opt = 10101;\n" + "}\n" + "extend google.protobuf.ExtensionRangeOptions {\n" + " optional string test_ext_opt = 10101;\n" + "}\n" + ; class SourceLocationTest : public testing::Test { public: SourceLocationTest() : source_tree_("/test/test.proto", kSourceLocationTestInput), - db_(&source_tree_), - pool_(&db_, &collector_) {} + simple_db_(), + source_tree_db_(&source_tree_), + merged_db_(&simple_db_, &source_tree_db_), + pool_(&merged_db_, &collector_) { + // we need descriptor.proto to be accessible by the pool + // since our test file imports it + FileDescriptorProto::descriptor()->file()->CopyTo(&file_proto_); + simple_db_.Add(file_proto_); + } static string PrintSourceLocation(const SourceLocation &loc) { return strings::Substitute("$0:$1-$2:$3", @@ -6962,12 +7017,20 @@ class SourceLocationTest : public testing::Test { } private: + FileDescriptorProto file_proto_; AbortingErrorCollector collector_; SingletonSourceTree source_tree_; - compiler::SourceTreeDescriptorDatabase db_; + SimpleDescriptorDatabase simple_db_; // contains descriptor.proto + compiler::SourceTreeDescriptorDatabase source_tree_db_; // loads test.proto + MergedDescriptorDatabase merged_db_; // combines above two dbs protected: DescriptorPool pool_; + + // tag number of all custom options in above test file + static const int kCustomOptionFieldNumber = 10101; + // tag number of field "a" in message type "A" in above test file + static const int kA_aFieldNumber = 1; }; // TODO(adonovan): implement support for option fields and for @@ -6981,27 +7044,27 @@ TEST_F(SourceLocationTest, GetSourceLocation) { const Descriptor *a_desc = file_desc->FindMessageTypeByName("A"); EXPECT_TRUE(a_desc->GetSourceLocation(&loc)); - EXPECT_EQ("2:1-7:2", PrintSourceLocation(loc)); + EXPECT_EQ("4:1-16:2", PrintSourceLocation(loc)); const Descriptor *a_b_desc = a_desc->FindNestedTypeByName("B"); EXPECT_TRUE(a_b_desc->GetSourceLocation(&loc)); - EXPECT_EQ("4:3-6:4", PrintSourceLocation(loc)); + EXPECT_EQ("7:3-9:4", PrintSourceLocation(loc)); const EnumDescriptor *e_desc = file_desc->FindEnumTypeByName("Indecision"); EXPECT_TRUE(e_desc->GetSourceLocation(&loc)); - EXPECT_EQ("8:1-12:2", PrintSourceLocation(loc)); + EXPECT_EQ("17:1-24:2", PrintSourceLocation(loc)); const EnumValueDescriptor *yes_desc = e_desc->FindValueByName("YES"); EXPECT_TRUE(yes_desc->GetSourceLocation(&loc)); - EXPECT_EQ("9:3-9:13", PrintSourceLocation(loc)); + EXPECT_EQ("21:3-21:42", PrintSourceLocation(loc)); const ServiceDescriptor *s_desc = file_desc->FindServiceByName("S"); EXPECT_TRUE(s_desc->GetSourceLocation(&loc)); - EXPECT_EQ("13:1-16:2", PrintSourceLocation(loc)); + EXPECT_EQ("25:1-35:2", PrintSourceLocation(loc)); const MethodDescriptor *m_desc = s_desc->FindMethodByName("Method"); EXPECT_TRUE(m_desc->GetSourceLocation(&loc)); - EXPECT_EQ("14:3-14:31", PrintSourceLocation(loc)); + EXPECT_EQ("29:3-29:31", PrintSourceLocation(loc)); } @@ -7014,16 +7077,426 @@ TEST_F(SourceLocationTest, ExtensionSourceLocation) { const FieldDescriptor *int32_extension_desc = file_desc->FindExtensionByName("int32_extension"); EXPECT_TRUE(int32_extension_desc->GetSourceLocation(&loc)); - EXPECT_EQ("21:3-21:41", PrintSourceLocation(loc)); + EXPECT_EQ("40:3-40:55", PrintSourceLocation(loc)); const Descriptor *c_desc = file_desc->FindMessageTypeByName("C"); EXPECT_TRUE(c_desc->GetSourceLocation(&loc)); - EXPECT_EQ("23:1-27:2", PrintSourceLocation(loc)); + EXPECT_EQ("42:1-46:2", PrintSourceLocation(loc)); const FieldDescriptor *message_extension_desc = c_desc->FindExtensionByName("message_extension"); EXPECT_TRUE(message_extension_desc->GetSourceLocation(&loc)); - EXPECT_EQ("25:5-25:41", PrintSourceLocation(loc)); + EXPECT_EQ("44:5-44:41", PrintSourceLocation(loc)); +} + +TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) { + // This one's a doozy. It checks every kind of option, including + // extension range options. + + // We are verifying that the file's source info contains correct + // info for interpreted options and that it does *not* contain + // any info for corresponding uninterpreted option path. + + SourceLocation loc; + + const FileDescriptor *file_desc = + GOOGLE_CHECK_NOTNULL(pool_.FindFileByName("/test/test.proto")); + + // File options + { + int path[] = {FileDescriptorProto::kOptionsFieldNumber, + FileOptions::kJavaPackageFieldNumber}; + int unint[] = {FileDescriptorProto::kOptionsFieldNumber, + FileOptions::kUninterpretedOptionFieldNumber, + 0}; + + std::vector<int> vpath(path, path + 2); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("2:1-2:37", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 3); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } + { + int path[] = {FileDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber}; + int unint[] = {FileDescriptorProto::kOptionsFieldNumber, + FileOptions::kUninterpretedOptionFieldNumber, + 1}; + std::vector<int> vpath(path, path + 2); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("3:1-3:35", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 3); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } + + // Message option + { + int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, + 0, + DescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber}; + int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber, + 0, + DescriptorProto::kOptionsFieldNumber, + MessageOptions::kUninterpretedOptionFieldNumber, + 0}; + std::vector<int> vpath(path, path + 4); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("5:3-5:36", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 5); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } + + // Field option + { + int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, + 0, + DescriptorProto::kFieldFieldNumber, + 0, + FieldDescriptorProto::kOptionsFieldNumber, + FieldOptions::kDeprecatedFieldNumber}; + int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber, + 0, + DescriptorProto::kFieldFieldNumber, + 0, + FieldDescriptorProto::kOptionsFieldNumber, + FieldOptions::kUninterpretedOptionFieldNumber, + 0}; + std::vector<int> vpath(path, path + 6); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("6:25-6:42", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 7); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } + + // Nested message option + { + int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, + 0, + DescriptorProto::kNestedTypeFieldNumber, + 0, + DescriptorProto::kFieldFieldNumber, + 0, + FieldDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber}; + int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber, + 0, + DescriptorProto::kNestedTypeFieldNumber, + 0, + DescriptorProto::kFieldFieldNumber, + 0, + FieldDescriptorProto::kOptionsFieldNumber, + FieldOptions::kUninterpretedOptionFieldNumber, + 0}; + std::vector<int> vpath(path, path + 8); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("8:28-8:55", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 9); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } + + // One-of option + { + int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, + 0, + DescriptorProto::kOneofDeclFieldNumber, + 0, + OneofDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber}; + int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber, + 0, + DescriptorProto::kOneofDeclFieldNumber, + 0, + OneofDescriptorProto::kOptionsFieldNumber, + OneofOptions::kUninterpretedOptionFieldNumber, + 0}; + std::vector<int> vpath(path, path + 6); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("11:5-11:40", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 7); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } + + // Enum option, repeated options + { + int path[] = {FileDescriptorProto::kEnumTypeFieldNumber, + 0, + EnumDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber, + 0}; + int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber, + 0, + EnumDescriptorProto::kOptionsFieldNumber, + EnumOptions::kUninterpretedOptionFieldNumber, + 0}; + std::vector<int> vpath(path, path + 5); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("18:3-18:31", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 5); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } + { + int path[] = {FileDescriptorProto::kEnumTypeFieldNumber, + 0, + EnumDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber, + 1}; + int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber, + 0, + EnumDescriptorProto::kOptionsFieldNumber, + EnumOptions::kUninterpretedOptionFieldNumber, + 1}; + std::vector<int> vpath(path, path + 5); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("19:3-19:31", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 5); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } + { + int path[] = {FileDescriptorProto::kEnumTypeFieldNumber, + 0, + EnumDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber, + 2}; + int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber, + 0, + EnumDescriptorProto::kOptionsFieldNumber, + OneofOptions::kUninterpretedOptionFieldNumber, + 2}; + std::vector<int> vpath(path, path + 5); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("20:3-20:31", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 5); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } + + // Enum value options + { + // option w/ message type that directly sets field + int path[] = {FileDescriptorProto::kEnumTypeFieldNumber, + 0, + EnumDescriptorProto::kValueFieldNumber, + 0, + EnumValueDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber, + kA_aFieldNumber}; + int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber, + 0, + EnumDescriptorProto::kValueFieldNumber, + 0, + EnumValueDescriptorProto::kOptionsFieldNumber, + EnumValueOptions::kUninterpretedOptionFieldNumber, + 0}; + std::vector<int> vpath(path, path + 7); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("21:14-21:40", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 7); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } + { + int path[] = {FileDescriptorProto::kEnumTypeFieldNumber, + 0, + EnumDescriptorProto::kValueFieldNumber, + 1, + EnumValueDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber}; + int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber, + 0, + EnumDescriptorProto::kValueFieldNumber, + 1, + EnumValueDescriptorProto::kOptionsFieldNumber, + EnumValueOptions::kUninterpretedOptionFieldNumber, + 0}; + std::vector<int> vpath(path, path + 6); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("22:14-22:42", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 7); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } + + // Service option, repeated options + { + int path[] = {FileDescriptorProto::kServiceFieldNumber, + 0, + ServiceDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber, + 0}; + int unint[] = {FileDescriptorProto::kServiceFieldNumber, + 0, + ServiceDescriptorProto::kOptionsFieldNumber, + ServiceOptions::kUninterpretedOptionFieldNumber, + 0}; + std::vector<int> vpath(path, path + 5); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("26:3-26:35", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 5); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } + { + int path[] = {FileDescriptorProto::kServiceFieldNumber, + 0, + ServiceDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber, + 1}; + int unint[] = {FileDescriptorProto::kServiceFieldNumber, + 0, + ServiceDescriptorProto::kOptionsFieldNumber, + ServiceOptions::kUninterpretedOptionFieldNumber, + 1}; + std::vector<int> vpath(path, path + 5); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("27:3-27:35", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 5); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } + { + int path[] = {FileDescriptorProto::kServiceFieldNumber, + 0, + ServiceDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber, + 2}; + int unint[] = {FileDescriptorProto::kServiceFieldNumber, + 0, + ServiceDescriptorProto::kOptionsFieldNumber, + ServiceOptions::kUninterpretedOptionFieldNumber, + 2}; + std::vector<int> vpath(path, path + 5); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("28:3-28:35", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 5); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } + + // Method options + { + int path[] = {FileDescriptorProto::kServiceFieldNumber, + 0, + ServiceDescriptorProto::kMethodFieldNumber, + 1, + MethodDescriptorProto::kOptionsFieldNumber, + MethodOptions::kDeprecatedFieldNumber}; + int unint[] = {FileDescriptorProto::kServiceFieldNumber, + 0, + ServiceDescriptorProto::kMethodFieldNumber, + 1, + MethodDescriptorProto::kOptionsFieldNumber, + MethodOptions::kUninterpretedOptionFieldNumber, + 0}; + std::vector<int> vpath(path, path + 6); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("32:5-32:30", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 7); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } + { + int path[] = {FileDescriptorProto::kServiceFieldNumber, + 0, + ServiceDescriptorProto::kMethodFieldNumber, + 1, + MethodDescriptorProto::kOptionsFieldNumber, + kCustomOptionFieldNumber}; + int unint[] = {FileDescriptorProto::kServiceFieldNumber, + 0, + ServiceDescriptorProto::kMethodFieldNumber, + 1, + MethodDescriptorProto::kOptionsFieldNumber, + MethodOptions::kUninterpretedOptionFieldNumber, + 1}; + std::vector<int> vpath(path, path + 6); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("33:5-33:41", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 7); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } + + // Extension range options + { + int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, + 1, + DescriptorProto::kExtensionRangeFieldNumber, + 0, + DescriptorProto_ExtensionRange::kOptionsFieldNumber}; + std::vector<int> vpath(path, path + 5); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("37:40-37:67", PrintSourceLocation(loc)); + } + { + int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, + 1, + DescriptorProto::kExtensionRangeFieldNumber, + 0, + DescriptorProto_ExtensionRange::kOptionsFieldNumber, + kCustomOptionFieldNumber}; + int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber, + 1, + DescriptorProto::kExtensionRangeFieldNumber, + 0, + DescriptorProto_ExtensionRange::kOptionsFieldNumber, + ExtensionRangeOptions::kUninterpretedOptionFieldNumber, + 0}; + std::vector<int> vpath(path, path + 6); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("37:41-37:66", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 7); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } + { + int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, + 1, + DescriptorProto::kExtensionRangeFieldNumber, + 1, + DescriptorProto_ExtensionRange::kOptionsFieldNumber, + kCustomOptionFieldNumber}; + int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber, + 1, + DescriptorProto::kExtensionRangeFieldNumber, + 1, + DescriptorProto_ExtensionRange::kOptionsFieldNumber, + ExtensionRangeOptions::kUninterpretedOptionFieldNumber, + 0}; + std::vector<int> vpath(path, path + 6); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("37:41-37:66", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 7); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } + + // Field option on extension + { + int path[] = {FileDescriptorProto::kExtensionFieldNumber, + 0, + FieldDescriptorProto::kOptionsFieldNumber, + FieldOptions::kPackedFieldNumber}; + int unint[] = {FileDescriptorProto::kExtensionFieldNumber, + 0, + FieldDescriptorProto::kOptionsFieldNumber, + FieldOptions::kUninterpretedOptionFieldNumber, + 0}; + std::vector<int> vpath(path, path + 4); + EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc)); + EXPECT_EQ("40:42-40:53", PrintSourceLocation(loc)); + + std::vector<int> vunint(unint, unint + 5); + EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc)); + } } // Missing SourceCodeInfo doesn't cause crash: diff --git a/src/google/protobuf/generated_message_util.h b/src/google/protobuf/generated_message_util.h index c0e41bf7..c26e3e52 100644 --- a/src/google/protobuf/generated_message_util.h +++ b/src/google/protobuf/generated_message_util.h @@ -175,7 +175,7 @@ struct LIBPROTOBUF_EXPORT FieldMetadata { inline bool IsPresent(const void* base, uint32 hasbit) { const uint32* has_bits_array = static_cast<const uint32*>(base); - return has_bits_array[hasbit / 32] & (1u << (hasbit & 31)); + return (has_bits_array[hasbit / 32] & (1u << (hasbit & 31))) != 0; } inline bool IsOneofPresent(const void* base, uint32 offset, uint32 tag) { diff --git a/src/google/protobuf/io/coded_stream.h b/src/google/protobuf/io/coded_stream.h index 9dad1c61..0f70ecde 100644 --- a/src/google/protobuf/io/coded_stream.h +++ b/src/google/protobuf/io/coded_stream.h @@ -851,7 +851,7 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { } static bool IsDefaultSerializationDeterministic() { - return default_serialization_deterministic_.load(std::memory_order_relaxed); + return default_serialization_deterministic_.load(std::memory_order_relaxed) != 0; } private: diff --git a/src/google/protobuf/stubs/atomic_sequence_num.h b/src/google/protobuf/stubs/atomic_sequence_num.h deleted file mode 100644 index bb20942f..00000000 --- a/src/google/protobuf/stubs/atomic_sequence_num.h +++ /dev/null @@ -1,54 +0,0 @@ -// 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. -#ifndef GOOGLE_PROTOBUF_ATOMIC_SEQUENCE_NUM_H_ -#define GOOGLE_PROTOBUF_ATOMIC_SEQUENCE_NUM_H_ - -#include <google/protobuf/stubs/atomicops.h> - -namespace google { -namespace protobuf { -namespace internal { - -class SequenceNumber { - public: - SequenceNumber() : word_(0) {} - - AtomicWord GetNext() { - return NoBarrier_AtomicIncrement(&word_, 1) - 1; - } - private: - AtomicWord word_; -}; - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMIC_SEQUENCE_NUM_H_ diff --git a/src/google/protobuf/stubs/atomicops.h b/src/google/protobuf/stubs/atomicops.h deleted file mode 100644 index cb4553b1..00000000 --- a/src/google/protobuf/stubs/atomicops.h +++ /dev/null @@ -1,237 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 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. - -// The routines exported by this module are subtle. If you use them, even if -// you get the code right, it will depend on careful reasoning about atomicity -// and memory ordering; it will be less readable, and harder to maintain. If -// you plan to use these routines, you should have a good reason, such as solid -// evidence that performance would otherwise suffer, or there being no -// alternative. You should assume only properties explicitly guaranteed by the -// specifications in this file. You are almost certainly _not_ writing code -// just for the x86; if you assume x86 semantics, x86 hardware bugs and -// implementations on other archtectures will cause your code to break. If you -// do not know what you are doing, avoid these routines, and use a Mutex. -// -// It is incorrect to make direct assignments to/from an atomic variable. -// You should use one of the Load or Store routines. The NoBarrier -// versions are provided when no barriers are needed: -// NoBarrier_Store() -// NoBarrier_Load() -// Although there are currently no compiler enforcement, you are encouraged -// to use these. - -// This header and the implementations for each platform (located in -// atomicops_internals_*) must be kept in sync with the upstream code (V8). - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_H_ - -// Don't include this file for people not concerned about thread safety. -#ifndef GOOGLE_PROTOBUF_NO_THREAD_SAFETY - -#include <google/protobuf/stubs/common.h> -#include <google/protobuf/stubs/platform_macros.h> - -namespace google { -namespace protobuf { -namespace internal { - -#ifdef GOOGLE_PROTOBUF_ARCH_32_BIT - typedef intptr_t Atomic32; - typedef int64 Atomic64; -#else - // We need to be able to go between Atomic64 and AtomicWord implicitly. This - // means Atomic64 and AtomicWord should be the same type on 64-bit. - #if defined(__ILP32__) || defined(GOOGLE_PROTOBUF_OS_NACL) - // NaCl's intptr_t is not actually 64-bits on 64-bit! - // http://code.google.com/p/nativeclient/issues/detail?id=1162 - // sparcv9's pointer type is 32bits - typedef intptr_t Atomic32; - typedef int64 Atomic64; - #else - typedef int32 Atomic32; - typedef intptr_t Atomic64; - #endif -#endif - -// Use AtomicWord for a machine-sized pointer. It will use the Atomic32 or -// Atomic64 routines below, depending on your architecture. -typedef intptr_t AtomicWord; - -// Atomically execute: -// result = *ptr; -// if (*ptr == old_value) -// *ptr = new_value; -// return result; -// -// I.e., replace "*ptr" with "new_value" if "*ptr" used to be "old_value". -// Always return the old value of "*ptr" -// -// This routine implies no memory barriers. -Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value); - -// Atomically store new_value into *ptr, returning the previous value held in -// *ptr. This routine implies no memory barriers. -Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, Atomic32 new_value); - -// Atomically increment *ptr by "increment". Returns the new value of -// *ptr with the increment applied. This routine implies no memory barriers. -Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment); - -Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment); - -// These following lower-level operations are typically useful only to people -// implementing higher-level synchronization operations like spinlocks, -// mutexes, and condition-variables. They combine CompareAndSwap(), a load, or -// a store with appropriate memory-ordering instructions. "Acquire" operations -// ensure that no later memory access can be reordered ahead of the operation. -// "Release" operations ensure that no previous memory access can be reordered -// after the operation. "Barrier" operations have both "Acquire" and "Release" -// semantics. A MemoryBarrierInternal() has "Barrier" semantics, but does no -// memory access. -Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value); -Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value); - -// This function was renamed from MemoryBarrier to MemoryBarrierInternal -// because MemoryBarrier is a define in Windows ARM builds and we do not -// undefine it because we call it from this function. -void MemoryBarrierInternal(); -void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value); -void Acquire_Store(volatile Atomic32* ptr, Atomic32 value); -void Release_Store(volatile Atomic32* ptr, Atomic32 value); - -Atomic32 NoBarrier_Load(volatile const Atomic32* ptr); -Atomic32 Acquire_Load(volatile const Atomic32* ptr); -Atomic32 Release_Load(volatile const Atomic32* ptr); - -// 64-bit atomic operations (only available on 64-bit processors). -#ifdef GOOGLE_PROTOBUF_ARCH_64_BIT -Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value); -Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, Atomic64 new_value); -Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment); -Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment); - -Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value); -Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value); -void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value); -void Acquire_Store(volatile Atomic64* ptr, Atomic64 value); -void Release_Store(volatile Atomic64* ptr, Atomic64 value); -Atomic64 NoBarrier_Load(volatile const Atomic64* ptr); -Atomic64 Acquire_Load(volatile const Atomic64* ptr); -Atomic64 Release_Load(volatile const Atomic64* ptr); -#endif // GOOGLE_PROTOBUF_ARCH_64_BIT - -} // namespace internal -} // namespace protobuf -} // namespace google - -// Include our platform specific implementation. -#define GOOGLE_PROTOBUF_ATOMICOPS_ERROR \ -"Atomic operations are not supported on your platform" - -// ThreadSanitizer, http://clang.llvm.org/docs/ThreadSanitizer.html. -#if defined(THREAD_SANITIZER) -#include <google/protobuf/stubs/atomicops_internals_tsan.h> -// MSVC. -#elif defined(_MSC_VER) -#if defined(GOOGLE_PROTOBUF_ARCH_IA32) || defined(GOOGLE_PROTOBUF_ARCH_X64) || defined(GOOGLE_PROTOBUF_ARCH_ARM) -#include <google/protobuf/stubs/atomicops_internals_x86_msvc.h> -#else -#error GOOGLE_PROTOBUF_ATOMICOPS_ERROR -#endif - -// Solaris -#elif defined(GOOGLE_PROTOBUF_OS_SOLARIS) -#include <google/protobuf/stubs/atomicops_internals_solaris.h> - -// AIX -#elif defined(GOOGLE_PROTOBUF_OS_AIX) -#include <google/protobuf/stubs/atomicops_internals_power.h> - -// GCC. -#elif defined(__GNUC__) -#if defined(GOOGLE_PROTOBUF_ARCH_IA32) || defined(GOOGLE_PROTOBUF_ARCH_X64) -#include <google/protobuf/stubs/atomicops_internals_x86_gcc.h> -#elif defined(GOOGLE_PROTOBUF_ARCH_ARM) && defined(__linux__) -#if (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4)) -#include <google/protobuf/stubs/atomicops_internals_generic_gcc.h> -#else -#include <google/protobuf/stubs/atomicops_internals_arm_gcc.h> -#endif -#elif defined(GOOGLE_PROTOBUF_ARCH_AARCH64) -#include <google/protobuf/stubs/atomicops_internals_arm64_gcc.h> -#elif defined(GOOGLE_PROTOBUF_ARCH_ARM_QNX) -#include <google/protobuf/stubs/atomicops_internals_arm_qnx.h> -#elif defined(GOOGLE_PROTOBUF_ARCH_MIPS) || defined(GOOGLE_PROTOBUF_ARCH_MIPS64) -#include <google/protobuf/stubs/atomicops_internals_mips_gcc.h> -#elif defined(GOOGLE_PROTOBUF_ARCH_POWER) -#include <google/protobuf/stubs/atomicops_internals_power.h> -#elif defined(__native_client__) -// The static_asserts in the C++11 atomics implementation cause it to fail -// with certain compilers, e.g. nvcc on macOS. Don't use elsewhere unless -// the TODO in that file is addressed. -#include <google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h> -#elif defined(GOOGLE_PROTOBUF_ARCH_PPC) -#include <google/protobuf/stubs/atomicops_internals_ppc_gcc.h> -#elif (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4)) -#include <google/protobuf/stubs/atomicops_internals_generic_gcc.h> -#elif defined(__clang__) -#if __has_extension(c_atomic) -#include <google/protobuf/stubs/atomicops_internals_generic_gcc.h> -#else -#error GOOGLE_PROTOBUF_ATOMICOPS_ERROR -#endif -#else -#error GOOGLE_PROTOBUF_ATOMICOPS_ERROR -#endif - -// Unknown. -#else -#error GOOGLE_PROTOBUF_ATOMICOPS_ERROR -#endif - -#undef GOOGLE_PROTOBUF_ATOMICOPS_ERROR - -#endif // GOOGLE_PROTOBUF_NO_THREAD_SAFETY - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_arm64_gcc.h b/src/google/protobuf/stubs/atomicops_internals_arm64_gcc.h deleted file mode 100644 index 9a69d21a..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_arm64_gcc.h +++ /dev/null @@ -1,325 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 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 is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM64_GCC_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM64_GCC_H_ - -namespace google { -namespace protobuf { -namespace internal { - -inline void MemoryBarrierInternal() { - __asm__ __volatile__ ("dmb ish" ::: "memory"); // NOLINT -} - -// NoBarrier versions of the operation include "memory" in the clobber list. -// This is not required for direct usage of the NoBarrier versions of the -// operations. However this is required for correctness when they are used as -// part of the Acquire or Release versions, to ensure that nothing from outside -// the call is reordered between the operation and the memory barrier. This does -// not change the code generated, so has no or minimal impact on the -// NoBarrier operations. - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 prev; - int32_t temp; - - __asm__ __volatile__ ( // NOLINT - "0: \n\t" - "ldxr %w[prev], %[ptr] \n\t" // Load the previous value. - "cmp %w[prev], %w[old_value] \n\t" - "bne 1f \n\t" - "stxr %w[temp], %w[new_value], %[ptr] \n\t" // Try to store the new value. - "cbnz %w[temp], 0b \n\t" // Retry if it did not work. - "1: \n\t" - : [prev]"=&r" (prev), - [temp]"=&r" (temp), - [ptr]"+Q" (*ptr) - : [old_value]"IJr" (old_value), - [new_value]"r" (new_value) - : "cc", "memory" - ); // NOLINT - - return prev; -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - Atomic32 result; - int32_t temp; - - __asm__ __volatile__ ( // NOLINT - "0: \n\t" - "ldxr %w[result], %[ptr] \n\t" // Load the previous value. - "stxr %w[temp], %w[new_value], %[ptr] \n\t" // Try to store the new value. - "cbnz %w[temp], 0b \n\t" // Retry if it did not work. - : [result]"=&r" (result), - [temp]"=&r" (temp), - [ptr]"+Q" (*ptr) - : [new_value]"r" (new_value) - : "memory" - ); // NOLINT - - return result; -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - Atomic32 result; - int32_t temp; - - __asm__ __volatile__ ( // NOLINT - "0: \n\t" - "ldxr %w[result], %[ptr] \n\t" // Load the previous value. - "add %w[result], %w[result], %w[increment]\n\t" - "stxr %w[temp], %w[result], %[ptr] \n\t" // Try to store the result. - "cbnz %w[temp], 0b \n\t" // Retry on failure. - : [result]"=&r" (result), - [temp]"=&r" (temp), - [ptr]"+Q" (*ptr) - : [increment]"IJr" (increment) - : "memory" - ); // NOLINT - - return result; -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - MemoryBarrierInternal(); - Atomic32 result = NoBarrier_AtomicIncrement(ptr, increment); - MemoryBarrierInternal(); - - return result; -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 prev = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - MemoryBarrierInternal(); - - return prev; -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - MemoryBarrierInternal(); - Atomic32 prev = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - - return prev; -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; - MemoryBarrierInternal(); -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - __asm__ __volatile__ ( // NOLINT - "stlr %w[value], %[ptr] \n\t" - : [ptr]"=Q" (*ptr) - : [value]"r" (value) - : "memory" - ); // NOLINT -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return *ptr; -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - Atomic32 value; - - __asm__ __volatile__ ( // NOLINT - "ldar %w[value], %[ptr] \n\t" - : [value]"=r" (value) - : [ptr]"Q" (*ptr) - : "memory" - ); // NOLINT - - return value; -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - MemoryBarrierInternal(); - return *ptr; -} - -// 64-bit versions of the operations. -// See the 32-bit versions for comments. - -inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 prev; - int32_t temp; - - __asm__ __volatile__ ( // NOLINT - "0: \n\t" - "ldxr %[prev], %[ptr] \n\t" - "cmp %[prev], %[old_value] \n\t" - "bne 1f \n\t" - "stxr %w[temp], %[new_value], %[ptr] \n\t" - "cbnz %w[temp], 0b \n\t" - "1: \n\t" - : [prev]"=&r" (prev), - [temp]"=&r" (temp), - [ptr]"+Q" (*ptr) - : [old_value]"IJr" (old_value), - [new_value]"r" (new_value) - : "cc", "memory" - ); // NOLINT - - return prev; -} - -inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, - Atomic64 new_value) { - Atomic64 result; - int32_t temp; - - __asm__ __volatile__ ( // NOLINT - "0: \n\t" - "ldxr %[result], %[ptr] \n\t" - "stxr %w[temp], %[new_value], %[ptr] \n\t" - "cbnz %w[temp], 0b \n\t" - : [result]"=&r" (result), - [temp]"=&r" (temp), - [ptr]"+Q" (*ptr) - : [new_value]"r" (new_value) - : "memory" - ); // NOLINT - - return result; -} - -inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - Atomic64 result; - int32_t temp; - - __asm__ __volatile__ ( // NOLINT - "0: \n\t" - "ldxr %[result], %[ptr] \n\t" - "add %[result], %[result], %[increment] \n\t" - "stxr %w[temp], %[result], %[ptr] \n\t" - "cbnz %w[temp], 0b \n\t" - : [result]"=&r" (result), - [temp]"=&r" (temp), - [ptr]"+Q" (*ptr) - : [increment]"IJr" (increment) - : "memory" - ); // NOLINT - - return result; -} - -inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - MemoryBarrierInternal(); - Atomic64 result = NoBarrier_AtomicIncrement(ptr, increment); - MemoryBarrierInternal(); - - return result; -} - -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 prev = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - MemoryBarrierInternal(); - - return prev; -} - -inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - MemoryBarrierInternal(); - Atomic64 prev = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - - return prev; -} - -inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; - MemoryBarrierInternal(); -} - -inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { - __asm__ __volatile__ ( // NOLINT - "stlr %x[value], %[ptr] \n\t" - : [ptr]"=Q" (*ptr) - : [value]"r" (value) - : "memory" - ); // NOLINT -} - -inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { - return *ptr; -} - -inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { - Atomic64 value; - - __asm__ __volatile__ ( // NOLINT - "ldar %x[value], %[ptr] \n\t" - : [value]"=r" (value) - : [ptr]"Q" (*ptr) - : "memory" - ); // NOLINT - - return value; -} - -inline Atomic64 Release_Load(volatile const Atomic64* ptr) { - MemoryBarrierInternal(); - return *ptr; -} - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM64_GCC_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_arm_gcc.h b/src/google/protobuf/stubs/atomicops_internals_arm_gcc.h deleted file mode 100644 index 6e2de67f..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_arm_gcc.h +++ /dev/null @@ -1,151 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 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 is an internal atomic implementation, use atomicops.h instead. -// -// LinuxKernelCmpxchg and Barrier_AtomicIncrement are from Google Gears. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM_GCC_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM_GCC_H_ - -namespace google { -namespace protobuf { -namespace internal { - -// 0xffff0fc0 is the hard coded address of a function provided by -// the kernel which implements an atomic compare-exchange. On older -// ARM architecture revisions (pre-v6) this may be implemented using -// a syscall. This address is stable, and in active use (hard coded) -// by at least glibc-2.7 and the Android C library. -typedef Atomic32 (*LinuxKernelCmpxchgFunc)(Atomic32 old_value, - Atomic32 new_value, - volatile Atomic32* ptr); -LinuxKernelCmpxchgFunc pLinuxKernelCmpxchg __attribute__((weak)) = - (LinuxKernelCmpxchgFunc) 0xffff0fc0; - -typedef void (*LinuxKernelMemoryBarrierFunc)(void); -LinuxKernelMemoryBarrierFunc pLinuxKernelMemoryBarrier __attribute__((weak)) = - (LinuxKernelMemoryBarrierFunc) 0xffff0fa0; - - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 prev_value = *ptr; - do { - if (!pLinuxKernelCmpxchg(old_value, new_value, - const_cast<Atomic32*>(ptr))) { - return old_value; - } - prev_value = *ptr; - } while (prev_value == old_value); - return prev_value; -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - Atomic32 old_value; - do { - old_value = *ptr; - } while (pLinuxKernelCmpxchg(old_value, new_value, - const_cast<Atomic32*>(ptr))); - return old_value; -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return Barrier_AtomicIncrement(ptr, increment); -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - for (;;) { - // Atomic exchange the old value with an incremented one. - Atomic32 old_value = *ptr; - Atomic32 new_value = old_value + increment; - if (pLinuxKernelCmpxchg(old_value, new_value, - const_cast<Atomic32*>(ptr)) == 0) { - // The exchange took place as expected. - return new_value; - } - // Otherwise, *ptr changed mid-loop and we need to retry. - } -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; -} - -inline void MemoryBarrierInternal() { - pLinuxKernelMemoryBarrier(); -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; - MemoryBarrierInternal(); -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - MemoryBarrierInternal(); - *ptr = value; -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return *ptr; -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - Atomic32 value = *ptr; - MemoryBarrierInternal(); - return value; -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - MemoryBarrierInternal(); - return *ptr; -} - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM_GCC_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_arm_qnx.h b/src/google/protobuf/stubs/atomicops_internals_arm_qnx.h deleted file mode 100644 index cd97e0c9..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_arm_qnx.h +++ /dev/null @@ -1,146 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 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 is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM_QNX_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM_QNX_H_ - -// For _smp_cmpxchg() -#include <pthread.h> - -namespace google { -namespace protobuf { -namespace internal { - -inline Atomic32 QNXCmpxchg(Atomic32 old_value, - Atomic32 new_value, - volatile Atomic32* ptr) { - return static_cast<Atomic32>( - _smp_cmpxchg((volatile unsigned *)ptr, - (unsigned)old_value, - (unsigned)new_value)); -} - - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 prev_value = *ptr; - do { - if (!QNXCmpxchg(old_value, new_value, - const_cast<Atomic32*>(ptr))) { - return old_value; - } - prev_value = *ptr; - } while (prev_value == old_value); - return prev_value; -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - Atomic32 old_value; - do { - old_value = *ptr; - } while (QNXCmpxchg(old_value, new_value, - const_cast<Atomic32*>(ptr))); - return old_value; -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return Barrier_AtomicIncrement(ptr, increment); -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - for (;;) { - // Atomic exchange the old value with an incremented one. - Atomic32 old_value = *ptr; - Atomic32 new_value = old_value + increment; - if (QNXCmpxchg(old_value, new_value, - const_cast<Atomic32*>(ptr)) == 0) { - // The exchange took place as expected. - return new_value; - } - // Otherwise, *ptr changed mid-loop and we need to retry. - } -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; -} - -inline void MemoryBarrierInternal() { - __sync_synchronize(); -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; - MemoryBarrierInternal(); -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - MemoryBarrierInternal(); - *ptr = value; -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return *ptr; -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - Atomic32 value = *ptr; - MemoryBarrierInternal(); - return value; -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - MemoryBarrierInternal(); - return *ptr; -} - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM_QNX_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h b/src/google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h deleted file mode 100644 index 44ef9c9e..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h +++ /dev/null @@ -1,231 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 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 is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_GENERIC_C11_ATOMIC_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_GENERIC_C11_ATOMIC_H_ - -#include <atomic> - -namespace google { -namespace protobuf { -namespace internal { - -// This implementation is transitional and maintains the original API for -// atomicops.h. This requires casting memory locations to the atomic types, and -// assumes that the API and the C++11 implementation are layout-compatible, -// which isn't true for all implementations or hardware platforms. The static -// assertion should detect this issue, were it to fire then this header -// shouldn't be used. -// -// TODO(jfb) If this header manages to stay committed then the API should be -// modified, and all call sites updated. -typedef volatile std::atomic<Atomic32>* AtomicLocation32; -static_assert(sizeof(*(AtomicLocation32) nullptr) == sizeof(Atomic32), - "incompatible 32-bit atomic layout"); - -inline void MemoryBarrierInternal() { -#if defined(__GLIBCXX__) - // Work around libstdc++ bug 51038 where atomic_thread_fence was declared but - // not defined, leading to the linker complaining about undefined references. - __atomic_thread_fence(std::memory_order_seq_cst); -#else - std::atomic_thread_fence(std::memory_order_seq_cst); -#endif -} - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - ((AtomicLocation32)ptr) - ->compare_exchange_strong(old_value, - new_value, - std::memory_order_relaxed, - std::memory_order_relaxed); - return old_value; -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - return ((AtomicLocation32)ptr) - ->exchange(new_value, std::memory_order_relaxed); -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return increment + - ((AtomicLocation32)ptr) - ->fetch_add(increment, std::memory_order_relaxed); -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return increment + ((AtomicLocation32)ptr)->fetch_add(increment); -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - ((AtomicLocation32)ptr) - ->compare_exchange_strong(old_value, - new_value, - std::memory_order_acquire, - std::memory_order_acquire); - return old_value; -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - ((AtomicLocation32)ptr) - ->compare_exchange_strong(old_value, - new_value, - std::memory_order_release, - std::memory_order_relaxed); - return old_value; -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - ((AtomicLocation32)ptr)->store(value, std::memory_order_relaxed); -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - ((AtomicLocation32)ptr)->store(value, std::memory_order_relaxed); - MemoryBarrierInternal(); -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - ((AtomicLocation32)ptr)->store(value, std::memory_order_release); -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return ((AtomicLocation32)ptr)->load(std::memory_order_relaxed); -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - return ((AtomicLocation32)ptr)->load(std::memory_order_acquire); -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - MemoryBarrierInternal(); - return ((AtomicLocation32)ptr)->load(std::memory_order_relaxed); -} - -#if defined(GOOGLE_PROTOBUF_ARCH_64_BIT) - -typedef volatile std::atomic<Atomic64>* AtomicLocation64; -static_assert(sizeof(*(AtomicLocation64) nullptr) == sizeof(Atomic64), - "incompatible 64-bit atomic layout"); - -inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - ((AtomicLocation64)ptr) - ->compare_exchange_strong(old_value, - new_value, - std::memory_order_relaxed, - std::memory_order_relaxed); - return old_value; -} - -inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, - Atomic64 new_value) { - return ((AtomicLocation64)ptr) - ->exchange(new_value, std::memory_order_relaxed); -} - -inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - return increment + - ((AtomicLocation64)ptr) - ->fetch_add(increment, std::memory_order_relaxed); -} - -inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - return increment + ((AtomicLocation64)ptr)->fetch_add(increment); -} - -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - ((AtomicLocation64)ptr) - ->compare_exchange_strong(old_value, - new_value, - std::memory_order_acquire, - std::memory_order_acquire); - return old_value; -} - -inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - ((AtomicLocation64)ptr) - ->compare_exchange_strong(old_value, - new_value, - std::memory_order_release, - std::memory_order_relaxed); - return old_value; -} - -inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { - ((AtomicLocation64)ptr)->store(value, std::memory_order_relaxed); -} - -inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { - ((AtomicLocation64)ptr)->store(value, std::memory_order_relaxed); - MemoryBarrierInternal(); -} - -inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { - ((AtomicLocation64)ptr)->store(value, std::memory_order_release); -} - -inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { - return ((AtomicLocation64)ptr)->load(std::memory_order_relaxed); -} - -inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { - return ((AtomicLocation64)ptr)->load(std::memory_order_acquire); -} - -inline Atomic64 Release_Load(volatile const Atomic64* ptr) { - MemoryBarrierInternal(); - return ((AtomicLocation64)ptr)->load(std::memory_order_relaxed); -} - -#endif // defined(GOOGLE_PROTOBUF_ARCH_64_BIT) - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_GENERIC_C11_ATOMIC_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_generic_gcc.h b/src/google/protobuf/stubs/atomicops_internals_generic_gcc.h deleted file mode 100644 index 075c406a..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_generic_gcc.h +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright 2013 Red Hat 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 Red Hat 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 is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_GENERIC_GCC_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_GENERIC_GCC_H_ - -namespace google { -namespace protobuf { -namespace internal { - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - __atomic_compare_exchange_n(ptr, &old_value, new_value, false, - __ATOMIC_RELAXED, __ATOMIC_RELAXED); - return old_value; -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - return __atomic_exchange_n(ptr, new_value, __ATOMIC_RELAXED); -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return __atomic_add_fetch(ptr, increment, __ATOMIC_RELAXED); -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return __atomic_add_fetch(ptr, increment, __ATOMIC_SEQ_CST); -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - __atomic_compare_exchange_n(ptr, &old_value, new_value, false, - __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE); - return old_value; -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - __atomic_compare_exchange_n(ptr, &old_value, new_value, false, - __ATOMIC_RELEASE, __ATOMIC_ACQUIRE); - return old_value; -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - __atomic_store_n(ptr, value, __ATOMIC_RELAXED); -} - -inline void MemoryBarrierInternal() { - __sync_synchronize(); -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - __atomic_store_n(ptr, value, __ATOMIC_SEQ_CST); -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - __atomic_store_n(ptr, value, __ATOMIC_RELEASE); -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return __atomic_load_n(ptr, __ATOMIC_RELAXED); -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - return __atomic_load_n(ptr, __ATOMIC_ACQUIRE); -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - return __atomic_load_n(ptr, __ATOMIC_SEQ_CST); -} - -#ifdef __LP64__ - -inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { - __atomic_store_n(ptr, value, __ATOMIC_RELEASE); -} - -inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { - return __atomic_load_n(ptr, __ATOMIC_ACQUIRE); -} - -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - __atomic_compare_exchange_n(ptr, &old_value, new_value, false, - __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE); - return old_value; -} - -inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - __atomic_compare_exchange_n(ptr, &old_value, new_value, false, - __ATOMIC_RELAXED, __ATOMIC_RELAXED); - return old_value; -} - -inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - return __atomic_add_fetch(ptr, increment, __ATOMIC_RELAXED); -} - -inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { - __atomic_store_n(ptr, value, __ATOMIC_RELAXED); -} - -inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, - Atomic64 new_value) { - return __atomic_exchange_n(ptr, new_value, __ATOMIC_RELAXED); -} - -inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { - return __atomic_load_n(ptr, __ATOMIC_RELAXED); -} - -inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - __atomic_compare_exchange_n(ptr, &old_value, new_value, false, - __ATOMIC_RELEASE, __ATOMIC_ACQUIRE); - return old_value; -} - -#endif // defined(__LP64__) - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_GENERIC_GCC_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_mips_gcc.h b/src/google/protobuf/stubs/atomicops_internals_mips_gcc.h deleted file mode 100644 index 6ce6820e..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_mips_gcc.h +++ /dev/null @@ -1,313 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 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 is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_MIPS_GCC_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_MIPS_GCC_H_ - -#define ATOMICOPS_COMPILER_BARRIER() __asm__ __volatile__("" : : : "memory") - -namespace google { -namespace protobuf { -namespace internal { - -// Atomically execute: -// result = *ptr; -// if (*ptr == old_value) -// *ptr = new_value; -// return result; -// -// I.e., replace "*ptr" with "new_value" if "*ptr" used to be "old_value". -// Always return the old value of "*ptr" -// -// This routine implies no memory barriers. -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 prev, tmp; - __asm__ __volatile__(".set push\n" - ".set noreorder\n" - "1:\n" - "ll %0, %5\n" // prev = *ptr - "bne %0, %3, 2f\n" // if (prev != old_value) goto 2 - "move %2, %4\n" // tmp = new_value - "sc %2, %1\n" // *ptr = tmp (with atomic check) - "beqz %2, 1b\n" // start again on atomic error - "nop\n" // delay slot nop - "2:\n" - ".set pop\n" - : "=&r" (prev), "=m" (*ptr), "=&r" (tmp) - : "r" (old_value), "r" (new_value), "m" (*ptr) - : "memory"); - return prev; -} - -// Atomically store new_value into *ptr, returning the previous value held in -// *ptr. This routine implies no memory barriers. -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - Atomic32 temp, old; - __asm__ __volatile__(".set push\n" - ".set noreorder\n" - "1:\n" - "ll %1, %4\n" // old = *ptr - "move %0, %3\n" // temp = new_value - "sc %0, %2\n" // *ptr = temp (with atomic check) - "beqz %0, 1b\n" // start again on atomic error - "nop\n" // delay slot nop - ".set pop\n" - : "=&r" (temp), "=&r" (old), "=m" (*ptr) - : "r" (new_value), "m" (*ptr) - : "memory"); - - return old; -} - -// Atomically increment *ptr by "increment". Returns the new value of -// *ptr with the increment applied. This routine implies no memory barriers. -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - Atomic32 temp, temp2; - - __asm__ __volatile__(".set push\n" - ".set noreorder\n" - "1:\n" - "ll %0, %4\n" // temp = *ptr - "addu %1, %0, %3\n" // temp2 = temp + increment - "sc %1, %2\n" // *ptr = temp2 (with atomic check) - "beqz %1, 1b\n" // start again on atomic error - "addu %1, %0, %3\n" // temp2 = temp + increment - ".set pop\n" - : "=&r" (temp), "=&r" (temp2), "=m" (*ptr) - : "Ir" (increment), "m" (*ptr) - : "memory"); - // temp2 now holds the final value. - return temp2; -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - ATOMICOPS_COMPILER_BARRIER(); - Atomic32 res = NoBarrier_AtomicIncrement(ptr, increment); - ATOMICOPS_COMPILER_BARRIER(); - return res; -} - -// "Acquire" operations -// ensure that no later memory access can be reordered ahead of the operation. -// "Release" operations ensure that no previous memory access can be reordered -// after the operation. "Barrier" operations have both "Acquire" and "Release" -// semantics. A MemoryBarrierInternal() has "Barrier" semantics, but does no -// memory access. -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - ATOMICOPS_COMPILER_BARRIER(); - Atomic32 res = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - ATOMICOPS_COMPILER_BARRIER(); - return res; -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - ATOMICOPS_COMPILER_BARRIER(); - Atomic32 res = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - ATOMICOPS_COMPILER_BARRIER(); - return res; -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; -} - -inline void MemoryBarrierInternal() { - __asm__ __volatile__("sync" : : : "memory"); -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; - MemoryBarrierInternal(); -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - MemoryBarrierInternal(); - *ptr = value; -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return *ptr; -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - Atomic32 value = *ptr; - MemoryBarrierInternal(); - return value; -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - MemoryBarrierInternal(); - return *ptr; -} - -#if defined(__LP64__) -// 64-bit versions of the atomic ops. - -inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 prev, tmp; - __asm__ __volatile__(".set push\n" - ".set noreorder\n" - "1:\n" - "lld %0, %5\n" // prev = *ptr - "bne %0, %3, 2f\n" // if (prev != old_value) goto 2 - "move %2, %4\n" // tmp = new_value - "scd %2, %1\n" // *ptr = tmp (with atomic check) - "beqz %2, 1b\n" // start again on atomic error - "nop\n" // delay slot nop - "2:\n" - ".set pop\n" - : "=&r" (prev), "=m" (*ptr), "=&r" (tmp) - : "r" (old_value), "r" (new_value), "m" (*ptr) - : "memory"); - return prev; -} - -// Atomically store new_value into *ptr, returning the previous value held in -// *ptr. This routine implies no memory barriers. -inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, - Atomic64 new_value) { - Atomic64 temp, old; - __asm__ __volatile__(".set push\n" - ".set noreorder\n" - "1:\n" - "lld %1, %4\n" // old = *ptr - "move %0, %3\n" // temp = new_value - "scd %0, %2\n" // *ptr = temp (with atomic check) - "beqz %0, 1b\n" // start again on atomic error - "nop\n" // delay slot nop - ".set pop\n" - : "=&r" (temp), "=&r" (old), "=m" (*ptr) - : "r" (new_value), "m" (*ptr) - : "memory"); - - return old; -} - -// Atomically increment *ptr by "increment". Returns the new value of -// *ptr with the increment applied. This routine implies no memory barriers. -inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - Atomic64 temp, temp2; - - __asm__ __volatile__(".set push\n" - ".set noreorder\n" - "1:\n" - "lld %0, %4\n" // temp = *ptr - "daddu %1, %0, %3\n" // temp2 = temp + increment - "scd %1, %2\n" // *ptr = temp2 (with atomic check) - "beqz %1, 1b\n" // start again on atomic error - "daddu %1, %0, %3\n" // temp2 = temp + increment - ".set pop\n" - : "=&r" (temp), "=&r" (temp2), "=m" (*ptr) - : "Ir" (increment), "m" (*ptr) - : "memory"); - // temp2 now holds the final value. - return temp2; -} - -inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - MemoryBarrierInternal(); - Atomic64 res = NoBarrier_AtomicIncrement(ptr, increment); - MemoryBarrierInternal(); - return res; -} - -// "Acquire" operations -// ensure that no later memory access can be reordered ahead of the operation. -// "Release" operations ensure that no previous memory access can be reordered -// after the operation. "Barrier" operations have both "Acquire" and "Release" -// semantics. A MemoryBarrierInternal() has "Barrier" semantics, but does no -// memory access. -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 res = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - MemoryBarrierInternal(); - return res; -} - -inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - MemoryBarrierInternal(); - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; - MemoryBarrierInternal(); -} - -inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { - MemoryBarrierInternal(); - *ptr = value; -} - -inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { - return *ptr; -} - -inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { - Atomic64 value = *ptr; - MemoryBarrierInternal(); - return value; -} - -inline Atomic64 Release_Load(volatile const Atomic64* ptr) { - MemoryBarrierInternal(); - return *ptr; -} -#endif - -} // namespace internal -} // namespace protobuf -} // namespace google - -#undef ATOMICOPS_COMPILER_BARRIER - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_MIPS_GCC_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_power.h b/src/google/protobuf/stubs/atomicops_internals_power.h deleted file mode 100644 index cad9f1e3..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_power.h +++ /dev/null @@ -1,440 +0,0 @@ -// Copyright 2014 Bloomberg Finance LP. 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 Bloomberg Finance LP. 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 is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_AIX_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_AIX_H_ - -namespace google { -namespace protobuf { -namespace internal { - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 result; - - asm volatile ( - "1: lwarx %[res], %[zero], %[obj] \n\t" // load and reserve - " cmpw %[cmp], %[res] \n\t" // compare values - " bne- 2f \n\t" - " stwcx. %[val], %[zero], %[obj] \n\t" // store new value - " bne- 1b \n\t" - "2: \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [cmp] "b" (old_value), - [val] "b" (new_value), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - Atomic32 result; - - asm volatile ( - "1: lwarx %[res], %[zero], %[obj] \n\t" - " stwcx. %[val], %[zero], %[obj] \n\t" - " bne- 1b \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [val] "b" (new_value), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - Atomic32 result; - - asm volatile ( - "1: lwarx %[res], %[zero], %[obj] \n\t" // load and reserve - " add %[res], %[val], %[res] \n\t" // add the operand - " stwcx. %[res], %[zero], %[obj] \n\t" // store old value - // if still reserved - " bne- 1b \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [val] "b" (increment), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline void MemoryBarrierInternal(void) { - asm volatile ( - " lwsync \n\t" - " isync \n\t" - : - : - : "memory"); -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - Atomic32 result; - - asm volatile ( - " lwsync \n\t" - - "1: lwarx %[res], %[zero], %[obj] \n\t" // load and reserve - " add %[res], %[val], %[res] \n\t" // add the operand - " stwcx. %[res], %[zero], %[obj] \n\t" // store old value - // if still reserved - " bne- 1b \n\t" - " isync \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [val] "b" (increment), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 result; - - asm volatile ( - "1: lwarx %[res], %[zero], %[obj] \n\t" // load and reserve - " cmpw %[cmp], %[res] \n\t" // compare values - " bne- 2f \n\t" - " stwcx. %[val], %[zero], %[obj] \n\t" // store new value - " bne- 1b \n\t" - - " isync \n\t" - "2: \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [cmp] "b" (old_value), - [val] "b" (new_value), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 result; - - asm volatile ( - " lwsync \n\t" - - "1: lwarx %[res], %[zero], %[obj] \n\t" // load and reserve - " cmpw %[cmp], %[res] \n\t" // compare values - " bne- 2f \n\t" - " stwcx. %[val], %[zero], %[obj] \n\t" // store new value - " bne- 1b \n\t" - - "2: \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [cmp] "b" (old_value), - [val] "b" (new_value), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - asm volatile ( - " stw %[val], %[obj] \n\t" - " isync \n\t" - : [obj] "=m" (*ptr) - : [val] "b" (value)); -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - asm volatile ( - " lwsync \n\t" - " stw %[val], %[obj] \n\t" - : [obj] "=m" (*ptr) - : [val] "b" (value)); -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return *ptr; -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - Atomic32 result; - - asm volatile ( - "1: lwz %[res], %[obj] \n\t" - " cmpw %[res], %[res] \n\t" // create data - // dependency for - // load/load ordering - " bne- 1b \n\t" // never taken - - " isync \n\t" - : [res] "=b" (result) - : [obj] "m" (*ptr), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - Atomic32 result; - - asm volatile ( - " lwsync \n\t" - - "1: lwz %[res], %[obj] \n\t" - " cmpw %[res], %[res] \n\t" // create data - // dependency for - // load/load ordering - " bne- 1b \n\t" // never taken - : [res] "=b" (result) - : [obj] "m" (*ptr), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -#ifdef GOOGLE_PROTOBUF_ARCH_64_BIT -inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 result; - - asm volatile ( - "1: ldarx %[res], %[zero], %[obj] \n\t" // load and reserve - " cmpd %[cmp], %[res] \n\t" // compare values - " bne- 2f \n\t" - - " stdcx. %[val], %[zero], %[obj] \n\t" // store the new value - " bne- 1b \n\t" - "2: \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [cmp] "b" (old_value), - [val] "b" (new_value), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, - Atomic64 new_value) { - Atomic64 result; - - asm volatile ( - "1: ldarx %[res], %[zero], %[obj] \n\t" - " stdcx. %[val], %[zero], %[obj] \n\t" - " bne- 1b \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [val] "b" (new_value), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - Atomic64 result; - - asm volatile ( - "1: ldarx %[res], %[zero], %[obj] \n\t" // load and reserve - " add %[res], %[res], %[val] \n\t" // add the operand - " stdcx. %[res], %[zero], %[obj] \n\t" // store old value if - // still reserved - - " bne- 1b \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [val] "b" (increment), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - - Atomic64 result; - - asm volatile ( - " lwsync \n\t" - - "1: ldarx %[res], %[zero], %[obj] \n\t" // load and reserve - " add %[res], %[res], %[val] \n\t" // add the operand - " stdcx. %[res], %[zero], %[obj] \n\t" // store old value if - // still reserved - - " bne- 1b \n\t" - - " isync \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [val] "b" (increment), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 result; - - asm volatile ( - "1: ldarx %[res], %[zero], %[obj] \n\t" // load and reserve - " cmpd %[cmp], %[res] \n\t" // compare values - " bne- 2f \n\t" - - " stdcx. %[val], %[zero], %[obj] \n\t" // store the new value - " bne- 1b \n\t" - " isync \n\t" - "2: \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [cmp] "b" (old_value), - [val] "b" (new_value), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 result; - - asm volatile ( - " lwsync \n\t" - - "1: ldarx %[res], %[zero], %[obj] \n\t" // load and reserve - " cmpd %[cmp], %[res] \n\t" // compare values - " bne- 2f \n\t" - - " stdcx. %[val], %[zero], %[obj] \n\t" // store the new value - " bne- 1b \n\t" - "2: \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [cmp] "b" (old_value), - [val] "b" (new_value), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { - asm volatile ( - " std %[val], %[obj] \n\t" - " isync \n\t" - : [obj] "=m" (*ptr) - : [val] "b" (value)); -} - -inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { - asm volatile ( - " lwsync \n\t" - " std %[val], %[obj] \n\t" - : [obj] "=m" (*ptr) - : [val] "b" (value)); -} - -inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { - return *ptr; -} - -inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { - Atomic64 result; - - asm volatile ( - "1: ld %[res], %[obj] \n\t" - " cmpd %[res], %[res] \n\t" // create data - // dependency for - // load/load ordering - " bne- 1b \n\t" // never taken - - " isync \n\t" - : [res] "=b" (result) - : [obj] "m" (*ptr), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic64 Release_Load(volatile const Atomic64* ptr) { - Atomic64 result; - - asm volatile ( - " lwsync \n\t" - - "1: ld %[res], %[obj] \n\t" - " cmpd %[res], %[res] \n\t" // create data - // dependency for - // load/load ordering - " bne- 1b \n\t" // never taken - : [res] "=b" (result) - : [obj] "m" (*ptr), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} -#endif - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_SPARC_GCC_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_ppc_gcc.h b/src/google/protobuf/stubs/atomicops_internals_ppc_gcc.h deleted file mode 100644 index d477dc6d..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_ppc_gcc.h +++ /dev/null @@ -1,155 +0,0 @@ -// 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. - -// Author: ogabbay@advaoptical.com (Oded Gabbay) -// Cleaned up by: bsilver16384@gmail.com (Brian Silverman) -// -// This file is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_PPC_GCC_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_PPC_GCC_H_ - -#define ATOMICOPS_COMPILER_BARRIER() __asm__ __volatile__("" : : : "memory") - -namespace google { -namespace protobuf { -namespace internal { - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32 *ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 prev; - - __asm__ __volatile__( - "0: \n\t" - "lwarx %[prev],0,%[ptr] \n\t" - "cmpw 0,%[prev],%[old_value] \n\t" - "bne- 1f \n\t" - "stwcx. %[new_value],0,%[ptr] \n\t" - "bne- 0b \n\t" - "1: \n\t" - : [prev] "=&r"(prev), "+m"(*ptr) - : [ptr] "r"(ptr), [old_value] "r"(old_value), [new_value] "r"(new_value) - : "cc", "memory"); - - return prev; -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32 *ptr, - Atomic32 new_value) { - Atomic32 old; - - __asm__ __volatile__( - "0: \n\t" - "lwarx %[old],0,%[ptr] \n\t" - "stwcx. %[new_value],0,%[ptr] \n\t" - "bne- 0b \n\t" - : [old] "=&r"(old), "+m"(*ptr) - : [ptr] "r"(ptr), [new_value] "r"(new_value) - : "cc", "memory"); - - return old; -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32 *ptr, - Atomic32 increment) { - Atomic32 temp; - - __asm__ __volatile__( - "0: \n\t" - "lwarx %[temp],0,%[ptr] \n\t" - "add %[temp],%[increment],%[temp] \n\t" - "stwcx. %[temp],0,%[ptr] \n\t" - "bne- 0b \n\t" - : [temp] "=&r"(temp) - : [increment] "r"(increment), [ptr] "r"(ptr) - : "cc", "memory"); - - return temp; -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32 *ptr, - Atomic32 increment) { - MemoryBarrierInternal(); - Atomic32 res = NoBarrier_AtomicIncrement(ptr, increment); - MemoryBarrierInternal(); - return res; -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32 *ptr, - Atomic32 old_value, Atomic32 new_value) { - Atomic32 res = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - MemoryBarrierInternal(); - return res; -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32 *ptr, - Atomic32 old_value, Atomic32 new_value) { - MemoryBarrierInternal(); - Atomic32 res = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - return res; -} - -inline void NoBarrier_Store(volatile Atomic32 *ptr, Atomic32 value) { - *ptr = value; -} - -inline void MemoryBarrierInternal() { __asm__ __volatile__("sync" : : : "memory"); } - -inline void Acquire_Store(volatile Atomic32 *ptr, Atomic32 value) { - *ptr = value; - MemoryBarrierInternal(); -} - -inline void Release_Store(volatile Atomic32 *ptr, Atomic32 value) { - MemoryBarrierInternal(); - *ptr = value; -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32 *ptr) { return *ptr; } - -inline Atomic32 Acquire_Load(volatile const Atomic32 *ptr) { - Atomic32 value = *ptr; - MemoryBarrierInternal(); - return value; -} - -inline Atomic32 Release_Load(volatile const Atomic32 *ptr) { - MemoryBarrierInternal(); - return *ptr; -} - -} // namespace internal -} // namespace protobuf -} // namespace google - -#undef ATOMICOPS_COMPILER_BARRIER - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_PPC_GCC_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_solaris.h b/src/google/protobuf/stubs/atomicops_internals_solaris.h deleted file mode 100644 index baecb993..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_solaris.h +++ /dev/null @@ -1,188 +0,0 @@ -// 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. - -// This file is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_SPARC_GCC_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_SPARC_GCC_H_ - -#include <atomic.h> - -namespace google { -namespace protobuf { -namespace internal { - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - return (Atomic32)atomic_cas_32((volatile uint32_t*)ptr, (uint32_t)old_value, (uint32_t)new_value); -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - return (Atomic32)atomic_swap_32((volatile uint32_t*)ptr, (uint32_t)new_value); -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return (Atomic32)atomic_add_32_nv((volatile uint32_t*)ptr, (uint32_t)increment); -} - -inline void MemoryBarrierInternal(void) { - membar_producer(); - membar_consumer(); -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - MemoryBarrierInternal(); - Atomic32 ret = NoBarrier_AtomicIncrement(ptr, increment); - MemoryBarrierInternal(); - - return ret; -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 ret = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - MemoryBarrierInternal(); - - return ret; -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - MemoryBarrierInternal(); - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; - membar_producer(); -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - membar_consumer(); - *ptr = value; -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return *ptr; -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - Atomic32 val = *ptr; - membar_consumer(); - return val; -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - membar_producer(); - return *ptr; -} - -#ifdef GOOGLE_PROTOBUF_ARCH_64_BIT -inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - return atomic_cas_64((volatile uint64_t*)ptr, (uint64_t)old_value, (uint64_t)new_value); -} - -inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, Atomic64 new_value) { - return atomic_swap_64((volatile uint64_t*)ptr, (uint64_t)new_value); -} - -inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment) { - return atomic_add_64_nv((volatile uint64_t*)ptr, increment); -} - -inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment) { - MemoryBarrierInternal(); - Atomic64 ret = atomic_add_64_nv((volatile uint64_t*)ptr, increment); - MemoryBarrierInternal(); - return ret; -} - -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 ret = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - MemoryBarrierInternal(); - return ret; -} - -inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - MemoryBarrierInternal(); - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; - membar_producer(); -} - -inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { - membar_consumer(); - *ptr = value; -} - -inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { - return *ptr; -} - -inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { - Atomic64 ret = *ptr; - membar_consumer(); - return ret; -} - -inline Atomic64 Release_Load(volatile const Atomic64* ptr) { - membar_producer(); - return *ptr; -} -#endif - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_SPARC_GCC_H_ - diff --git a/src/google/protobuf/stubs/atomicops_internals_tsan.h b/src/google/protobuf/stubs/atomicops_internals_tsan.h deleted file mode 100644 index 676380b1..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_tsan.h +++ /dev/null @@ -1,219 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2013 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 is an internal atomic implementation for compiler-based -// ThreadSanitizer (http://clang.llvm.org/docs/ThreadSanitizer.html). -// Use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_TSAN_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_TSAN_H_ - -#define ATOMICOPS_COMPILER_BARRIER() __asm__ __volatile__("" : : : "memory") - -#include <sanitizer/tsan_interface_atomic.h> - -namespace google { -namespace protobuf { -namespace internal { - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32 *ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 cmp = old_value; - __tsan_atomic32_compare_exchange_strong(ptr, &cmp, new_value, - __tsan_memory_order_relaxed, __tsan_memory_order_relaxed); - return cmp; -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32 *ptr, - Atomic32 new_value) { - return __tsan_atomic32_exchange(ptr, new_value, - __tsan_memory_order_relaxed); -} - -inline Atomic32 Acquire_AtomicExchange(volatile Atomic32 *ptr, - Atomic32 new_value) { - return __tsan_atomic32_exchange(ptr, new_value, - __tsan_memory_order_acquire); -} - -inline Atomic32 Release_AtomicExchange(volatile Atomic32 *ptr, - Atomic32 new_value) { - return __tsan_atomic32_exchange(ptr, new_value, - __tsan_memory_order_release); -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32 *ptr, - Atomic32 increment) { - return increment + __tsan_atomic32_fetch_add(ptr, increment, - __tsan_memory_order_relaxed); -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32 *ptr, - Atomic32 increment) { - return increment + __tsan_atomic32_fetch_add(ptr, increment, - __tsan_memory_order_acq_rel); -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32 *ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 cmp = old_value; - __tsan_atomic32_compare_exchange_strong(ptr, &cmp, new_value, - __tsan_memory_order_acquire, __tsan_memory_order_acquire); - return cmp; -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32 *ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 cmp = old_value; - __tsan_atomic32_compare_exchange_strong(ptr, &cmp, new_value, - __tsan_memory_order_release, __tsan_memory_order_relaxed); - return cmp; -} - -inline void NoBarrier_Store(volatile Atomic32 *ptr, Atomic32 value) { - __tsan_atomic32_store(ptr, value, __tsan_memory_order_relaxed); -} - -inline void Acquire_Store(volatile Atomic32 *ptr, Atomic32 value) { - __tsan_atomic32_store(ptr, value, __tsan_memory_order_relaxed); - __tsan_atomic_thread_fence(__tsan_memory_order_seq_cst); -} - -inline void Release_Store(volatile Atomic32 *ptr, Atomic32 value) { - __tsan_atomic32_store(ptr, value, __tsan_memory_order_release); -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32 *ptr) { - return __tsan_atomic32_load(ptr, __tsan_memory_order_relaxed); -} - -inline Atomic32 Acquire_Load(volatile const Atomic32 *ptr) { - return __tsan_atomic32_load(ptr, __tsan_memory_order_acquire); -} - -inline Atomic32 Release_Load(volatile const Atomic32 *ptr) { - __tsan_atomic_thread_fence(__tsan_memory_order_seq_cst); - return __tsan_atomic32_load(ptr, __tsan_memory_order_relaxed); -} - -inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64 *ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 cmp = old_value; - __tsan_atomic64_compare_exchange_strong(ptr, &cmp, new_value, - __tsan_memory_order_relaxed, __tsan_memory_order_relaxed); - return cmp; -} - -inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64 *ptr, - Atomic64 new_value) { - return __tsan_atomic64_exchange(ptr, new_value, __tsan_memory_order_relaxed); -} - -inline Atomic64 Acquire_AtomicExchange(volatile Atomic64 *ptr, - Atomic64 new_value) { - return __tsan_atomic64_exchange(ptr, new_value, __tsan_memory_order_acquire); -} - -inline Atomic64 Release_AtomicExchange(volatile Atomic64 *ptr, - Atomic64 new_value) { - return __tsan_atomic64_exchange(ptr, new_value, __tsan_memory_order_release); -} - -inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64 *ptr, - Atomic64 increment) { - return increment + __tsan_atomic64_fetch_add(ptr, increment, - __tsan_memory_order_relaxed); -} - -inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64 *ptr, - Atomic64 increment) { - return increment + __tsan_atomic64_fetch_add(ptr, increment, - __tsan_memory_order_acq_rel); -} - -inline void NoBarrier_Store(volatile Atomic64 *ptr, Atomic64 value) { - __tsan_atomic64_store(ptr, value, __tsan_memory_order_relaxed); -} - -inline void Acquire_Store(volatile Atomic64 *ptr, Atomic64 value) { - __tsan_atomic64_store(ptr, value, __tsan_memory_order_relaxed); - __tsan_atomic_thread_fence(__tsan_memory_order_seq_cst); -} - -inline void Release_Store(volatile Atomic64 *ptr, Atomic64 value) { - __tsan_atomic64_store(ptr, value, __tsan_memory_order_release); -} - -inline Atomic64 NoBarrier_Load(volatile const Atomic64 *ptr) { - return __tsan_atomic64_load(ptr, __tsan_memory_order_relaxed); -} - -inline Atomic64 Acquire_Load(volatile const Atomic64 *ptr) { - return __tsan_atomic64_load(ptr, __tsan_memory_order_acquire); -} - -inline Atomic64 Release_Load(volatile const Atomic64 *ptr) { - __tsan_atomic_thread_fence(__tsan_memory_order_seq_cst); - return __tsan_atomic64_load(ptr, __tsan_memory_order_relaxed); -} - -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64 *ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 cmp = old_value; - __tsan_atomic64_compare_exchange_strong(ptr, &cmp, new_value, - __tsan_memory_order_acquire, __tsan_memory_order_acquire); - return cmp; -} - -inline Atomic64 Release_CompareAndSwap(volatile Atomic64 *ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 cmp = old_value; - __tsan_atomic64_compare_exchange_strong(ptr, &cmp, new_value, - __tsan_memory_order_release, __tsan_memory_order_relaxed); - return cmp; -} - -inline void MemoryBarrierInternal() { - __tsan_atomic_thread_fence(__tsan_memory_order_seq_cst); -} - -} // namespace internal -} // namespace protobuf -} // namespace google - -#undef ATOMICOPS_COMPILER_BARRIER - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_TSAN_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_x86_gcc.cc b/src/google/protobuf/stubs/atomicops_internals_x86_gcc.cc deleted file mode 100644 index 53c9eae0..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_x86_gcc.cc +++ /dev/null @@ -1,137 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 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 module gets enough CPU information to optimize the -// atomicops module on x86. - -#include <cstring> - -#include <google/protobuf/stubs/atomicops.h> - -// This file only makes sense with atomicops_internals_x86_gcc.h -- it -// depends on structs that are defined in that file. If atomicops.h -// doesn't sub-include that file, then we aren't needed, and shouldn't -// try to do anything. -#ifdef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_GCC_H_ - -// Inline cpuid instruction. In PIC compilations, %ebx contains the address -// of the global offset table. To avoid breaking such executables, this code -// must preserve that register's value across cpuid instructions. -#if defined(__i386__) -#define cpuid(a, b, c, d, inp) \ - asm("mov %%ebx, %%edi\n" \ - "cpuid\n" \ - "xchg %%edi, %%ebx\n" \ - : "=a" (a), "=D" (b), "=c" (c), "=d" (d) : "a" (inp)) -#elif defined(__x86_64__) -#define cpuid(a, b, c, d, inp) \ - asm("mov %%rbx, %%rdi\n" \ - "cpuid\n" \ - "xchg %%rdi, %%rbx\n" \ - : "=a" (a), "=D" (b), "=c" (c), "=d" (d) : "a" (inp)) -#endif - -#if defined(cpuid) // initialize the struct only on x86 - -namespace google { -namespace protobuf { -namespace internal { - -// Set the flags so that code will run correctly and conservatively, so even -// if we haven't been initialized yet, we're probably single threaded, and our -// default values should hopefully be pretty safe. -struct AtomicOps_x86CPUFeatureStruct AtomicOps_Internalx86CPUFeatures = { - false, // bug can't exist before process spawns multiple threads - false, // no SSE2 -}; - -namespace { - -// Initialize the AtomicOps_Internalx86CPUFeatures struct. -void AtomicOps_Internalx86CPUFeaturesInit() { - uint32_t eax; - uint32_t ebx; - uint32_t ecx; - uint32_t edx; - - // Get vendor string (issue CPUID with eax = 0) - cpuid(eax, ebx, ecx, edx, 0); - char vendor[13]; - memcpy(vendor, &ebx, 4); - memcpy(vendor + 4, &edx, 4); - memcpy(vendor + 8, &ecx, 4); - vendor[12] = 0; - - // get feature flags in ecx/edx, and family/model in eax - cpuid(eax, ebx, ecx, edx, 1); - - int family = (eax >> 8) & 0xf; // family and model fields - int model = (eax >> 4) & 0xf; - if (family == 0xf) { // use extended family and model fields - family += (eax >> 20) & 0xff; - model += ((eax >> 16) & 0xf) << 4; - } - - // Opteron Rev E has a bug in which on very rare occasions a locked - // instruction doesn't act as a read-acquire barrier if followed by a - // non-locked read-modify-write instruction. Rev F has this bug in - // pre-release versions, but not in versions released to customers, - // so we test only for Rev E, which is family 15, model 32..63 inclusive. - if (strcmp(vendor, "AuthenticAMD") == 0 && // AMD - family == 15 && - 32 <= model && model <= 63) { - AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug = true; - } else { - AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug = false; - } - - // edx bit 26 is SSE2 which we use to tell use whether we can use mfence - AtomicOps_Internalx86CPUFeatures.has_sse2 = ((edx >> 26) & 1); -} - -class AtomicOpsx86Initializer { - public: - AtomicOpsx86Initializer() { - AtomicOps_Internalx86CPUFeaturesInit(); - } -}; - -// A global to get use initialized on startup via static initialization :/ -AtomicOpsx86Initializer g_initer; - -} // namespace - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // __i386__ - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_GCC_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_x86_gcc.h b/src/google/protobuf/stubs/atomicops_internals_x86_gcc.h deleted file mode 100644 index e80121fd..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_x86_gcc.h +++ /dev/null @@ -1,293 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 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 is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_GCC_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_GCC_H_ - -namespace google { -namespace protobuf { -namespace internal { - -// This struct is not part of the public API of this module; clients may not -// use it. -// Features of this x86. Values may not be correct before main() is run, -// but are set conservatively. -struct AtomicOps_x86CPUFeatureStruct { - bool has_amd_lock_mb_bug; // Processor has AMD memory-barrier bug; do lfence - // after acquire compare-and-swap. - bool has_sse2; // Processor has SSE2. -}; -extern struct AtomicOps_x86CPUFeatureStruct AtomicOps_Internalx86CPUFeatures; - -#define ATOMICOPS_COMPILER_BARRIER() __asm__ __volatile__("" : : : "memory") - -// 32-bit low-level operations on any platform. - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 prev; - __asm__ __volatile__("lock; cmpxchgl %1,%2" - : "=a" (prev) - : "q" (new_value), "m" (*ptr), "0" (old_value) - : "memory"); - return prev; -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - __asm__ __volatile__("xchgl %1,%0" // The lock prefix is implicit for xchg. - : "=r" (new_value) - : "m" (*ptr), "0" (new_value) - : "memory"); - return new_value; // Now it's the previous value. -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - Atomic32 temp = increment; - __asm__ __volatile__("lock; xaddl %0,%1" - : "+r" (temp), "+m" (*ptr) - : : "memory"); - // temp now holds the old value of *ptr - return temp + increment; -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - Atomic32 temp = increment; - __asm__ __volatile__("lock; xaddl %0,%1" - : "+r" (temp), "+m" (*ptr) - : : "memory"); - // temp now holds the old value of *ptr - if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) { - __asm__ __volatile__("lfence" : : : "memory"); - } - return temp + increment; -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 x = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) { - __asm__ __volatile__("lfence" : : : "memory"); - } - return x; -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; -} - -#if defined(__x86_64__) - -// 64-bit implementations of memory barrier can be simpler, because it -// "mfence" is guaranteed to exist. -inline void MemoryBarrierInternal() { - __asm__ __volatile__("mfence" : : : "memory"); -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; - MemoryBarrierInternal(); -} - -#else - -inline void MemoryBarrierInternal() { - if (AtomicOps_Internalx86CPUFeatures.has_sse2) { - __asm__ __volatile__("mfence" : : : "memory"); - } else { // mfence is faster but not present on PIII - Atomic32 x = 0; - NoBarrier_AtomicExchange(&x, 0); // acts as a barrier on PIII - } -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - if (AtomicOps_Internalx86CPUFeatures.has_sse2) { - *ptr = value; - __asm__ __volatile__("mfence" : : : "memory"); - } else { - NoBarrier_AtomicExchange(ptr, value); - // acts as a barrier on PIII - } -} -#endif - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - ATOMICOPS_COMPILER_BARRIER(); - *ptr = value; // An x86 store acts as a release barrier. - // See comments in Atomic64 version of Release_Store(), below. -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return *ptr; -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - Atomic32 value = *ptr; // An x86 load acts as a acquire barrier. - // See comments in Atomic64 version of Release_Store(), below. - ATOMICOPS_COMPILER_BARRIER(); - return value; -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - MemoryBarrierInternal(); - return *ptr; -} - -#if defined(__x86_64__) - -// 64-bit low-level operations on 64-bit platform. - -inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 prev; - __asm__ __volatile__("lock; cmpxchgq %1,%2" - : "=a" (prev) - : "q" (new_value), "m" (*ptr), "0" (old_value) - : "memory"); - return prev; -} - -inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, - Atomic64 new_value) { - __asm__ __volatile__("xchgq %1,%0" // The lock prefix is implicit for xchg. - : "=r" (new_value) - : "m" (*ptr), "0" (new_value) - : "memory"); - return new_value; // Now it's the previous value. -} - -inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - Atomic64 temp = increment; - __asm__ __volatile__("lock; xaddq %0,%1" - : "+r" (temp), "+m" (*ptr) - : : "memory"); - // temp now contains the previous value of *ptr - return temp + increment; -} - -inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - Atomic64 temp = increment; - __asm__ __volatile__("lock; xaddq %0,%1" - : "+r" (temp), "+m" (*ptr) - : : "memory"); - // temp now contains the previous value of *ptr - if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) { - __asm__ __volatile__("lfence" : : : "memory"); - } - return temp + increment; -} - -inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; - MemoryBarrierInternal(); -} - -inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { - ATOMICOPS_COMPILER_BARRIER(); - - *ptr = value; // An x86 store acts as a release barrier - // for current AMD/Intel chips as of Jan 2008. - // See also Acquire_Load(), below. - - // When new chips come out, check: - // IA-32 Intel Architecture Software Developer's Manual, Volume 3: - // System Programming Guide, Chatper 7: Multiple-processor management, - // Section 7.2, Memory Ordering. - // Last seen at: - // http://developer.intel.com/design/pentium4/manuals/index_new.htm - // - // x86 stores/loads fail to act as barriers for a few instructions (clflush - // maskmovdqu maskmovq movntdq movnti movntpd movntps movntq) but these are - // not generated by the compiler, and are rare. Users of these instructions - // need to know about cache behaviour in any case since all of these involve - // either flushing cache lines or non-temporal cache hints. -} - -inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { - return *ptr; -} - -inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { - Atomic64 value = *ptr; // An x86 load acts as a acquire barrier, - // for current AMD/Intel chips as of Jan 2008. - // See also Release_Store(), above. - ATOMICOPS_COMPILER_BARRIER(); - return value; -} - -inline Atomic64 Release_Load(volatile const Atomic64* ptr) { - MemoryBarrierInternal(); - return *ptr; -} - -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 x = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) { - __asm__ __volatile__("lfence" : : : "memory"); - } - return x; -} - -inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -#endif // defined(__x86_64__) - -} // namespace internal -} // namespace protobuf -} // namespace google - -#undef ATOMICOPS_COMPILER_BARRIER - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_GCC_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_x86_msvc.cc b/src/google/protobuf/stubs/atomicops_internals_x86_msvc.cc deleted file mode 100644 index 74a1bd4e..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_x86_msvc.cc +++ /dev/null @@ -1,113 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 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. - -// The compilation of extension_set.cc fails when windows.h is included. -// Therefore we move the code depending on windows.h to this separate cc file. - -// Don't compile this file for people not concerned about thread safety. -#ifndef GOOGLE_PROTOBUF_NO_THREAD_SAFETY - -#include <google/protobuf/stubs/atomicops.h> - -#ifdef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_MSVC_H_ - -#include <windows.h> - -namespace google { -namespace protobuf { -namespace internal { - -inline void MemoryBarrierInternal() { - // On ARM this is a define while on x86/x64 this is - // a function declared in WinNT.h - MemoryBarrier(); -} - -Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - LONG result = InterlockedCompareExchange( - reinterpret_cast<volatile LONG*>(ptr), - static_cast<LONG>(new_value), - static_cast<LONG>(old_value)); - return static_cast<Atomic32>(result); -} - -Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - LONG result = InterlockedExchange( - reinterpret_cast<volatile LONG*>(ptr), - static_cast<LONG>(new_value)); - return static_cast<Atomic32>(result); -} - -Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return InterlockedExchangeAdd( - reinterpret_cast<volatile LONG*>(ptr), - static_cast<LONG>(increment)) + increment; -} - -#if defined(_WIN64) - -// 64-bit low-level operations on 64-bit platform. - -Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - PVOID result = InterlockedCompareExchangePointer( - reinterpret_cast<volatile PVOID*>(ptr), - reinterpret_cast<PVOID>(new_value), reinterpret_cast<PVOID>(old_value)); - return reinterpret_cast<Atomic64>(result); -} - -Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, - Atomic64 new_value) { - PVOID result = InterlockedExchangePointer( - reinterpret_cast<volatile PVOID*>(ptr), - reinterpret_cast<PVOID>(new_value)); - return reinterpret_cast<Atomic64>(result); -} - -Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - return InterlockedExchangeAdd64( - reinterpret_cast<volatile LONGLONG*>(ptr), - static_cast<LONGLONG>(increment)) + increment; -} - -#endif // defined(_WIN64) - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_MSVC_H_ -#endif // GOOGLE_PROTOBUF_NO_THREAD_SAFETY diff --git a/src/google/protobuf/stubs/atomicops_internals_x86_msvc.h b/src/google/protobuf/stubs/atomicops_internals_x86_msvc.h deleted file mode 100644 index 34d60d98..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_x86_msvc.h +++ /dev/null @@ -1,150 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 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 is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_MSVC_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_MSVC_H_ - -namespace google { -namespace protobuf { -namespace internal { - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return Barrier_AtomicIncrement(ptr, increment); -} - -#if !(defined(_MSC_VER) && _MSC_VER >= 1400) -#error "We require at least vs2005 for MemoryBarrier" -#endif - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - NoBarrier_AtomicExchange(ptr, value); - // acts as a barrier in this implementation -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; // works w/o barrier for current Intel chips as of June 2005 - // See comments in Atomic64 version of Release_Store() below. -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return *ptr; -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - Atomic32 value = *ptr; - return value; -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - MemoryBarrierInternal(); - return *ptr; -} - -#if defined(_WIN64) - -// 64-bit low-level operations on 64-bit platform. - -inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - return Barrier_AtomicIncrement(ptr, increment); -} - -inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { - NoBarrier_AtomicExchange(ptr, value); - // acts as a barrier in this implementation -} - -inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; // works w/o barrier for current Intel chips as of June 2005 - - // When new chips come out, check: - // IA-32 Intel Architecture Software Developer's Manual, Volume 3: - // System Programming Guide, Chatper 7: Multiple-processor management, - // Section 7.2, Memory Ordering. - // Last seen at: - // http://developer.intel.com/design/pentium4/manuals/index_new.htm -} - -inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { - return *ptr; -} - -inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { - Atomic64 value = *ptr; - return value; -} - -inline Atomic64 Release_Load(volatile const Atomic64* ptr) { - MemoryBarrierInternal(); - return *ptr; -} - -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -#endif // defined(_WIN64) - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_MSVC_H_ diff --git a/src/google/protobuf/stubs/once.cc b/src/google/protobuf/stubs/once.cc deleted file mode 100644 index 889c6476..00000000 --- a/src/google/protobuf/stubs/once.cc +++ /dev/null @@ -1,99 +0,0 @@ -// 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/base/once.h -// -// This header is intended to be included only by internal .cc files and -// generated .pb.cc files. Users should not use this directly. - -#include <google/protobuf/stubs/once.h> - -#ifndef GOOGLE_PROTOBUF_NO_THREAD_SAFETY - -#ifdef _WIN32 -#include <windows.h> -#else -#include <sched.h> -#endif - -#include <google/protobuf/stubs/atomicops.h> - -namespace google { -namespace protobuf { - -namespace { - -void SchedYield() { -#ifdef _WIN32 - Sleep(0); -#else // POSIX - sched_yield(); -#endif -} - -} // namespace - -void GoogleOnceInitImpl(ProtobufOnceType* once, Closure* closure) { - internal::AtomicWord state = internal::Acquire_Load(once); - // Fast path. The provided closure was already executed. - if (state == ONCE_STATE_DONE) { - return; - } - // The closure execution did not complete yet. The once object can be in one - // of the two following states: - // - UNINITIALIZED: We are the first thread calling this function. - // - EXECUTING_CLOSURE: Another thread is already executing the closure. - // - // First, try to change the state from UNINITIALIZED to EXECUTING_CLOSURE - // atomically. - state = internal::Acquire_CompareAndSwap( - once, ONCE_STATE_UNINITIALIZED, ONCE_STATE_EXECUTING_CLOSURE); - if (state == ONCE_STATE_UNINITIALIZED) { - // We are the first thread to call this function, so we have to call the - // closure. - closure->Run(); - internal::Release_Store(once, ONCE_STATE_DONE); - } else { - // Another thread has already started executing the closure. We need to - // wait until it completes the initialization. - while (state == ONCE_STATE_EXECUTING_CLOSURE) { - // Note that futex() could be used here on Linux as an improvement. - SchedYield(); - state = internal::Acquire_Load(once); - } - } -} - -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_NO_THREAD_SAFETY diff --git a/src/google/protobuf/stubs/once_unittest.cc b/src/google/protobuf/stubs/once_unittest.cc deleted file mode 100644 index cdd353d8..00000000 --- a/src/google/protobuf/stubs/once_unittest.cc +++ /dev/null @@ -1,254 +0,0 @@ -// 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) - -#ifdef _WIN32 -#include <windows.h> -#else -#include <unistd.h> -#include <pthread.h> -#endif - -#include <google/protobuf/stubs/once.h> -#include <google/protobuf/testing/googletest.h> -#include <gtest/gtest.h> - -namespace google { -namespace protobuf { -namespace { - -class OnceInitTest : public testing::Test { - protected: - void SetUp() { - state_ = INIT_NOT_STARTED; - current_test_ = this; - } - - // Since ProtobufOnceType is only allowed to be allocated in static storage, - // each test must use a different pair of ProtobufOnceType objects which it - // must declare itself. - void SetOnces(ProtobufOnceType* once, ProtobufOnceType* recursive_once) { - once_ = once; - recursive_once_ = recursive_once; - } - - void InitOnce() { - GoogleOnceInit(once_, &InitStatic); - } - void InitRecursiveOnce() { - GoogleOnceInit(recursive_once_, &InitRecursiveStatic); - } - - void BlockInit() { init_blocker_.Lock(); } - void UnblockInit() { init_blocker_.Unlock(); } - - class TestThread { - public: - TestThread(Closure* callback) - : done_(false), joined_(false), callback_(callback) { -#ifdef _WIN32 - thread_ = CreateThread(NULL, 0, &Start, this, 0, NULL); -#else - pthread_create(&thread_, NULL, &Start, this); -#endif - } - ~TestThread() { - if (!joined_) Join(); - } - - bool IsDone() { - MutexLock lock(&done_mutex_); - return done_; - } - void Join() { - joined_ = true; -#ifdef _WIN32 - WaitForSingleObject(thread_, INFINITE); - CloseHandle(thread_); -#else - pthread_join(thread_, NULL); -#endif - } - - private: -#ifdef _WIN32 - HANDLE thread_; -#else - pthread_t thread_; -#endif - - Mutex done_mutex_; - bool done_; - bool joined_; - Closure* callback_; - -#ifdef _WIN32 - static DWORD WINAPI Start(LPVOID arg) { -#else - static void* Start(void* arg) { -#endif - reinterpret_cast<TestThread*>(arg)->Run(); - return 0; - } - - void Run() { - callback_->Run(); - MutexLock lock(&done_mutex_); - done_ = true; - } - }; - - TestThread* RunInitOnceInNewThread() { - return new TestThread(NewCallback(this, &OnceInitTest::InitOnce)); - } - TestThread* RunInitRecursiveOnceInNewThread() { - return new TestThread( - NewCallback(this, &OnceInitTest::InitRecursiveOnce)); - } - - enum State { - INIT_NOT_STARTED, - INIT_STARTED, - INIT_DONE - }; - State CurrentState() { - MutexLock lock(&mutex_); - return state_; - } - - void WaitABit() { -#ifdef _WIN32 - Sleep(1000); -#else - sleep(1); -#endif - } - - private: - Mutex mutex_; - Mutex init_blocker_; - State state_; - ProtobufOnceType* once_; - ProtobufOnceType* recursive_once_; - - void Init() { - MutexLock lock(&mutex_); - EXPECT_EQ(INIT_NOT_STARTED, state_); - state_ = INIT_STARTED; - mutex_.Unlock(); - init_blocker_.Lock(); - init_blocker_.Unlock(); - mutex_.Lock(); - state_ = INIT_DONE; - } - - static OnceInitTest* current_test_; - static void InitStatic() { current_test_->Init(); } - static void InitRecursiveStatic() { current_test_->InitOnce(); } -}; - -OnceInitTest* OnceInitTest::current_test_ = NULL; - -GOOGLE_PROTOBUF_DECLARE_ONCE(simple_once); - -TEST_F(OnceInitTest, Simple) { - SetOnces(&simple_once, NULL); - - EXPECT_EQ(INIT_NOT_STARTED, CurrentState()); - InitOnce(); - EXPECT_EQ(INIT_DONE, CurrentState()); - - // Calling again has no effect. - InitOnce(); - EXPECT_EQ(INIT_DONE, CurrentState()); -} - -GOOGLE_PROTOBUF_DECLARE_ONCE(recursive_once1); -GOOGLE_PROTOBUF_DECLARE_ONCE(recursive_once2); - -TEST_F(OnceInitTest, Recursive) { - SetOnces(&recursive_once1, &recursive_once2); - - EXPECT_EQ(INIT_NOT_STARTED, CurrentState()); - InitRecursiveOnce(); - EXPECT_EQ(INIT_DONE, CurrentState()); -} - -GOOGLE_PROTOBUF_DECLARE_ONCE(multiple_threads_once); - -TEST_F(OnceInitTest, MultipleThreads) { - SetOnces(&multiple_threads_once, NULL); - - std::unique_ptr<TestThread> threads[4]; - EXPECT_EQ(INIT_NOT_STARTED, CurrentState()); - for (int i = 0; i < 4; i++) { - threads[i].reset(RunInitOnceInNewThread()); - } - for (int i = 0; i < 4; i++) { - threads[i]->Join(); - } - EXPECT_EQ(INIT_DONE, CurrentState()); -} - -GOOGLE_PROTOBUF_DECLARE_ONCE(multiple_threads_blocked_once1); -GOOGLE_PROTOBUF_DECLARE_ONCE(multiple_threads_blocked_once2); - -TEST_F(OnceInitTest, MultipleThreadsBlocked) { - SetOnces(&multiple_threads_blocked_once1, &multiple_threads_blocked_once2); - - std::unique_ptr<TestThread> threads[8]; - EXPECT_EQ(INIT_NOT_STARTED, CurrentState()); - - BlockInit(); - for (int i = 0; i < 4; i++) { - threads[i].reset(RunInitOnceInNewThread()); - } - for (int i = 4; i < 8; i++) { - threads[i].reset(RunInitRecursiveOnceInNewThread()); - } - - WaitABit(); - - // We should now have one thread blocked inside Init(), four blocked waiting - // for Init() to complete, and three blocked waiting for InitRecursive() to - // complete. - EXPECT_EQ(INIT_STARTED, CurrentState()); - UnblockInit(); - - for (int i = 0; i < 8; i++) { - threads[i]->Join(); - } - EXPECT_EQ(INIT_DONE, CurrentState()); -} - -} // anonymous namespace -} // namespace protobuf -} // namespace google diff --git a/src/google/protobuf/stubs/shared_ptr.h b/src/google/protobuf/stubs/shared_ptr.h deleted file mode 100644 index 7da114e9..00000000 --- a/src/google/protobuf/stubs/shared_ptr.h +++ /dev/null @@ -1,471 +0,0 @@ -// 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/shared_ptr.h - -#ifndef GOOGLE_PROTOBUF_STUBS_SHARED_PTR_H__ -#define GOOGLE_PROTOBUF_STUBS_SHARED_PTR_H__ - -#include <google/protobuf/stubs/atomicops.h> - -#include <algorithm> // for swap -#include <stddef.h> -#include <memory> - -namespace google { -namespace protobuf { -namespace internal { - -// Alias to std::shared_ptr for any C++11 platform, -// and for any supported MSVC compiler. -#if !defined(UTIL_GTL_USE_STD_SHARED_PTR) && \ - (defined(COMPILER_MSVC) || defined(LANG_CXX11)) -#define UTIL_GTL_USE_STD_SHARED_PTR 1 -#endif - -#if defined(UTIL_GTL_USE_STD_SHARED_PTR) && UTIL_GTL_USE_STD_SHARED_PTR - -// These are transitional. They will be going away soon. -// Please just #include <memory> and just type std::shared_ptr yourself, instead -// of relying on this file. -// -// Migration doc: http://go/std-shared-ptr-lsc -using std::enable_shared_from_this; -using std::shared_ptr; -using std::static_pointer_cast; -using std::weak_ptr; - -#else // below, UTIL_GTL_USE_STD_SHARED_PTR not set or set to 0. - -// For everything else there is the google3 implementation. -inline bool RefCountDec(volatile Atomic32 *ptr) { - return Barrier_AtomicIncrement(ptr, -1) != 0; -} - -inline void RefCountInc(volatile Atomic32 *ptr) { - NoBarrier_AtomicIncrement(ptr, 1); -} - -template <typename T> class shared_ptr; -template <typename T> class weak_ptr; - -// This class is an internal implementation detail for shared_ptr. If two -// shared_ptrs point to the same object, they also share a control block. -// An "empty" shared_pointer refers to NULL and also has a NULL control block. -// It contains all of the state that's needed for reference counting or any -// other kind of resource management. In this implementation the control block -// happens to consist of two atomic words, the reference count (the number -// of shared_ptrs that share ownership of the object) and the weak count -// (the number of weak_ptrs that observe the object, plus 1 if the -// refcount is nonzero). -// -// The "plus 1" is to prevent a race condition in the shared_ptr and -// weak_ptr destructors. We need to make sure the control block is -// only deleted once, so we need to make sure that at most one -// object sees the weak count decremented from 1 to 0. -class SharedPtrControlBlock { - template <typename T> friend class shared_ptr; - template <typename T> friend class weak_ptr; - private: - SharedPtrControlBlock() : refcount_(1), weak_count_(1) { } - Atomic32 refcount_; - Atomic32 weak_count_; -}; - -// Forward declaration. The class is defined below. -template <typename T> class enable_shared_from_this; - -template <typename T> -class shared_ptr { - template <typename U> friend class weak_ptr; - public: - typedef T element_type; - - shared_ptr() : ptr_(NULL), control_block_(NULL) {} - - explicit shared_ptr(T* ptr) - : ptr_(ptr), - control_block_(ptr != NULL ? new SharedPtrControlBlock : NULL) { - // If p is non-null and T inherits from enable_shared_from_this, we - // set up the data that shared_from_this needs. - MaybeSetupWeakThis(ptr); - } - - // Copy constructor: makes this object a copy of ptr, and increments - // the reference count. - template <typename U> - shared_ptr(const shared_ptr<U>& ptr) - : ptr_(NULL), - control_block_(NULL) { - Initialize(ptr); - } - // Need non-templated version to prevent the compiler-generated default - shared_ptr(const shared_ptr<T>& ptr) - : ptr_(NULL), - control_block_(NULL) { - Initialize(ptr); - } - - // Assignment operator. Replaces the existing shared_ptr with ptr. - // Increment ptr's reference count and decrement the one being replaced. - template <typename U> - shared_ptr<T>& operator=(const shared_ptr<U>& ptr) { - if (ptr_ != ptr.ptr_) { - shared_ptr<T> me(ptr); // will hold our previous state to be destroyed. - swap(me); - } - return *this; - } - - // Need non-templated version to prevent the compiler-generated default - shared_ptr<T>& operator=(const shared_ptr<T>& ptr) { - if (ptr_ != ptr.ptr_) { - shared_ptr<T> me(ptr); // will hold our previous state to be destroyed. - swap(me); - } - return *this; - } - - // TODO(austern): Consider providing this constructor. The draft C++ standard - // (20.8.10.2.1) includes it. However, it says that this constructor throws - // a bad_weak_ptr exception when ptr is expired. Is it better to provide this - // constructor and make it do something else, like fail with a CHECK, or to - // leave this constructor out entirely? - // - // template <typename U> - // shared_ptr(const weak_ptr<U>& ptr); - - ~shared_ptr() { - if (ptr_ != NULL) { - if (!RefCountDec(&control_block_->refcount_)) { - delete ptr_; - - // weak_count_ is defined as the number of weak_ptrs that observe - // ptr_, plus 1 if refcount_ is nonzero. - if (!RefCountDec(&control_block_->weak_count_)) { - delete control_block_; - } - } - } - } - - // Replaces underlying raw pointer with the one passed in. The reference - // count is set to one (or zero if the pointer is NULL) for the pointer - // being passed in and decremented for the one being replaced. - // - // If you have a compilation error with this code, make sure you aren't - // passing NULL, nullptr, or 0 to this function. Call reset without an - // argument to reset to a null ptr. - template <typename Y> - void reset(Y* p) { - if (p != ptr_) { - shared_ptr<T> tmp(p); - tmp.swap(*this); - } - } - - void reset() { - reset(static_cast<T*>(NULL)); - } - - // Exchanges the contents of this with the contents of r. This function - // supports more efficient swapping since it eliminates the need for a - // temporary shared_ptr object. - void swap(shared_ptr<T>& r) { - using std::swap; // http://go/using-std-swap - swap(ptr_, r.ptr_); - swap(control_block_, r.control_block_); - } - - // The following function is useful for gaining access to the underlying - // pointer when a shared_ptr remains in scope so the reference-count is - // known to be > 0 (e.g. for parameter passing). - T* get() const { - return ptr_; - } - - T& operator*() const { - return *ptr_; - } - - T* operator->() const { - return ptr_; - } - - long use_count() const { - return control_block_ ? control_block_->refcount_ : 1; - } - - bool unique() const { - return use_count() == 1; - } - - private: - // If r is non-empty, initialize *this to share ownership with r, - // increasing the underlying reference count. - // If r is empty, *this remains empty. - // Requires: this is empty, namely this->ptr_ == NULL. - template <typename U> - void Initialize(const shared_ptr<U>& r) { - // This performs a static_cast on r.ptr_ to U*, which is a no-op since it - // is already a U*. So initialization here requires that r.ptr_ is - // implicitly convertible to T*. - InitializeWithStaticCast<U>(r); - } - - // Initializes *this as described in Initialize, but additionally performs a - // static_cast from r.ptr_ (V*) to U*. - // NOTE(gfc): We'd need a more general form to support const_pointer_cast and - // dynamic_pointer_cast, but those operations are sufficiently discouraged - // that supporting static_pointer_cast is sufficient. - template <typename U, typename V> - void InitializeWithStaticCast(const shared_ptr<V>& r) { - if (r.control_block_ != NULL) { - RefCountInc(&r.control_block_->refcount_); - - ptr_ = static_cast<U*>(r.ptr_); - control_block_ = r.control_block_; - } - } - - // Helper function for the constructor that takes a raw pointer. If T - // doesn't inherit from enable_shared_from_this<T> then we have nothing to - // do, so this function is trivial and inline. The other version is declared - // out of line, after the class definition of enable_shared_from_this. - void MaybeSetupWeakThis(enable_shared_from_this<T>* ptr); - void MaybeSetupWeakThis(...) { } - - T* ptr_; - SharedPtrControlBlock* control_block_; - -#ifndef SWIG - template <typename U> - friend class shared_ptr; - - template <typename U, typename V> - friend shared_ptr<U> static_pointer_cast(const shared_ptr<V>& rhs); -#endif -}; - -// Matches the interface of std::swap as an aid to generic programming. -template <typename T> void swap(shared_ptr<T>& r, shared_ptr<T>& s) { - r.swap(s); -} - -template <typename T, typename U> -shared_ptr<T> static_pointer_cast(const shared_ptr<U>& rhs) { - shared_ptr<T> lhs; - lhs.template InitializeWithStaticCast<T>(rhs); - return lhs; -} - -// See comments at the top of the file for a description of why this -// class exists, and the draft C++ standard (as of July 2009 the -// latest draft is N2914) for the detailed specification. -template <typename T> -class weak_ptr { - template <typename U> friend class weak_ptr; - public: - typedef T element_type; - - // Create an empty (i.e. already expired) weak_ptr. - weak_ptr() : ptr_(NULL), control_block_(NULL) { } - - // Create a weak_ptr that observes the same object that ptr points - // to. Note that there is no race condition here: we know that the - // control block can't disappear while we're looking at it because - // it is owned by at least one shared_ptr, ptr. - template <typename U> weak_ptr(const shared_ptr<U>& ptr) { - CopyFrom(ptr.ptr_, ptr.control_block_); - } - - // Copy a weak_ptr. The object it points to might disappear, but we - // don't care: we're only working with the control block, and it can't - // disappear while we're looking at because it's owned by at least one - // weak_ptr, ptr. - template <typename U> weak_ptr(const weak_ptr<U>& ptr) { - CopyFrom(ptr.ptr_, ptr.control_block_); - } - - // Need non-templated version to prevent default copy constructor - weak_ptr(const weak_ptr& ptr) { - CopyFrom(ptr.ptr_, ptr.control_block_); - } - - // Destroy the weak_ptr. If no shared_ptr owns the control block, and if - // we are the last weak_ptr to own it, then it can be deleted. Note that - // weak_count_ is defined as the number of weak_ptrs sharing this control - // block, plus 1 if there are any shared_ptrs. We therefore know that it's - // safe to delete the control block when weak_count_ reaches 0, without - // having to perform any additional tests. - ~weak_ptr() { - if (control_block_ != NULL && - !RefCountDec(&control_block_->weak_count_)) { - delete control_block_; - } - } - - weak_ptr& operator=(const weak_ptr& ptr) { - if (&ptr != this) { - weak_ptr tmp(ptr); - tmp.swap(*this); - } - return *this; - } - template <typename U> weak_ptr& operator=(const weak_ptr<U>& ptr) { - weak_ptr tmp(ptr); - tmp.swap(*this); - return *this; - } - template <typename U> weak_ptr& operator=(const shared_ptr<U>& ptr) { - weak_ptr tmp(ptr); - tmp.swap(*this); - return *this; - } - - void swap(weak_ptr& ptr) { - using std::swap; // http://go/using-std-swap - swap(ptr_, ptr.ptr_); - swap(control_block_, ptr.control_block_); - } - - void reset() { - weak_ptr tmp; - tmp.swap(*this); - } - - // Return the number of shared_ptrs that own the object we are observing. - // Note that this number can be 0 (if this pointer has expired). - long use_count() const { - return control_block_ != NULL ? control_block_->refcount_ : 0; - } - - bool expired() const { return use_count() == 0; } - - // Return a shared_ptr that owns the object we are observing. If we - // have expired, the shared_ptr will be empty. We have to be careful - // about concurrency, though, since some other thread might be - // destroying the last owning shared_ptr while we're in this - // function. We want to increment the refcount only if it's nonzero - // and get the new value, and we want that whole operation to be - // atomic. - shared_ptr<T> lock() const { - shared_ptr<T> result; - if (control_block_ != NULL) { - Atomic32 old_refcount; - do { - old_refcount = control_block_->refcount_; - if (old_refcount == 0) - break; - } while (old_refcount != - NoBarrier_CompareAndSwap( - &control_block_->refcount_, old_refcount, - old_refcount + 1)); - if (old_refcount > 0) { - result.ptr_ = ptr_; - result.control_block_ = control_block_; - } - } - - return result; - } - - private: - void CopyFrom(T* ptr, SharedPtrControlBlock* control_block) { - ptr_ = ptr; - control_block_ = control_block; - if (control_block_ != NULL) - RefCountInc(&control_block_->weak_count_); - } - - private: - element_type* ptr_; - SharedPtrControlBlock* control_block_; -}; - -template <typename T> void swap(weak_ptr<T>& r, weak_ptr<T>& s) { - r.swap(s); -} - -// See comments at the top of the file for a description of why this class -// exists, and section 20.8.10.5 of the draft C++ standard (as of July 2009 -// the latest draft is N2914) for the detailed specification. -template <typename T> -class enable_shared_from_this { - friend class shared_ptr<T>; - public: - // Precondition: there must be a shared_ptr that owns *this and that was - // created, directly or indirectly, from a raw pointer of type T*. (The - // latter part of the condition is technical but not quite redundant; it - // rules out some complicated uses involving inheritance hierarchies.) - shared_ptr<T> shared_from_this() { - // Behavior is undefined if the precondition isn't satisfied; we choose - // to die with a CHECK failure. - GOOGLE_CHECK(!weak_this_.expired()) << "No shared_ptr owns this object"; - return weak_this_.lock(); - } - shared_ptr<const T> shared_from_this() const { - GOOGLE_CHECK(!weak_this_.expired()) << "No shared_ptr owns this object"; - return weak_this_.lock(); - } - - protected: - enable_shared_from_this() { } - enable_shared_from_this(const enable_shared_from_this& other) { } - enable_shared_from_this& operator=(const enable_shared_from_this& other) { - return *this; - } - ~enable_shared_from_this() { } - - private: - weak_ptr<T> weak_this_; -}; - -// This is a helper function called by shared_ptr's constructor from a raw -// pointer. If T inherits from enable_shared_from_this<T>, it sets up -// weak_this_ so that shared_from_this works correctly. If T does not inherit -// from weak_this we get a different overload, defined inline, which does -// nothing. -template<typename T> -void shared_ptr<T>::MaybeSetupWeakThis(enable_shared_from_this<T>* ptr) { - if (ptr) { - GOOGLE_CHECK(ptr->weak_this_.expired()) - << "Object already owned by a shared_ptr"; - ptr->weak_this_ = *this; - } -} - -#endif // UTIL_GTL_USE_STD_SHARED_PTR - -} // internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_STUBS_SHARED_PTR_H__ diff --git a/src/google/protobuf/stubs/type_traits.h b/src/google/protobuf/stubs/type_traits.h deleted file mode 100644 index 3ab5ea7d..00000000 --- a/src/google/protobuf/stubs/type_traits.h +++ /dev/null @@ -1,364 +0,0 @@ -// Copyright (c) 2006, 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: Matt Austern -// -// 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. -// -// Define a small subset of tr1 type traits. The traits we define are: -// enable_if -// is_integral -// is_floating_point -// is_pointer -// is_enum -// is_reference -// is_pod -// has_trivial_constructor -// has_trivial_copy -// has_trivial_assign -// has_trivial_destructor -// remove_const -// remove_volatile -// remove_cv -// remove_reference -// add_reference -// remove_pointer -// is_same -// is_convertible -// We can add more type traits as required. - -#ifndef GOOGLE_PROTOBUF_TYPE_TRAITS_H_ -#define GOOGLE_PROTOBUF_TYPE_TRAITS_H_ - -#include <cstddef> // for NULL -#include <utility> // For pair - -#include <google/protobuf/stubs/template_util.h> // For true_type and false_type - -namespace google { -namespace protobuf { -namespace internal { - -template<typename B, typename D> -struct is_base_of { - typedef char (&yes)[1]; - typedef char (&no)[2]; - - // BEGIN GOOGLE LOCAL MODIFICATION -- check is a #define on Mac. - #undef check - // END GOOGLE LOCAL MODIFICATION - - static yes check(const B*); - static no check(const void*); - - enum { - value = sizeof(check(static_cast<const D*>(NULL))) == sizeof(yes), - }; -}; - -template <bool cond, class T = void> struct enable_if; -template <class T> struct is_integral; -template <class T> struct is_floating_point; -template <class T> struct is_pointer; -// MSVC can't compile this correctly, and neither can gcc 3.3.5 (at least) -#if !defined(_MSC_VER) && !(defined(__GNUC__) && __GNUC__ <= 3) -// is_enum uses is_convertible, which is not available on MSVC. -template <class T> struct is_enum; -#endif -template <class T> struct is_reference; -template <class T> struct is_pod; -template <class T> struct has_trivial_constructor; -template <class T> struct has_trivial_copy; -template <class T> struct has_trivial_assign; -template <class T> struct has_trivial_destructor; -template <class T> struct remove_const; -template <class T> struct remove_volatile; -template <class T> struct remove_cv; -template <class T> struct remove_reference; -template <class T> struct add_reference; -template <class T> struct remove_pointer; -template <class T, class U> struct is_same; -#if !(defined(__GNUC__) && __GNUC__ <= 3) -template <class From, class To> struct is_convertible; -#endif - -// enable_if, equivalent semantics to c++11 std::enable_if, specifically: -// "If B is true, the member typedef type shall equal T; otherwise, there -// shall be no member typedef type." -// Specified by 20.9.7.6 [Other transformations] - -template<bool cond, class T> struct enable_if { typedef T type; }; -template<class T> struct enable_if<false, T> {}; -// is_integral is false except for the built-in integer types. A -// cv-qualified type is integral if and only if the underlying type is. -template <class T> struct is_integral : false_type { }; -template<> struct is_integral<bool> : true_type { }; -template<> struct is_integral<char> : true_type { }; -template<> struct is_integral<unsigned char> : true_type { }; -template<> struct is_integral<signed char> : true_type { }; -#if defined(_MSC_VER) -// wchar_t is not by default a distinct type from unsigned short in -// Microsoft C. -// See http://msdn2.microsoft.com/en-us/library/dh8che7s(VS.80).aspx -template<> struct is_integral<__wchar_t> : true_type { }; -#else -template<> struct is_integral<wchar_t> : true_type { }; -#endif -template<> struct is_integral<short> : true_type { }; -template<> struct is_integral<unsigned short> : true_type { }; -template<> struct is_integral<int> : true_type { }; -template<> struct is_integral<unsigned int> : true_type { }; -template<> struct is_integral<long> : true_type { }; -template<> struct is_integral<unsigned long> : true_type { }; -#if defined(HAVE_LONG_LONG) || defined(_MSC_VER) -template<> struct is_integral<long long> : true_type { }; -template<> struct is_integral<unsigned long long> : true_type { }; -#endif -template <class T> struct is_integral<const T> : is_integral<T> { }; -template <class T> struct is_integral<volatile T> : is_integral<T> { }; -template <class T> struct is_integral<const volatile T> : is_integral<T> { }; - -// is_floating_point is false except for the built-in floating-point types. -// A cv-qualified type is integral if and only if the underlying type is. -template <class T> struct is_floating_point : false_type { }; -template<> struct is_floating_point<float> : true_type { }; -template<> struct is_floating_point<double> : true_type { }; -template<> struct is_floating_point<long double> : true_type { }; -template <class T> struct is_floating_point<const T> - : is_floating_point<T> { }; -template <class T> struct is_floating_point<volatile T> - : is_floating_point<T> { }; -template <class T> struct is_floating_point<const volatile T> - : is_floating_point<T> { }; - -// is_pointer is false except for pointer types. A cv-qualified type (e.g. -// "int* const", as opposed to "int const*") is cv-qualified if and only if -// the underlying type is. -template <class T> struct is_pointer : false_type { }; -template <class T> struct is_pointer<T*> : true_type { }; -template <class T> struct is_pointer<const T> : is_pointer<T> { }; -template <class T> struct is_pointer<volatile T> : is_pointer<T> { }; -template <class T> struct is_pointer<const volatile T> : is_pointer<T> { }; - -#if !defined(_MSC_VER) && !(defined(__GNUC__) && __GNUC__ <= 3) - -namespace type_traits_internal { - -template <class T> struct is_class_or_union { - template <class U> static small_ tester(void (U::*)()); - template <class U> static big_ tester(...); - static const bool value = sizeof(tester<T>(0)) == sizeof(small_); -}; - -// is_convertible chokes if the first argument is an array. That's why -// we use add_reference here. -template <bool NotUnum, class T> struct is_enum_impl - : is_convertible<typename add_reference<T>::type, int> { }; - -template <class T> struct is_enum_impl<true, T> : false_type { }; - -} // namespace type_traits_internal - -// Specified by TR1 [4.5.1] primary type categories. - -// Implementation note: -// -// Each type is either void, integral, floating point, array, pointer, -// reference, member object pointer, member function pointer, enum, -// union or class. Out of these, only integral, floating point, reference, -// class and enum types are potentially convertible to int. Therefore, -// if a type is not a reference, integral, floating point or class and -// is convertible to int, it's a enum. Adding cv-qualification to a type -// does not change whether it's an enum. -// -// Is-convertible-to-int check is done only if all other checks pass, -// because it can't be used with some types (e.g. void or classes with -// inaccessible conversion operators). -template <class T> struct is_enum - : type_traits_internal::is_enum_impl< - is_same<T, void>::value || - is_integral<T>::value || - is_floating_point<T>::value || - is_reference<T>::value || - type_traits_internal::is_class_or_union<T>::value, - T> { }; - -template <class T> struct is_enum<const T> : is_enum<T> { }; -template <class T> struct is_enum<volatile T> : is_enum<T> { }; -template <class T> struct is_enum<const volatile T> : is_enum<T> { }; - -#endif - -// is_reference is false except for reference types. -template<typename T> struct is_reference : false_type {}; -template<typename T> struct is_reference<T&> : true_type {}; - - -// We can't get is_pod right without compiler help, so fail conservatively. -// We will assume it's false except for arithmetic types, enumerations, -// pointers and cv-qualified versions thereof. Note that std::pair<T,U> -// is not a POD even if T and U are PODs. -template <class T> struct is_pod - : integral_constant<bool, (is_integral<T>::value || - is_floating_point<T>::value || -#if !defined(_MSC_VER) && !(defined(__GNUC__) && __GNUC__ <= 3) - // is_enum is not available on MSVC. - is_enum<T>::value || -#endif - is_pointer<T>::value)> { }; -template <class T> struct is_pod<const T> : is_pod<T> { }; -template <class T> struct is_pod<volatile T> : is_pod<T> { }; -template <class T> struct is_pod<const volatile T> : is_pod<T> { }; - - -// We can't get has_trivial_constructor right without compiler help, so -// fail conservatively. We will assume it's false except for: (1) types -// for which is_pod is true. (2) std::pair of types with trivial -// constructors. (3) array of a type with a trivial constructor. -// (4) const versions thereof. -template <class T> struct has_trivial_constructor : is_pod<T> { }; -template <class T, class U> struct has_trivial_constructor<std::pair<T, U> > - : integral_constant<bool, - (has_trivial_constructor<T>::value && - has_trivial_constructor<U>::value)> { }; -template <class A, int N> struct has_trivial_constructor<A[N]> - : has_trivial_constructor<A> { }; -template <class T> struct has_trivial_constructor<const T> - : has_trivial_constructor<T> { }; - -// We can't get has_trivial_copy right without compiler help, so fail -// conservatively. We will assume it's false except for: (1) types -// for which is_pod is true. (2) std::pair of types with trivial copy -// constructors. (3) array of a type with a trivial copy constructor. -// (4) const versions thereof. -template <class T> struct has_trivial_copy : is_pod<T> { }; -template <class T, class U> struct has_trivial_copy<std::pair<T, U> > - : integral_constant<bool, - (has_trivial_copy<T>::value && - has_trivial_copy<U>::value)> { }; -template <class A, int N> struct has_trivial_copy<A[N]> - : has_trivial_copy<A> { }; -template <class T> struct has_trivial_copy<const T> : has_trivial_copy<T> { }; - -// We can't get has_trivial_assign right without compiler help, so fail -// conservatively. We will assume it's false except for: (1) types -// for which is_pod is true. (2) std::pair of types with trivial copy -// constructors. (3) array of a type with a trivial assign constructor. -template <class T> struct has_trivial_assign : is_pod<T> { }; -template <class T, class U> struct has_trivial_assign<std::pair<T, U> > - : integral_constant<bool, - (has_trivial_assign<T>::value && - has_trivial_assign<U>::value)> { }; -template <class A, int N> struct has_trivial_assign<A[N]> - : has_trivial_assign<A> { }; - -// We can't get has_trivial_destructor right without compiler help, so -// fail conservatively. We will assume it's false except for: (1) types -// for which is_pod is true. (2) std::pair of types with trivial -// destructors. (3) array of a type with a trivial destructor. -// (4) const versions thereof. -template <class T> struct has_trivial_destructor : is_pod<T> { }; -template <class T, class U> struct has_trivial_destructor<std::pair<T, U> > - : integral_constant<bool, - (has_trivial_destructor<T>::value && - has_trivial_destructor<U>::value)> { }; -template <class A, int N> struct has_trivial_destructor<A[N]> - : has_trivial_destructor<A> { }; -template <class T> struct has_trivial_destructor<const T> - : has_trivial_destructor<T> { }; - -// Specified by TR1 [4.7.1] -template<typename T> struct remove_const { typedef T type; }; -template<typename T> struct remove_const<T const> { typedef T type; }; -template<typename T> struct remove_volatile { typedef T type; }; -template<typename T> struct remove_volatile<T volatile> { typedef T type; }; -template<typename T> struct remove_cv { - typedef typename remove_const<typename remove_volatile<T>::type>::type type; -}; - - -// Specified by TR1 [4.7.2] Reference modifications. -template<typename T> struct remove_reference { typedef T type; }; -template<typename T> struct remove_reference<T&> { typedef T type; }; - -template <typename T> struct add_reference { typedef T& type; }; -template <typename T> struct add_reference<T&> { typedef T& type; }; - -// Specified by TR1 [4.7.4] Pointer modifications. -template<typename T> struct remove_pointer { typedef T type; }; -template<typename T> struct remove_pointer<T*> { typedef T type; }; -template<typename T> struct remove_pointer<T* const> { typedef T type; }; -template<typename T> struct remove_pointer<T* volatile> { typedef T type; }; -template<typename T> struct remove_pointer<T* const volatile> { - typedef T type; }; - -// Specified by TR1 [4.6] Relationships between types -template<typename T, typename U> struct is_same : public false_type { }; -template<typename T> struct is_same<T, T> : public true_type { }; - -// Specified by TR1 [4.6] Relationships between types -#if !(defined(__GNUC__) && __GNUC__ <= 3) -namespace type_traits_internal { - -// This class is an implementation detail for is_convertible, and you -// don't need to know how it works to use is_convertible. For those -// who care: we declare two different functions, one whose argument is -// of type To and one with a variadic argument list. We give them -// return types of different size, so we can use sizeof to trick the -// compiler into telling us which function it would have chosen if we -// had called it with an argument of type From. See Alexandrescu's -// _Modern C++ Design_ for more details on this sort of trick. - -template <typename From, typename To> -struct ConvertHelper { - static small_ Test(To); - static big_ Test(...); - static From Create(); - enum { - value = sizeof(Test(Create())) == sizeof(small_) - }; -}; -} // namespace type_traits_internal - -// Inherits from true_type if From is convertible to To, false_type otherwise. -template <typename From, typename To> -struct is_convertible - : integral_constant<bool, - type_traits_internal::ConvertHelper<From, To>::value> { -}; -#endif - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_TYPE_TRAITS_H_ diff --git a/src/google/protobuf/stubs/type_traits_unittest.cc b/src/google/protobuf/stubs/type_traits_unittest.cc deleted file mode 100644 index 0e54b952..00000000 --- a/src/google/protobuf/stubs/type_traits_unittest.cc +++ /dev/null @@ -1,631 +0,0 @@ -// Copyright (c) 2006, 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: Matt Austern - -#include <google/protobuf/stubs/type_traits.h> - -#include <stdlib.h> // for exit() -#include <stdio.h> -#include <string> -#include <vector> - -#include <google/protobuf/testing/googletest.h> -#include <gtest/gtest.h> - -typedef int int32; -// IBM AIX typedefs `int64` in `sys/inttypes.h`, included transitively above. -#ifndef _AIX -typedef long int64; -#endif - -using std::string; -using std::vector; -using std::pair; - - -// This assertion produces errors like "error: invalid use of -// incomplete type 'struct <unnamed>::AssertTypesEq<const int, int>'" -// when it fails. -template<typename T, typename U> struct AssertTypesEq; -template<typename T> struct AssertTypesEq<T, T> {}; -#define COMPILE_ASSERT_TYPES_EQ(T, U) static_cast<void>(AssertTypesEq<T, U>()) - -// A user-defined POD type. -struct A { - int n_; -}; - -// A user-defined non-POD type with a trivial copy constructor. -class B { - public: - explicit B(int n) : n_(n) { } - private: - int n_; -}; - -// Another user-defined non-POD type with a trivial copy constructor. -// We will explicitly declare C to have a trivial copy constructor -// by specializing has_trivial_copy. -class C { - public: - explicit C(int n) : n_(n) { } - private: - int n_; -}; - -namespace google { -namespace protobuf { -namespace internal { -template<> struct has_trivial_copy<C> : true_type { }; -} // namespace internal -} // namespace protobuf -} // namespace google - -// Another user-defined non-POD type with a trivial assignment operator. -// We will explicitly declare C to have a trivial assignment operator -// by specializing has_trivial_assign. -class D { - public: - explicit D(int n) : n_(n) { } - private: - int n_; -}; - -namespace google { -namespace protobuf { -namespace internal { -template<> struct has_trivial_assign<D> : true_type { }; -} // namespace internal -} // namespace protobuf -} // namespace google - -// Another user-defined non-POD type with a trivial constructor. -// We will explicitly declare E to have a trivial constructor -// by specializing has_trivial_constructor. -class E { - public: - int n_; -}; - -namespace google { -namespace protobuf { -namespace internal { -template<> struct has_trivial_constructor<E> : true_type { }; -} // namespace internal -} // namespace protobuf -} // namespace google - -// Another user-defined non-POD type with a trivial destructor. -// We will explicitly declare E to have a trivial destructor -// by specializing has_trivial_destructor. -class F { - public: - explicit F(int n) : n_(n) { } - private: - int n_; -}; - -namespace google { -namespace protobuf { -namespace internal { -template<> struct has_trivial_destructor<F> : true_type { }; -} // namespace internal -} // namespace protobuf -} // namespace google - -enum G {}; - -union H {}; - -class I { - public: - operator int() const; -}; - -class J { - private: - operator int() const; -}; - -namespace google { -namespace protobuf { -namespace internal { -namespace { - -// A base class and a derived class that inherits from it, used for -// testing conversion type traits. -class Base { - public: - virtual ~Base() { } -}; - -class Derived : public Base { -}; - -TEST(TypeTraitsTest, TestIsInteger) { - // Verify that is_integral is true for all integer types. - EXPECT_TRUE(is_integral<bool>::value); - EXPECT_TRUE(is_integral<char>::value); - EXPECT_TRUE(is_integral<unsigned char>::value); - EXPECT_TRUE(is_integral<signed char>::value); - EXPECT_TRUE(is_integral<wchar_t>::value); - EXPECT_TRUE(is_integral<int>::value); - EXPECT_TRUE(is_integral<unsigned int>::value); - EXPECT_TRUE(is_integral<short>::value); - EXPECT_TRUE(is_integral<unsigned short>::value); - EXPECT_TRUE(is_integral<long>::value); - EXPECT_TRUE(is_integral<unsigned long>::value); - - // Verify that is_integral is false for a few non-integer types. - EXPECT_FALSE(is_integral<void>::value); - EXPECT_FALSE(is_integral<float>::value); - EXPECT_FALSE(is_integral<string>::value); - EXPECT_FALSE(is_integral<int*>::value); - EXPECT_FALSE(is_integral<A>::value); - EXPECT_FALSE((is_integral<pair<int, int> >::value)); - - // Verify that cv-qualified integral types are still integral, and - // cv-qualified non-integral types are still non-integral. - EXPECT_TRUE(is_integral<const char>::value); - EXPECT_TRUE(is_integral<volatile bool>::value); - EXPECT_TRUE(is_integral<const volatile unsigned int>::value); - EXPECT_FALSE(is_integral<const float>::value); - EXPECT_FALSE(is_integral<int* volatile>::value); - EXPECT_FALSE(is_integral<const volatile string>::value); -} - -TEST(TypeTraitsTest, TestIsFloating) { - // Verify that is_floating_point is true for all floating-point types. - EXPECT_TRUE(is_floating_point<float>::value); - EXPECT_TRUE(is_floating_point<double>::value); - EXPECT_TRUE(is_floating_point<long double>::value); - - // Verify that is_floating_point is false for a few non-float types. - EXPECT_FALSE(is_floating_point<void>::value); - EXPECT_FALSE(is_floating_point<long>::value); - EXPECT_FALSE(is_floating_point<string>::value); - EXPECT_FALSE(is_floating_point<float*>::value); - EXPECT_FALSE(is_floating_point<A>::value); - EXPECT_FALSE((is_floating_point<pair<int, int> >::value)); - - // Verify that cv-qualified floating point types are still floating, and - // cv-qualified non-floating types are still non-floating. - EXPECT_TRUE(is_floating_point<const float>::value); - EXPECT_TRUE(is_floating_point<volatile double>::value); - EXPECT_TRUE(is_floating_point<const volatile long double>::value); - EXPECT_FALSE(is_floating_point<const int>::value); - EXPECT_FALSE(is_floating_point<volatile string>::value); - EXPECT_FALSE(is_floating_point<const volatile char>::value); -} - -TEST(TypeTraitsTest, TestIsPointer) { - // Verify that is_pointer is true for some pointer types. - EXPECT_TRUE(is_pointer<int*>::value); - EXPECT_TRUE(is_pointer<void*>::value); - EXPECT_TRUE(is_pointer<string*>::value); - EXPECT_TRUE(is_pointer<const void*>::value); - EXPECT_TRUE(is_pointer<volatile float* const*>::value); - - // Verify that is_pointer is false for some non-pointer types. - EXPECT_FALSE(is_pointer<void>::value); - EXPECT_FALSE(is_pointer<float&>::value); - EXPECT_FALSE(is_pointer<long>::value); - EXPECT_FALSE(is_pointer<vector<int*> >::value); - EXPECT_FALSE(is_pointer<int[5]>::value); - - // A function pointer is a pointer, but a function type, or a function - // reference type, is not. - EXPECT_TRUE(is_pointer<int (*)(int x)>::value); - EXPECT_FALSE(is_pointer<void(char x)>::value); - EXPECT_FALSE(is_pointer<double (&)(string x)>::value); - - // Verify that is_pointer<T> is true for some cv-qualified pointer types, - // and false for some cv-qualified non-pointer types. - EXPECT_TRUE(is_pointer<int* const>::value); - EXPECT_TRUE(is_pointer<const void* volatile>::value); - EXPECT_TRUE(is_pointer<char** const volatile>::value); - EXPECT_FALSE(is_pointer<const int>::value); - EXPECT_FALSE(is_pointer<volatile std::vector<int*> >::value); - EXPECT_FALSE(is_pointer<const volatile double>::value); -} - -TEST(TypeTraitsTest, TestIsEnum) { -// is_enum isn't supported on MSVC or gcc 3.x -#if !defined(_MSC_VER) && !(defined(__GNUC__) && __GNUC__ <= 3) - // Verify that is_enum is true for enum types. - EXPECT_TRUE(is_enum<G>::value); - EXPECT_TRUE(is_enum<const G>::value); - EXPECT_TRUE(is_enum<volatile G>::value); - EXPECT_TRUE(is_enum<const volatile G>::value); - - // Verify that is_enum is false for a few non-enum types. - EXPECT_FALSE(is_enum<void>::value); - EXPECT_FALSE(is_enum<G&>::value); - EXPECT_FALSE(is_enum<G[1]>::value); - EXPECT_FALSE(is_enum<const G[1]>::value); - EXPECT_FALSE(is_enum<G[]>::value); - EXPECT_FALSE(is_enum<int>::value); - EXPECT_FALSE(is_enum<float>::value); - EXPECT_FALSE(is_enum<A>::value); - EXPECT_FALSE(is_enum<A*>::value); - EXPECT_FALSE(is_enum<const A>::value); - EXPECT_FALSE(is_enum<H>::value); - EXPECT_FALSE(is_enum<I>::value); - EXPECT_FALSE(is_enum<J>::value); - EXPECT_FALSE(is_enum<void()>::value); - EXPECT_FALSE(is_enum<void(*)()>::value); - EXPECT_FALSE(is_enum<int A::*>::value); - EXPECT_FALSE(is_enum<void (A::*)()>::value); -#endif -} - -TEST(TypeTraitsTest, TestIsReference) { - // Verifies that is_reference is true for all reference types. - typedef float& RefFloat; - EXPECT_TRUE(is_reference<float&>::value); - EXPECT_TRUE(is_reference<const int&>::value); - EXPECT_TRUE(is_reference<const int*&>::value); - EXPECT_TRUE(is_reference<int (&)(bool)>::value); - EXPECT_TRUE(is_reference<RefFloat>::value); - EXPECT_TRUE(is_reference<const RefFloat>::value); - EXPECT_TRUE(is_reference<volatile RefFloat>::value); - EXPECT_TRUE(is_reference<const volatile RefFloat>::value); - - - // Verifies that is_reference is false for all non-reference types. - EXPECT_FALSE(is_reference<float>::value); - EXPECT_FALSE(is_reference<const float>::value); - EXPECT_FALSE(is_reference<volatile float>::value); - EXPECT_FALSE(is_reference<const volatile float>::value); - EXPECT_FALSE(is_reference<const int*>::value); - EXPECT_FALSE(is_reference<int()>::value); - EXPECT_FALSE(is_reference<void(*)(const char&)>::value); -} - -TEST(TypeTraitsTest, TestAddReference) { - COMPILE_ASSERT_TYPES_EQ(int&, add_reference<int>::type); - COMPILE_ASSERT_TYPES_EQ(const int&, add_reference<const int>::type); - COMPILE_ASSERT_TYPES_EQ(volatile int&, - add_reference<volatile int>::type); - COMPILE_ASSERT_TYPES_EQ(const volatile int&, - add_reference<const volatile int>::type); - COMPILE_ASSERT_TYPES_EQ(int&, add_reference<int&>::type); - COMPILE_ASSERT_TYPES_EQ(const int&, add_reference<const int&>::type); - COMPILE_ASSERT_TYPES_EQ(volatile int&, - add_reference<volatile int&>::type); - COMPILE_ASSERT_TYPES_EQ(const volatile int&, - add_reference<const volatile int&>::type); -} - -TEST(TypeTraitsTest, TestIsPod) { - // Verify that arithmetic types and pointers are marked as PODs. - EXPECT_TRUE(is_pod<bool>::value); - EXPECT_TRUE(is_pod<char>::value); - EXPECT_TRUE(is_pod<unsigned char>::value); - EXPECT_TRUE(is_pod<signed char>::value); - EXPECT_TRUE(is_pod<wchar_t>::value); - EXPECT_TRUE(is_pod<int>::value); - EXPECT_TRUE(is_pod<unsigned int>::value); - EXPECT_TRUE(is_pod<short>::value); - EXPECT_TRUE(is_pod<unsigned short>::value); - EXPECT_TRUE(is_pod<long>::value); - EXPECT_TRUE(is_pod<unsigned long>::value); - EXPECT_TRUE(is_pod<float>::value); - EXPECT_TRUE(is_pod<double>::value); - EXPECT_TRUE(is_pod<long double>::value); - EXPECT_TRUE(is_pod<string*>::value); - EXPECT_TRUE(is_pod<A*>::value); - EXPECT_TRUE(is_pod<const B*>::value); - EXPECT_TRUE(is_pod<C**>::value); - EXPECT_TRUE(is_pod<const int>::value); - EXPECT_TRUE(is_pod<char* volatile>::value); - EXPECT_TRUE(is_pod<const volatile double>::value); -#if !defined(_MSC_VER) && !(defined(__GNUC__) && __GNUC__ <= 3) - EXPECT_TRUE(is_pod<G>::value); - EXPECT_TRUE(is_pod<const G>::value); - EXPECT_TRUE(is_pod<volatile G>::value); - EXPECT_TRUE(is_pod<const volatile G>::value); -#endif - - // Verify that some non-POD types are not marked as PODs. - EXPECT_FALSE(is_pod<void>::value); - EXPECT_FALSE(is_pod<string>::value); - EXPECT_FALSE((is_pod<pair<int, int> >::value)); - EXPECT_FALSE(is_pod<A>::value); - EXPECT_FALSE(is_pod<B>::value); - EXPECT_FALSE(is_pod<C>::value); - EXPECT_FALSE(is_pod<const string>::value); - EXPECT_FALSE(is_pod<volatile A>::value); - EXPECT_FALSE(is_pod<const volatile B>::value); -} - -TEST(TypeTraitsTest, TestHasTrivialConstructor) { - // Verify that arithmetic types and pointers have trivial constructors. - EXPECT_TRUE(has_trivial_constructor<bool>::value); - EXPECT_TRUE(has_trivial_constructor<char>::value); - EXPECT_TRUE(has_trivial_constructor<unsigned char>::value); - EXPECT_TRUE(has_trivial_constructor<signed char>::value); - EXPECT_TRUE(has_trivial_constructor<wchar_t>::value); - EXPECT_TRUE(has_trivial_constructor<int>::value); - EXPECT_TRUE(has_trivial_constructor<unsigned int>::value); - EXPECT_TRUE(has_trivial_constructor<short>::value); - EXPECT_TRUE(has_trivial_constructor<unsigned short>::value); - EXPECT_TRUE(has_trivial_constructor<long>::value); - EXPECT_TRUE(has_trivial_constructor<unsigned long>::value); - EXPECT_TRUE(has_trivial_constructor<float>::value); - EXPECT_TRUE(has_trivial_constructor<double>::value); - EXPECT_TRUE(has_trivial_constructor<long double>::value); - EXPECT_TRUE(has_trivial_constructor<string*>::value); - EXPECT_TRUE(has_trivial_constructor<A*>::value); - EXPECT_TRUE(has_trivial_constructor<const B*>::value); - EXPECT_TRUE(has_trivial_constructor<C**>::value); - - // Verify that pairs and arrays of such types have trivial - // constructors. - typedef int int10[10]; - EXPECT_TRUE((has_trivial_constructor<pair<int, char*> >::value)); - EXPECT_TRUE(has_trivial_constructor<int10>::value); - - // Verify that pairs of types without trivial constructors - // are not marked as trivial. - EXPECT_FALSE((has_trivial_constructor<pair<int, string> >::value)); - EXPECT_FALSE((has_trivial_constructor<pair<string, int> >::value)); - - // Verify that types without trivial constructors are - // correctly marked as such. - EXPECT_FALSE(has_trivial_constructor<string>::value); - EXPECT_FALSE(has_trivial_constructor<vector<int> >::value); - - // Verify that E, which we have declared to have a trivial - // constructor, is correctly marked as such. - EXPECT_TRUE(has_trivial_constructor<E>::value); -} - -TEST(TypeTraitsTest, TestHasTrivialCopy) { - // Verify that arithmetic types and pointers have trivial copy - // constructors. - EXPECT_TRUE(has_trivial_copy<bool>::value); - EXPECT_TRUE(has_trivial_copy<char>::value); - EXPECT_TRUE(has_trivial_copy<unsigned char>::value); - EXPECT_TRUE(has_trivial_copy<signed char>::value); - EXPECT_TRUE(has_trivial_copy<wchar_t>::value); - EXPECT_TRUE(has_trivial_copy<int>::value); - EXPECT_TRUE(has_trivial_copy<unsigned int>::value); - EXPECT_TRUE(has_trivial_copy<short>::value); - EXPECT_TRUE(has_trivial_copy<unsigned short>::value); - EXPECT_TRUE(has_trivial_copy<long>::value); - EXPECT_TRUE(has_trivial_copy<unsigned long>::value); - EXPECT_TRUE(has_trivial_copy<float>::value); - EXPECT_TRUE(has_trivial_copy<double>::value); - EXPECT_TRUE(has_trivial_copy<long double>::value); - EXPECT_TRUE(has_trivial_copy<string*>::value); - EXPECT_TRUE(has_trivial_copy<A*>::value); - EXPECT_TRUE(has_trivial_copy<const B*>::value); - EXPECT_TRUE(has_trivial_copy<C**>::value); - - // Verify that pairs and arrays of such types have trivial - // copy constructors. - typedef int int10[10]; - EXPECT_TRUE((has_trivial_copy<pair<int, char*> >::value)); - EXPECT_TRUE(has_trivial_copy<int10>::value); - - // Verify that pairs of types without trivial copy constructors - // are not marked as trivial. - EXPECT_FALSE((has_trivial_copy<pair<int, string> >::value)); - EXPECT_FALSE((has_trivial_copy<pair<string, int> >::value)); - - // Verify that types without trivial copy constructors are - // correctly marked as such. - EXPECT_FALSE(has_trivial_copy<string>::value); - EXPECT_FALSE(has_trivial_copy<vector<int> >::value); - - // Verify that C, which we have declared to have a trivial - // copy constructor, is correctly marked as such. - EXPECT_TRUE(has_trivial_copy<C>::value); -} - -TEST(TypeTraitsTest, TestHasTrivialAssign) { - // Verify that arithmetic types and pointers have trivial assignment - // operators. - EXPECT_TRUE(has_trivial_assign<bool>::value); - EXPECT_TRUE(has_trivial_assign<char>::value); - EXPECT_TRUE(has_trivial_assign<unsigned char>::value); - EXPECT_TRUE(has_trivial_assign<signed char>::value); - EXPECT_TRUE(has_trivial_assign<wchar_t>::value); - EXPECT_TRUE(has_trivial_assign<int>::value); - EXPECT_TRUE(has_trivial_assign<unsigned int>::value); - EXPECT_TRUE(has_trivial_assign<short>::value); - EXPECT_TRUE(has_trivial_assign<unsigned short>::value); - EXPECT_TRUE(has_trivial_assign<long>::value); - EXPECT_TRUE(has_trivial_assign<unsigned long>::value); - EXPECT_TRUE(has_trivial_assign<float>::value); - EXPECT_TRUE(has_trivial_assign<double>::value); - EXPECT_TRUE(has_trivial_assign<long double>::value); - EXPECT_TRUE(has_trivial_assign<string*>::value); - EXPECT_TRUE(has_trivial_assign<A*>::value); - EXPECT_TRUE(has_trivial_assign<const B*>::value); - EXPECT_TRUE(has_trivial_assign<C**>::value); - - // Verify that pairs and arrays of such types have trivial - // assignment operators. - typedef int int10[10]; - EXPECT_TRUE((has_trivial_assign<pair<int, char*> >::value)); - EXPECT_TRUE(has_trivial_assign<int10>::value); - - // Verify that pairs of types without trivial assignment operators - // are not marked as trivial. - EXPECT_FALSE((has_trivial_assign<pair<int, string> >::value)); - EXPECT_FALSE((has_trivial_assign<pair<string, int> >::value)); - - // Verify that types without trivial assignment operators are - // correctly marked as such. - EXPECT_FALSE(has_trivial_assign<string>::value); - EXPECT_FALSE(has_trivial_assign<vector<int> >::value); - - // Verify that D, which we have declared to have a trivial - // assignment operator, is correctly marked as such. - EXPECT_TRUE(has_trivial_assign<D>::value); -} - -TEST(TypeTraitsTest, TestHasTrivialDestructor) { - // Verify that arithmetic types and pointers have trivial destructors. - EXPECT_TRUE(has_trivial_destructor<bool>::value); - EXPECT_TRUE(has_trivial_destructor<char>::value); - EXPECT_TRUE(has_trivial_destructor<unsigned char>::value); - EXPECT_TRUE(has_trivial_destructor<signed char>::value); - EXPECT_TRUE(has_trivial_destructor<wchar_t>::value); - EXPECT_TRUE(has_trivial_destructor<int>::value); - EXPECT_TRUE(has_trivial_destructor<unsigned int>::value); - EXPECT_TRUE(has_trivial_destructor<short>::value); - EXPECT_TRUE(has_trivial_destructor<unsigned short>::value); - EXPECT_TRUE(has_trivial_destructor<long>::value); - EXPECT_TRUE(has_trivial_destructor<unsigned long>::value); - EXPECT_TRUE(has_trivial_destructor<float>::value); - EXPECT_TRUE(has_trivial_destructor<double>::value); - EXPECT_TRUE(has_trivial_destructor<long double>::value); - EXPECT_TRUE(has_trivial_destructor<string*>::value); - EXPECT_TRUE(has_trivial_destructor<A*>::value); - EXPECT_TRUE(has_trivial_destructor<const B*>::value); - EXPECT_TRUE(has_trivial_destructor<C**>::value); - - // Verify that pairs and arrays of such types have trivial - // destructors. - typedef int int10[10]; - EXPECT_TRUE((has_trivial_destructor<pair<int, char*> >::value)); - EXPECT_TRUE(has_trivial_destructor<int10>::value); - - // Verify that pairs of types without trivial destructors - // are not marked as trivial. - EXPECT_FALSE((has_trivial_destructor<pair<int, string> >::value)); - EXPECT_FALSE((has_trivial_destructor<pair<string, int> >::value)); - - // Verify that types without trivial destructors are - // correctly marked as such. - EXPECT_FALSE(has_trivial_destructor<string>::value); - EXPECT_FALSE(has_trivial_destructor<vector<int> >::value); - - // Verify that F, which we have declared to have a trivial - // destructor, is correctly marked as such. - EXPECT_TRUE(has_trivial_destructor<F>::value); -} - -// Tests remove_pointer. -TEST(TypeTraitsTest, TestRemovePointer) { - COMPILE_ASSERT_TYPES_EQ(int, remove_pointer<int>::type); - COMPILE_ASSERT_TYPES_EQ(int, remove_pointer<int*>::type); - COMPILE_ASSERT_TYPES_EQ(const int, remove_pointer<const int*>::type); - COMPILE_ASSERT_TYPES_EQ(int, remove_pointer<int* const>::type); - COMPILE_ASSERT_TYPES_EQ(int, remove_pointer<int* volatile>::type); -} - -TEST(TypeTraitsTest, TestRemoveConst) { - COMPILE_ASSERT_TYPES_EQ(int, remove_const<int>::type); - COMPILE_ASSERT_TYPES_EQ(int, remove_const<const int>::type); - COMPILE_ASSERT_TYPES_EQ(int *, remove_const<int * const>::type); - // TR1 examples. - COMPILE_ASSERT_TYPES_EQ(const int *, remove_const<const int *>::type); - COMPILE_ASSERT_TYPES_EQ(volatile int, - remove_const<const volatile int>::type); -} - -TEST(TypeTraitsTest, TestRemoveVolatile) { - COMPILE_ASSERT_TYPES_EQ(int, remove_volatile<int>::type); - COMPILE_ASSERT_TYPES_EQ(int, remove_volatile<volatile int>::type); - COMPILE_ASSERT_TYPES_EQ(int *, remove_volatile<int * volatile>::type); - // TR1 examples. - COMPILE_ASSERT_TYPES_EQ(volatile int *, - remove_volatile<volatile int *>::type); - COMPILE_ASSERT_TYPES_EQ(const int, - remove_volatile<const volatile int>::type); -} - -TEST(TypeTraitsTest, TestRemoveCV) { - COMPILE_ASSERT_TYPES_EQ(int, remove_cv<int>::type); - COMPILE_ASSERT_TYPES_EQ(int, remove_cv<volatile int>::type); - COMPILE_ASSERT_TYPES_EQ(int, remove_cv<const int>::type); - COMPILE_ASSERT_TYPES_EQ(int *, remove_cv<int * const volatile>::type); - // TR1 examples. - COMPILE_ASSERT_TYPES_EQ(const volatile int *, - remove_cv<const volatile int *>::type); - COMPILE_ASSERT_TYPES_EQ(int, - remove_cv<const volatile int>::type); -} - -TEST(TypeTraitsTest, TestRemoveReference) { - COMPILE_ASSERT_TYPES_EQ(int, remove_reference<int>::type); - COMPILE_ASSERT_TYPES_EQ(int, remove_reference<int&>::type); - COMPILE_ASSERT_TYPES_EQ(const int, remove_reference<const int&>::type); - COMPILE_ASSERT_TYPES_EQ(int*, remove_reference<int * &>::type); -} - -TEST(TypeTraitsTest, TestIsSame) { - EXPECT_TRUE((is_same<int32, int32>::value)); - EXPECT_FALSE((is_same<int32, int64>::value)); - EXPECT_FALSE((is_same<int64, int32>::value)); - EXPECT_FALSE((is_same<int, const int>::value)); - - EXPECT_TRUE((is_same<void, void>::value)); - EXPECT_FALSE((is_same<void, int>::value)); - EXPECT_FALSE((is_same<int, void>::value)); - - EXPECT_TRUE((is_same<int*, int*>::value)); - EXPECT_TRUE((is_same<void*, void*>::value)); - EXPECT_FALSE((is_same<int*, void*>::value)); - EXPECT_FALSE((is_same<void*, int*>::value)); - EXPECT_FALSE((is_same<void*, const void*>::value)); - EXPECT_FALSE((is_same<void*, void* const>::value)); - - EXPECT_TRUE((is_same<Base*, Base*>::value)); - EXPECT_TRUE((is_same<Derived*, Derived*>::value)); - EXPECT_FALSE((is_same<Base*, Derived*>::value)); - EXPECT_FALSE((is_same<Derived*, Base*>::value)); -} - -TEST(TypeTraitsTest, TestConvertible) { -#if !(defined(__GNUC__) && __GNUC__ <= 3) - EXPECT_TRUE((is_convertible<int, int>::value)); - EXPECT_TRUE((is_convertible<int, long>::value)); - EXPECT_TRUE((is_convertible<long, int>::value)); - - EXPECT_TRUE((is_convertible<int*, void*>::value)); - EXPECT_FALSE((is_convertible<void*, int*>::value)); - - EXPECT_TRUE((is_convertible<Derived*, Base*>::value)); - EXPECT_FALSE((is_convertible<Base*, Derived*>::value)); - EXPECT_TRUE((is_convertible<Derived*, const Base*>::value)); - EXPECT_FALSE((is_convertible<const Derived*, Base*>::value)); -#endif -} - -} // anonymous namespace -} // namespace internal -} // namespace protobuf -} // namespace google diff --git a/src/google/protobuf/util/internal/default_value_objectwriter.cc b/src/google/protobuf/util/internal/default_value_objectwriter.cc index 2826e90e..b41feb7a 100644 --- a/src/google/protobuf/util/internal/default_value_objectwriter.cc +++ b/src/google/protobuf/util/internal/default_value_objectwriter.cc @@ -66,6 +66,7 @@ DefaultValueObjectWriter::DefaultValueObjectWriter( root_(nullptr), suppress_empty_list_(false), preserve_proto_field_names_(false), + use_ints_for_enums_(false), field_scrub_callback_(nullptr), ow_(ow) {} @@ -200,10 +201,10 @@ DefaultValueObjectWriter::Node* DefaultValueObjectWriter::CreateNewNode( DefaultValueObjectWriter::Node* DefaultValueObjectWriter::CreateNewNode( const string& name, const google::protobuf::Type* type, NodeKind kind, const DataPiece& data, bool is_placeholder, const std::vector<string>& path, - bool suppress_empty_list, bool preserve_proto_field_names, + bool suppress_empty_list, bool preserve_proto_field_names, bool use_ints_for_enums, FieldScrubCallBack* field_scrub_callback) { return new Node(name, type, kind, data, is_placeholder, path, - suppress_empty_list, preserve_proto_field_names, + suppress_empty_list, preserve_proto_field_names, use_ints_for_enums, field_scrub_callback); } @@ -220,12 +221,13 @@ DefaultValueObjectWriter::Node::Node( path_(path), suppress_empty_list_(suppress_empty_list), preserve_proto_field_names_(false), + use_ints_for_enums_(false), field_scrub_callback_(field_scrub_callback) {} DefaultValueObjectWriter::Node::Node( const string& name, const google::protobuf::Type* type, NodeKind kind, const DataPiece& data, bool is_placeholder, const std::vector<string>& path, - bool suppress_empty_list, bool preserve_proto_field_names, + bool suppress_empty_list, bool preserve_proto_field_names, bool use_ints_for_enums, FieldScrubCallBack* field_scrub_callback) : name_(name), type_(type), @@ -236,6 +238,7 @@ DefaultValueObjectWriter::Node::Node( path_(path), suppress_empty_list_(suppress_empty_list), preserve_proto_field_names_(preserve_proto_field_names), + use_ints_for_enums_(use_ints_for_enums), field_scrub_callback_(field_scrub_callback) {} DefaultValueObjectWriter::Node* DefaultValueObjectWriter::Node::FindChild( @@ -408,9 +411,9 @@ void DefaultValueObjectWriter::Node::PopulateChildren( std::unique_ptr<Node> child(new Node( preserve_proto_field_names_ ? field.name() : field.json_name(), field_type, kind, - kind == PRIMITIVE ? CreateDefaultDataPieceForField(field, typeinfo) + kind == PRIMITIVE ? CreateDefaultDataPieceForField(field, typeinfo, use_ints_for_enums_) : DataPiece::NullData(), - true, path, suppress_empty_list_, preserve_proto_field_names_, + true, path, suppress_empty_list_, preserve_proto_field_names_, use_ints_for_enums_, field_scrub_callback_)); new_children.push_back(child.release()); } @@ -435,7 +438,7 @@ void DefaultValueObjectWriter::MaybePopulateChildrenOfAny(Node* node) { } DataPiece DefaultValueObjectWriter::FindEnumDefault( - const google::protobuf::Field& field, const TypeInfo* typeinfo) { + const google::protobuf::Field& field, const TypeInfo* typeinfo, bool use_ints_for_enums) { if (!field.default_value().empty()) return DataPiece(field.default_value(), true); @@ -448,12 +451,12 @@ DataPiece DefaultValueObjectWriter::FindEnumDefault( } // We treat the first value as the default if none is specified. return enum_type->enumvalue_size() > 0 - ? DataPiece(enum_type->enumvalue(0).name(), true) + ? (use_ints_for_enums ? DataPiece(enum_type->enumvalue(0).number()) : DataPiece(enum_type->enumvalue(0).name(), true)) : DataPiece::NullData(); } DataPiece DefaultValueObjectWriter::CreateDefaultDataPieceForField( - const google::protobuf::Field& field, const TypeInfo* typeinfo) { + const google::protobuf::Field& field, const TypeInfo* typeinfo, bool use_ints_for_enums) { switch (field.kind()) { case google::protobuf::Field_Kind_TYPE_DOUBLE: { return DataPiece(ConvertTo<double>( @@ -496,7 +499,7 @@ DataPiece DefaultValueObjectWriter::CreateDefaultDataPieceForField( field.default_value(), &DataPiece::ToUint32, static_cast<uint32>(0))); } case google::protobuf::Field_Kind_TYPE_ENUM: { - return FindEnumDefault(field, typeinfo); + return FindEnumDefault(field, typeinfo, use_ints_for_enums); } default: { return DataPiece::NullData(); } } @@ -508,7 +511,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::StartObject( std::vector<string> path; root_.reset(CreateNewNode(string(name), &type_, OBJECT, DataPiece::NullData(), false, path, - suppress_empty_list_, preserve_proto_field_names_, + suppress_empty_list_, preserve_proto_field_names_, use_ints_for_enums_, field_scrub_callback_.get())); root_->PopulateChildren(typeinfo_); current_ = root_.get(); @@ -526,7 +529,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::StartObject( : nullptr), OBJECT, DataPiece::NullData(), false, child == nullptr ? current_->path() : child->path(), - suppress_empty_list_, preserve_proto_field_names_, + suppress_empty_list_, preserve_proto_field_names_, use_ints_for_enums_, field_scrub_callback_.get())); child = node.get(); current_->AddChild(node.release()); @@ -559,7 +562,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::StartList( std::vector<string> path; root_.reset(CreateNewNode(string(name), &type_, LIST, DataPiece::NullData(), false, path, suppress_empty_list_, - preserve_proto_field_names_, + preserve_proto_field_names_, use_ints_for_enums_, field_scrub_callback_.get())); current_ = root_.get(); return this; @@ -570,7 +573,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::StartList( std::unique_ptr<Node> node( CreateNewNode(string(name), nullptr, LIST, DataPiece::NullData(), false, child == nullptr ? current_->path() : child->path(), - suppress_empty_list_, preserve_proto_field_names_, + suppress_empty_list_, preserve_proto_field_names_, use_ints_for_enums_, field_scrub_callback_.get())); child = node.get(); current_->AddChild(node.release()); @@ -632,7 +635,7 @@ void DefaultValueObjectWriter::RenderDataPiece(StringPiece name, std::unique_ptr<Node> node( CreateNewNode(string(name), nullptr, PRIMITIVE, data, false, child == nullptr ? current_->path() : child->path(), - suppress_empty_list_, preserve_proto_field_names_, + suppress_empty_list_, preserve_proto_field_names_, use_ints_for_enums_, field_scrub_callback_.get())); current_->AddChild(node.release()); } else { diff --git a/src/google/protobuf/util/internal/default_value_objectwriter.h b/src/google/protobuf/util/internal/default_value_objectwriter.h index 02cf827a..6e71f9c8 100644 --- a/src/google/protobuf/util/internal/default_value_objectwriter.h +++ b/src/google/protobuf/util/internal/default_value_objectwriter.h @@ -128,6 +128,12 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter { preserve_proto_field_names_ = value; } + // If set to true, enums are rendered as ints from output when default values + // are written. + void set_print_enums_as_ints(bool value) { + use_ints_for_enums_ = value; + } + protected: enum NodeKind { PRIMITIVE = 0, @@ -147,7 +153,7 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter { Node(const string& name, const google::protobuf::Type* type, NodeKind kind, const DataPiece& data, bool is_placeholder, const std::vector<string>& path, bool suppress_empty_list, - bool preserve_proto_field_names, + bool preserve_proto_field_names, bool use_ints_for_enums, FieldScrubCallBack* field_scrub_callback); virtual ~Node() { for (int i = 0; i < children_.size(); ++i) { @@ -230,6 +236,9 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter { // Whether to preserve original proto field names bool preserve_proto_field_names_; + // Whether to always print enums as ints + bool use_ints_for_enums_; + // Pointer to function for determining whether a field needs to be scrubbed // or not. This callback is owned by the creator of this node. FieldScrubCallBack* field_scrub_callback_; @@ -253,11 +262,12 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter { const std::vector<string>& path, bool suppress_empty_list, bool preserve_proto_field_names, + bool use_ints_for_enums, FieldScrubCallBack* field_scrub_callback); // Creates a DataPiece containing the default value of the type of the field. static DataPiece CreateDefaultDataPieceForField( - const google::protobuf::Field& field, const TypeInfo* typeinfo); + const google::protobuf::Field& field, const TypeInfo* typeinfo, bool use_ints_for_enums); protected: // Returns a pointer to current Node in tree. @@ -279,7 +289,8 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter { // there is no default. For proto3, where we cannot specify an explicit // default, a zero value will always be returned. static DataPiece FindEnumDefault(const google::protobuf::Field& field, - const TypeInfo* typeinfo); + const TypeInfo* typeinfo, + bool use_ints_for_enums); // Type information for all the types used in the descriptor. Used to find // google::protobuf::Type of nested messages/enums. @@ -304,6 +315,9 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter { // Whether to preserve original proto field names bool preserve_proto_field_names_; + // Whether to always print enums as ints + bool use_ints_for_enums_; + // Unique Pointer to function for determining whether a field needs to be // scrubbed or not. FieldScrubCallBackPtr field_scrub_callback_; diff --git a/src/google/protobuf/util/json_format_proto3.proto b/src/google/protobuf/util/json_format_proto3.proto index 8a0441c8..cbc3f81f 100644 --- a/src/google/protobuf/util/json_format_proto3.proto +++ b/src/google/protobuf/util/json_format_proto3.proto @@ -181,3 +181,9 @@ message TestCustomJsonName { message TestExtensions { .protobuf_unittest.TestAllExtensions extensions = 1; } + +message TestEnumValue{ + EnumType enum_value1 = 1; + EnumType enum_value2 = 2; + EnumType enum_value3 = 3; +}
\ No newline at end of file diff --git a/src/google/protobuf/util/json_util.cc b/src/google/protobuf/util/json_util.cc index ea0cc2e4..f81a7a30 100644 --- a/src/google/protobuf/util/json_util.cc +++ b/src/google/protobuf/util/json_util.cc @@ -97,6 +97,8 @@ util::Status BinaryToJsonStream(TypeResolver* resolver, resolver, type, &json_writer); default_value_writer.set_preserve_proto_field_names( options.preserve_proto_field_names); + default_value_writer.set_print_enums_as_ints( + options.always_print_enums_as_ints); return proto_source.WriteTo(&default_value_writer); } else { return proto_source.WriteTo(&json_writer); diff --git a/src/google/protobuf/util/json_util_test.cc b/src/google/protobuf/util/json_util_test.cc index dbd262f6..ed9092df 100644 --- a/src/google/protobuf/util/json_util_test.cc +++ b/src/google/protobuf/util/json_util_test.cc @@ -54,6 +54,7 @@ using proto3::BAR; using proto3::TestMessage; using proto3::TestMap; using proto3::TestOneof; +using proto3::TestEnumValue; static const char kTypeUrlPrefix[] = "type.googleapis.com"; @@ -217,6 +218,29 @@ TEST_F(JsonUtilTest, TestAlwaysPrintEnumsAsInts) { EXPECT_EQ(proto3::BAR, parsed.repeated_enum_value(1)); } +TEST_F(JsonUtilTest, TestPrintEnumsAsIntsWithDefaultValue) { + TestEnumValue orig; + //orig.set_enum_value1(proto3::FOO) + orig.set_enum_value2(proto3::FOO); + orig.set_enum_value3(proto3::BAR); + + JsonPrintOptions print_options; + print_options.always_print_enums_as_ints = true; + print_options.always_print_primitive_fields = true; + + string expected_json = "{\"enumValue1\":0,\"enumValue2\":0,\"enumValue3\":1}"; + EXPECT_EQ(expected_json, ToJson(orig, print_options)); + + TestEnumValue parsed; + JsonParseOptions parse_options; + ASSERT_TRUE(FromJson(expected_json, &parsed, parse_options)); + + EXPECT_EQ(proto3::FOO, parsed.enum_value1()); + EXPECT_EQ(proto3::FOO, parsed.enum_value2()); + EXPECT_EQ(proto3::BAR, parsed.enum_value3()); + +} + TEST_F(JsonUtilTest, ParseMessage) { // Some random message but good enough to verify that the parsing warpper // functions are working properly. diff --git a/third_party/googletest b/third_party/googletest new file mode 160000 +Subproject c3bb0ee2a63279a803aaad956b9b26d74bf9e6e diff --git a/update_file_lists.sh b/update_file_lists.sh index 15291990..a064d657 100755 --- a/update_file_lists.sh +++ b/update_file_lists.sh @@ -24,7 +24,7 @@ get_header_files() { } get_source_files() { - get_variable_value $@ | grep "cc$" + get_variable_value $@ | grep "cc$\|inc$" } get_proto_files_blacklisted() { @@ -55,6 +55,7 @@ PUBLIC_HEADERS=$(sort_files $GZHEADERS $HEADERS) LIBPROTOBUF_LITE_SOURCES=$(get_source_files $MAKEFILE libprotobuf_lite_la_SOURCES) LIBPROTOBUF_SOURCES=$(get_source_files $MAKEFILE libprotobuf_la_SOURCES) LIBPROTOC_SOURCES=$(get_source_files $MAKEFILE libprotoc_la_SOURCES) +LIBPROTOC_HEADERS=$(get_header_files $MAKEFILE libprotoc_la_SOURCES) LITE_PROTOS=$(get_proto_files $MAKEFILE protoc_lite_outputs) PROTOS=$(get_proto_files $MAKEFILE protoc_outputs) PROTOS_BLACKLISTED=$(get_proto_files_blacklisted $MAKEFILE protoc_outputs) @@ -116,6 +117,7 @@ CMAKE_PREFIX="\${protobuf_source_dir}/src/" set_cmake_value $CMAKE_DIR/libprotobuf-lite.cmake libprotobuf_lite_files $CMAKE_PREFIX $LIBPROTOBUF_LITE_SOURCES set_cmake_value $CMAKE_DIR/libprotobuf.cmake libprotobuf_files $CMAKE_PREFIX $LIBPROTOBUF_SOURCES set_cmake_value $CMAKE_DIR/libprotoc.cmake libprotoc_files $CMAKE_PREFIX $LIBPROTOC_SOURCES +set_cmake_value $CMAKE_DIR/libprotoc.cmake libprotoc_headers $CMAKE_PREFIX $LIBPROTOC_HEADERS set_cmake_value $CMAKE_DIR/tests.cmake lite_test_protos "" $LITE_PROTOS set_cmake_value $CMAKE_DIR/tests.cmake tests_protos "" $PROTOS_BLACKLISTED set_cmake_value $CMAKE_DIR/tests.cmake common_test_files $CMAKE_PREFIX $COMMON_TEST_SOURCES |