diff options
Diffstat (limited to 'src')
314 files changed, 15832 insertions, 24822 deletions
diff --git a/src/Makefile.am b/src/Makefile.am index aa945d3e..b8648049 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -56,28 +56,12 @@ clean-local: CLEANFILES = $(protoc_outputs) unittest_proto_middleman \ testzip.jar testzip.list testzip.proto testzip.zip \ - no_warning_test.cc \ - google/protobuf/compiler/js/well_known_types_embed.cc \ - js_embed$(EXEEXT) + no_warning_test.cc MAINTAINERCLEANFILES = \ Makefile.in nobase_include_HEADERS = \ - google/protobuf/stubs/atomic_sequence_num.h \ - google/protobuf/stubs/atomicops.h \ - google/protobuf/stubs/atomicops_internals_power.h \ - google/protobuf/stubs/atomicops_internals_ppc_gcc.h \ - google/protobuf/stubs/atomicops_internals_arm64_gcc.h \ - google/protobuf/stubs/atomicops_internals_arm_gcc.h \ - google/protobuf/stubs/atomicops_internals_arm_qnx.h \ - google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h \ - google/protobuf/stubs/atomicops_internals_generic_gcc.h \ - google/protobuf/stubs/atomicops_internals_mips_gcc.h \ - google/protobuf/stubs/atomicops_internals_solaris.h \ - google/protobuf/stubs/atomicops_internals_tsan.h \ - google/protobuf/stubs/atomicops_internals_x86_gcc.h \ - google/protobuf/stubs/atomicops_internals_x86_msvc.h \ google/protobuf/stubs/callback.h \ google/protobuf/stubs/bytestream.h \ google/protobuf/stubs/casts.h \ @@ -90,14 +74,11 @@ nobase_include_HEADERS = \ google/protobuf/stubs/once.h \ google/protobuf/stubs/platform_macros.h \ google/protobuf/stubs/port.h \ - google/protobuf/stubs/scoped_ptr.h \ - google/protobuf/stubs/shared_ptr.h \ google/protobuf/stubs/singleton.h \ google/protobuf/stubs/status.h \ google/protobuf/stubs/stl_util.h \ 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 \ @@ -119,6 +100,7 @@ nobase_include_HEADERS = \ google/protobuf/generated_message_util.h \ google/protobuf/has_bits.h \ google/protobuf/implicit_weak_message.h \ + google/protobuf/inlined_string_field.h \ google/protobuf/map_entry.h \ google/protobuf/map_entry_lite.h \ google/protobuf/map_field.h \ @@ -163,7 +145,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 \ @@ -189,8 +170,6 @@ libprotobuf_lite_la_LDFLAGS += -Wl,--version-script=$(srcdir)/libprotobuf-lite.m EXTRA_libprotobuf_lite_la_DEPENDENCIES = libprotobuf-lite.map endif libprotobuf_lite_la_SOURCES = \ - google/protobuf/stubs/atomicops_internals_x86_gcc.cc \ - google/protobuf/stubs/atomicops_internals_x86_msvc.cc \ google/protobuf/stubs/bytestream.cc \ google/protobuf/stubs/bytestream.h \ google/protobuf/stubs/common.cc \ @@ -201,8 +180,6 @@ libprotobuf_lite_la_SOURCES = \ google/protobuf/stubs/io_win32.h \ google/protobuf/stubs/map_util.h \ google/protobuf/stubs/mathutil.h \ - google/protobuf/stubs/once.cc \ - google/protobuf/stubs/shared_ptr.h \ google/protobuf/stubs/status.cc \ google/protobuf/stubs/status.h \ google/protobuf/stubs/status_macros.h \ @@ -429,29 +406,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 \ @@ -515,22 +469,6 @@ bin_PROGRAMS = protoc protoc_LDADD = $(PTHREAD_LIBS) libprotobuf.la libprotoc.la protoc_SOURCES = google/protobuf/compiler/main.cc -# The special JS code for the well-known types is linked into the compiler via -# well_known_types_embed.cc, which is generated from .js source files. We have -# to build the js_embed binary using $(CXX_FOR_BUILD) so that it is executable -# on the build machine in a cross-compilation setup. -js_embed$(EXEEXT): $(srcdir)/google/protobuf/compiler/js/embed.cc - $(CXX_FOR_BUILD) -o $@ $< -js_well_known_types_sources = \ - google/protobuf/compiler/js/well_known_types/any.js \ - google/protobuf/compiler/js/well_known_types/struct.js \ - google/protobuf/compiler/js/well_known_types/timestamp.js -# We have to cd to $(srcdir) so that out-of-tree builds work properly. -google/protobuf/compiler/js/well_known_types_embed.cc: js_embed$(EXEEXT) $(js_well_known_types_sources) - mkdir -p `dirname $@` && \ - oldpwd=`pwd` && cd $(srcdir) && \ - $$oldpwd/js_embed$(EXEEXT) $(js_well_known_types_sources) > $$oldpwd/$@ - # Tests ============================================================== protoc_inputs = \ @@ -609,7 +547,6 @@ EXTRA_DIST = \ google/protobuf/package_info.h \ google/protobuf/io/package_info.h \ google/protobuf/util/package_info.h \ - google/protobuf/compiler/js/embed.cc \ google/protobuf/compiler/ruby/ruby_generated_code.proto \ google/protobuf/compiler/ruby/ruby_generated_code_pb.rb \ google/protobuf/compiler/package_info.h \ @@ -722,8 +659,6 @@ protoc_outputs = \ google/protobuf/util/message_differencer_unittest.pb.cc \ google/protobuf/util/message_differencer_unittest.pb.h -BUILT_SOURCES = $(protoc_outputs) google/protobuf/compiler/js/well_known_types_embed.cc - if USE_EXTERNAL_PROTOC unittest_proto_middleman: $(protoc_inputs) @@ -751,20 +686,25 @@ COMMON_TEST_SOURCES = \ google/protobuf/map_test_util_impl.h \ google/protobuf/test_util.cc \ google/protobuf/test_util.h \ + google/protobuf/test_util.inc \ google/protobuf/testing/googletest.cc \ google/protobuf/testing/googletest.h \ 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. @@ -774,7 +714,6 @@ protobuf_test_SOURCES = \ google/protobuf/stubs/common_unittest.cc \ google/protobuf/stubs/int128_unittest.cc \ google/protobuf/stubs/io_win32_unittest.cc \ - google/protobuf/stubs/once_unittest.cc \ google/protobuf/stubs/statusor_test.cc \ google/protobuf/stubs/status_test.cc \ google/protobuf/stubs/stringpiece_unittest.cc \ @@ -783,7 +722,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 \ @@ -796,10 +734,11 @@ protobuf_test_SOURCES = \ google/protobuf/map_field_test.cc \ google/protobuf/map_test.cc \ google/protobuf/message_unittest.cc \ + google/protobuf/message_unittest.inc \ google/protobuf/no_field_presence_test.cc \ google/protobuf/preserve_unknown_enum_test.cc \ - google/protobuf/proto3_arena_unittest.cc \ google/protobuf/proto3_arena_lite_unittest.cc \ + google/protobuf/proto3_arena_unittest.cc \ google/protobuf/proto3_lite_unittest.cc \ google/protobuf/reflection_ops_unittest.cc \ google/protobuf/repeated_field_reflection_unittest.cc \ @@ -823,6 +762,7 @@ protobuf_test_SOURCES = \ google/protobuf/compiler/cpp/cpp_move_unittest.cc \ google/protobuf/compiler/cpp/cpp_unittest.h \ google/protobuf/compiler/cpp/cpp_unittest.cc \ + google/protobuf/compiler/cpp/cpp_unittest.inc \ google/protobuf/compiler/cpp/cpp_plugin_unittest.cc \ google/protobuf/compiler/cpp/metadata_test.cc \ google/protobuf/compiler/java/java_plugin_unittest.cc \ @@ -846,24 +786,24 @@ protobuf_test_SOURCES = \ google/protobuf/util/time_util_test.cc \ google/protobuf/util/type_resolver_util_test.cc \ $(COMMON_TEST_SOURCES) - - nodist_protobuf_test_SOURCES = $(protoc_outputs) +$(am_protobuf_test_OBJECTS): unittest_proto_middleman # Run cpp_unittest again with PROTOBUF_TEST_NO_DESCRIPTORS defined. protobuf_lazy_descriptor_test_LDADD = $(PTHREAD_LIBS) libprotobuf.la \ libprotoc.la \ - ../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 = \ google/protobuf/compiler/cpp/cpp_unittest.cc \ $(COMMON_TEST_SOURCES) nodist_protobuf_lazy_descriptor_test_SOURCES = $(protoc_outputs) +$(am_protobuf_lazy_descriptor_test_OBJECTS): unittest_proto_middleman COMMON_LITE_TEST_SOURCES = \ google/protobuf/arena_test_util.cc \ @@ -877,37 +817,39 @@ 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 \ $(COMMON_LITE_TEST_SOURCES) nodist_protobuf_lite_test_SOURCES = $(protoc_lite_outputs) +$(am_protobuf_lite_test_OBJECTS): unittest_proto_middleman # lite_arena_unittest depends on gtest because teboring@ found that without # gtest when building the test internally our memory sanitizer doesn't detect # memory leaks (don't know why). protobuf_lite_arena_test_LDADD = $(PTHREAD_LIBS) libprotobuf-lite.la \ - ../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 \ $(COMMON_LITE_TEST_SOURCES) nodist_protobuf_lite_arena_test_SOURCES = $(protoc_lite_outputs) +$(am_protobuf_lite_arena_test_OBJECTS): unittest_proto_middleman # Test plugin binary. test_plugin_LDADD = $(PTHREAD_LIBS) libprotobuf.la libprotoc.la \ - ../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 \ @@ -928,9 +870,7 @@ endif no_warning_test.cc: echo "// Generated from Makefile.am" > no_warning_test.cc for FILE in $(nobase_include_HEADERS); do \ - if ! echo $${FILE} | grep "atomicops"; then \ - echo "#include <$${FILE}>" >> no_warning_test.cc; \ - fi \ + echo "#include <$${FILE}>" >> no_warning_test.cc; \ done echo "int main(int, char**) { return 0; }" >> no_warning_test.cc diff --git a/src/README.md b/src/README.md index c9362ee2..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,12 +184,22 @@ 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 library. +Protobuf and its dependencies can be installed directly by using `vcpkg`: + + >vcpkg install protobuf protobuf:x64-windows + +If zlib support is desired, you'll also need to install the zlib feature: + + >vcpkg install protobuf[zlib] protobuf[zlib]:x64-windows + +See https://github.com/Microsoft/vcpkg for more information. + To build from source using Microsoft Visual C++, see [cmake/README.md](../cmake/README.md). To build from source using Cygwin or MinGW, follow the Unix installation diff --git a/src/google/protobuf/any.cc b/src/google/protobuf/any.cc index 83edba57..b94529e6 100644 --- a/src/google/protobuf/any.cc +++ b/src/google/protobuf/any.cc @@ -32,6 +32,7 @@ #include <google/protobuf/generated_message_util.h> + namespace google { namespace protobuf { namespace internal { @@ -84,15 +85,23 @@ bool AnyMetadata::InternalIs(const Descriptor* descriptor) const { return full_name == descriptor->full_name(); } -bool ParseAnyTypeUrl(const string& type_url, string* full_type_name) { +bool ParseAnyTypeUrl(const string& type_url, string* url_prefix, + string* full_type_name) { size_t pos = type_url.find_last_of("/"); if (pos == string::npos || pos + 1 == type_url.size()) { return false; } + if (url_prefix) { + *url_prefix = type_url.substr(0, pos + 1); + } *full_type_name = type_url.substr(pos + 1); return true; } +bool ParseAnyTypeUrl(const string& type_url, string* full_type_name) { + return ParseAnyTypeUrl(type_url, NULL, full_type_name); +} + bool GetAnyFieldDescriptors(const Message& message, const FieldDescriptor** type_url_field, diff --git a/src/google/protobuf/any.h b/src/google/protobuf/any.h index c2c27ec3..a34e5f8e 100644 --- a/src/google/protobuf/any.h +++ b/src/google/protobuf/any.h @@ -92,8 +92,19 @@ extern const char kTypeGoogleProdComPrefix[]; // "type.googleprod.com/". // "type.googleapis.com/rpc.QueryOrigin" will return "rpc.QueryOrigin" in // *full_type_name. Returns false if the type_url does not have a "/" // in the type url separating the full type name. +// +// NOTE: this function is available publicly as: +// google::protobuf::Any() // static method on the generated message type. bool ParseAnyTypeUrl(const string& type_url, string* full_type_name); +// Get the proto type name and prefix from Any::type_url value. For example, +// passing "type.googleapis.com/rpc.QueryOrigin" will return +// "type.googleapis.com/" in *url_prefix and "rpc.QueryOrigin" in +// *full_type_name. Returns false if the type_url does not have a "/" in the +// type url separating the full type name. +bool ParseAnyTypeUrl(const string& type_url, string* url_prefix, + string* full_type_name); + // See if message is of type google.protobuf.Any, if so, return the descriptors // for "type_url" and "value" fields. bool GetAnyFieldDescriptors(const Message& message, diff --git a/src/google/protobuf/any.pb.cc b/src/google/protobuf/any.pb.cc index 4335e467..d0fc2905 100644 --- a/src/google/protobuf/any.pb.cc +++ b/src/google/protobuf/any.pb.cc @@ -7,7 +7,6 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> -#include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> @@ -19,6 +18,7 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + namespace google { namespace protobuf { class AnyDefaultTypeInternal { @@ -29,14 +29,9 @@ class AnyDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2fany_2eproto { -void InitDefaultsAnyImpl() { +static void InitDefaultsAny() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_Any_default_instance_; new (ptr) ::google::protobuf::Any(); @@ -45,9 +40,11 @@ void InitDefaultsAnyImpl() { ::google::protobuf::Any::InitAsDefaultInstance(); } -void InitDefaultsAny() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsAnyImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Any = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsAny}, {}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_Any.base); } ::google::protobuf::Metadata file_level_metadata[1]; @@ -69,17 +66,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Any_default_instance_), }; -void protobuf_AssignDescriptors() { +static void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/any.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/any.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } -void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); +static void protobuf_AssignDescriptorsOnce() { + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -88,7 +84,7 @@ void protobuf_RegisterTypes(const ::std::string&) { ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1); } -void AddDescriptorsImpl() { +static void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n\031google/protobuf/any.proto\022\017google.prot" @@ -105,8 +101,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -134,6 +130,11 @@ void Any::PackFrom(const ::google::protobuf::Message& message, bool Any::UnpackTo(::google::protobuf::Message* message) const { return _any_metadata_.UnpackTo(message); } +bool Any::ParseAnyTypeUrl(const string& type_url, + string* full_type_name) { + return ::google::protobuf::internal::ParseAnyTypeUrl(type_url, + full_type_name); +} #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Any::kTypeUrlFieldNumber; @@ -142,16 +143,14 @@ const int Any::kValueFieldNumber; Any::Any() : ::google::protobuf::Message(), _internal_metadata_(NULL), _any_metadata_(&type_url_, &value_) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAny(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fany_2eproto::scc_info_Any.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Any) } Any::Any(const Any& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _cached_size_(0), _any_metadata_(&type_url_, &value_) { _internal_metadata_.MergeFrom(from._internal_metadata_); type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -168,7 +167,6 @@ Any::Any(const Any& from) void Any::SharedCtor() { type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - _cached_size_ = 0; } Any::~Any() { @@ -182,9 +180,7 @@ void Any::SharedDtor() { } void Any::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Any::descriptor() { ::protobuf_google_2fprotobuf_2fany_2eproto::protobuf_AssignDescriptorsOnce(); @@ -192,7 +188,7 @@ const ::google::protobuf::Descriptor* Any::descriptor() { } const Any& Any::default_instance() { - ::protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAny(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fany_2eproto::scc_info_Any.base); return *internal_default_instance(); } @@ -214,7 +210,7 @@ bool Any::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Any) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -352,9 +348,7 @@ size_t Any::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -414,10 +408,11 @@ void Any::Swap(Any* other) { } void Any::InternalSwap(Any* other) { using std::swap; - type_url_.Swap(&other->type_url_); - value_.Swap(&other->value_); + type_url_.Swap(&other->type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + value_.Swap(&other->value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Any::GetMetadata() const { @@ -431,7 +426,7 @@ void Any::InternalSwap(Any* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Any* Arena::Create< ::google::protobuf::Any >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Any* Arena::CreateMaybeMessage< ::google::protobuf::Any >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::Any >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/any.pb.h b/src/google/protobuf/any.pb.h index 14c21a8f..bc537999 100644 --- a/src/google/protobuf/any.pb.h +++ b/src/google/protobuf/any.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/any.proto -#ifndef PROTOBUF_google_2fprotobuf_2fany_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2fany_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto #include <string> @@ -24,6 +24,7 @@ #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> +#include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export @@ -31,6 +32,7 @@ #include <google/protobuf/unknown_field_set.h> #include <google/protobuf/any.h> // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fany_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2fany_2eproto { // Internal implementation detail -- do not use these members. @@ -43,11 +45,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsAnyImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsAny(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsAny(); -} } // namespace protobuf_google_2fprotobuf_2fany_2eproto namespace google { namespace protobuf { @@ -58,7 +55,7 @@ LIBPROTOBUF_EXPORT extern AnyDefaultTypeInternal _Any_default_instance_; } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Any* Arena::Create< ::google::protobuf::Any>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Any* Arena::CreateMaybeMessage<::google::protobuf::Any>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -100,7 +97,7 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in return reinterpret_cast<const Any*>( &_Any_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; // implements Any ----------------------------------------------- @@ -112,6 +109,8 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in template<typename T> bool Is() const { return _any_metadata_.Is<T>(); } + static bool ParseAnyTypeUrl(const string& type_url, + string* full_type_name); void Swap(Any* other); friend void swap(Any& a, Any& b) { @@ -120,32 +119,33 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in // implements Message ---------------------------------------------- - inline Any* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<Any>(NULL); + inline Any* New() const final { + return CreateMaybeMessage<Any>(NULL); } - Any* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<Any>(arena); + Any* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<Any>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Any& from); void MergeFrom(const Any& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Any* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -156,7 +156,7 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -196,10 +196,9 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr type_url_; ::google::protobuf::internal::ArenaStringPtr value_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::internal::AnyMetadata _any_metadata_; friend struct ::protobuf_google_2fprotobuf_2fany_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAnyImpl(); }; // =================================================================== @@ -329,4 +328,4 @@ inline void Any::set_allocated_value(::std::string* value) { // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2fany_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto diff --git a/src/google/protobuf/api.pb.cc b/src/google/protobuf/api.pb.cc index b0354551..6ad9f48d 100644 --- a/src/google/protobuf/api.pb.cc +++ b/src/google/protobuf/api.pb.cc @@ -7,7 +7,6 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> -#include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> @@ -19,6 +18,17 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + +namespace protobuf_google_2fprotobuf_2fapi_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fapi_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Mixin; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fapi_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Method; +} // namespace protobuf_google_2fprotobuf_2fapi_2eproto +namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SourceContext; +} // namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto +namespace protobuf_google_2fprotobuf_2ftype_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Option; +} // namespace protobuf_google_2fprotobuf_2ftype_2eproto namespace google { namespace protobuf { class ApiDefaultTypeInternal { @@ -39,18 +49,9 @@ class MixinDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2fapi_2eproto { -void InitDefaultsApiImpl() { +static void InitDefaultsApi() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethod(); - protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption(); - protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext(); - protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixin(); { void* ptr = &::google::protobuf::_Api_default_instance_; new (ptr) ::google::protobuf::Api(); @@ -59,20 +60,16 @@ void InitDefaultsApiImpl() { ::google::protobuf::Api::InitAsDefaultInstance(); } -void InitDefaultsApi() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsApiImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<4> scc_info_Api = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 4, InitDefaultsApi}, { + &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Method.base, + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base, + &protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base, + &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Mixin.base,}}; -void InitDefaultsMethodImpl() { +static void InitDefaultsMethod() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption(); { void* ptr = &::google::protobuf::_Method_default_instance_; new (ptr) ::google::protobuf::Method(); @@ -81,19 +78,13 @@ void InitDefaultsMethodImpl() { ::google::protobuf::Method::InitAsDefaultInstance(); } -void InitDefaultsMethod() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMethodImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_Method = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethod}, { + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base,}}; -void InitDefaultsMixinImpl() { +static void InitDefaultsMixin() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_Mixin_default_instance_; new (ptr) ::google::protobuf::Mixin(); @@ -102,9 +93,13 @@ void InitDefaultsMixinImpl() { ::google::protobuf::Mixin::InitAsDefaultInstance(); } -void InitDefaultsMixin() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMixinImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Mixin = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsMixin}, {}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_Api.base); + ::google::protobuf::internal::InitSCC(&scc_info_Method.base); + ::google::protobuf::internal::InitSCC(&scc_info_Mixin.base); } ::google::protobuf::Metadata file_level_metadata[3]; @@ -154,17 +149,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Mixin_default_instance_), }; -void protobuf_AssignDescriptors() { +static void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/api.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/api.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } -void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); +static void protobuf_AssignDescriptorsOnce() { + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -173,7 +167,7 @@ void protobuf_RegisterTypes(const ::std::string&) { ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 3); } -void AddDescriptorsImpl() { +static void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n\031google/protobuf/api.proto\022\017google.prot" @@ -205,8 +199,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -245,9 +239,8 @@ const int Api::kSyntaxFieldNumber; Api::Api() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsApi(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Api.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Api) } @@ -256,8 +249,7 @@ Api::Api(const Api& from) _internal_metadata_(NULL), methods_(from.methods_), options_(from.options_), - mixins_(from.mixins_), - _cached_size_(0) { + mixins_(from.mixins_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { @@ -282,7 +274,6 @@ void Api::SharedCtor() { ::memset(&source_context_, 0, static_cast<size_t>( reinterpret_cast<char*>(&syntax_) - reinterpret_cast<char*>(&source_context_)) + sizeof(syntax_)); - _cached_size_ = 0; } Api::~Api() { @@ -297,9 +288,7 @@ void Api::SharedDtor() { } void Api::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Api::descriptor() { ::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce(); @@ -307,7 +296,7 @@ const ::google::protobuf::Descriptor* Api::descriptor() { } const Api& Api::default_instance() { - ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsApi(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Api.base); return *internal_default_instance(); } @@ -337,7 +326,7 @@ bool Api::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Api) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -503,7 +492,7 @@ void Api::SerializeWithCachedSizes( // .google.protobuf.SourceContext source_context = 5; if (this->has_source_context()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 5, *source_context_, output); + 5, this->_internal_source_context(), output); } // repeated .google.protobuf.Mixin mixins = 6; @@ -577,7 +566,7 @@ void Api::SerializeWithCachedSizes( if (this->has_source_context()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 5, *source_context_, deterministic, target); + 5, this->_internal_source_context(), deterministic, target); } // repeated .google.protobuf.Mixin mixins = 6; @@ -672,9 +661,7 @@ size_t Api::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -746,12 +733,13 @@ void Api::InternalSwap(Api* other) { CastToBase(&methods_)->InternalSwap(CastToBase(&other->methods_)); CastToBase(&options_)->InternalSwap(CastToBase(&other->options_)); CastToBase(&mixins_)->InternalSwap(CastToBase(&other->mixins_)); - name_.Swap(&other->name_); - version_.Swap(&other->version_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + version_.Swap(&other->version_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(source_context_, other->source_context_); swap(syntax_, other->syntax_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Api::GetMetadata() const { @@ -779,17 +767,15 @@ const int Method::kSyntaxFieldNumber; Method::Method() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethod(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Method.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Method) } Method::Method(const Method& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - options_(from.options_), - _cached_size_(0) { + options_(from.options_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { @@ -816,7 +802,6 @@ void Method::SharedCtor() { ::memset(&request_streaming_, 0, static_cast<size_t>( reinterpret_cast<char*>(&syntax_) - reinterpret_cast<char*>(&request_streaming_)) + sizeof(syntax_)); - _cached_size_ = 0; } Method::~Method() { @@ -831,9 +816,7 @@ void Method::SharedDtor() { } void Method::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Method::descriptor() { ::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce(); @@ -841,7 +824,7 @@ const ::google::protobuf::Descriptor* Method::descriptor() { } const Method& Method::default_instance() { - ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethod(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Method.base); return *internal_default_instance(); } @@ -868,7 +851,7 @@ bool Method::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Method) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1193,9 +1176,7 @@ size_t Method::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1270,14 +1251,16 @@ void Method::Swap(Method* other) { void Method::InternalSwap(Method* other) { using std::swap; CastToBase(&options_)->InternalSwap(CastToBase(&other->options_)); - name_.Swap(&other->name_); - request_type_url_.Swap(&other->request_type_url_); - response_type_url_.Swap(&other->response_type_url_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + request_type_url_.Swap(&other->request_type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + response_type_url_.Swap(&other->response_type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(request_streaming_, other->request_streaming_); swap(response_streaming_, other->response_streaming_); swap(syntax_, other->syntax_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Method::GetMetadata() const { @@ -1297,16 +1280,14 @@ const int Mixin::kRootFieldNumber; Mixin::Mixin() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixin(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Mixin.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Mixin) } Mixin::Mixin(const Mixin& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { @@ -1322,7 +1303,6 @@ Mixin::Mixin(const Mixin& from) void Mixin::SharedCtor() { name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); root_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - _cached_size_ = 0; } Mixin::~Mixin() { @@ -1336,9 +1316,7 @@ void Mixin::SharedDtor() { } void Mixin::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Mixin::descriptor() { ::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1346,7 +1324,7 @@ const ::google::protobuf::Descriptor* Mixin::descriptor() { } const Mixin& Mixin::default_instance() { - ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixin(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Mixin.base); return *internal_default_instance(); } @@ -1368,7 +1346,7 @@ bool Mixin::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Mixin) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1518,9 +1496,7 @@ size_t Mixin::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1580,10 +1556,11 @@ void Mixin::Swap(Mixin* other) { } void Mixin::InternalSwap(Mixin* other) { using std::swap; - name_.Swap(&other->name_); - root_.Swap(&other->root_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + root_.Swap(&other->root_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Mixin::GetMetadata() const { @@ -1597,13 +1574,13 @@ void Mixin::InternalSwap(Mixin* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Api* Arena::Create< ::google::protobuf::Api >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Api* Arena::CreateMaybeMessage< ::google::protobuf::Api >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::Api >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Method* Arena::Create< ::google::protobuf::Method >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Method* Arena::CreateMaybeMessage< ::google::protobuf::Method >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::Method >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Mixin* Arena::Create< ::google::protobuf::Mixin >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Mixin* Arena::CreateMaybeMessage< ::google::protobuf::Mixin >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::Mixin >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/api.pb.h b/src/google/protobuf/api.pb.h index 648aa308..5a720cce 100644 --- a/src/google/protobuf/api.pb.h +++ b/src/google/protobuf/api.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/api.proto -#ifndef PROTOBUF_google_2fprotobuf_2fapi_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2fapi_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto #include <string> @@ -24,6 +24,7 @@ #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> +#include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export @@ -32,6 +33,7 @@ #include <google/protobuf/source_context.pb.h> #include <google/protobuf/type.pb.h> // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fapi_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2fapi_2eproto { // Internal implementation detail -- do not use these members. @@ -44,17 +46,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsApiImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsApi(); -void LIBPROTOBUF_EXPORT InitDefaultsMethodImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsMethod(); -void LIBPROTOBUF_EXPORT InitDefaultsMixinImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsMixin(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsApi(); - InitDefaultsMethod(); - InitDefaultsMixin(); -} } // namespace protobuf_google_2fprotobuf_2fapi_2eproto namespace google { namespace protobuf { @@ -71,9 +62,9 @@ LIBPROTOBUF_EXPORT extern MixinDefaultTypeInternal _Mixin_default_instance_; } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Api* Arena::Create< ::google::protobuf::Api>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Method* Arena::Create< ::google::protobuf::Method>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Mixin* Arena::Create< ::google::protobuf::Mixin>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Api* Arena::CreateMaybeMessage<::google::protobuf::Api>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Method* Arena::CreateMaybeMessage<::google::protobuf::Method>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Mixin* Arena::CreateMaybeMessage<::google::protobuf::Mixin>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -115,7 +106,7 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in return reinterpret_cast<const Api*>( &_Api_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void Swap(Api* other); @@ -125,32 +116,33 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in // implements Message ---------------------------------------------- - inline Api* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<Api>(NULL); + inline Api* New() const final { + return CreateMaybeMessage<Api>(NULL); } - Api* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<Api>(arena); + Api* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<Api>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Api& from); void MergeFrom(const Api& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Api* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -161,7 +153,7 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -235,6 +227,9 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in bool has_source_context() const; void clear_source_context(); static const int kSourceContextFieldNumber = 5; + private: + const ::google::protobuf::SourceContext& _internal_source_context() const; + public: const ::google::protobuf::SourceContext& source_context() const; ::google::protobuf::SourceContext* release_source_context(); ::google::protobuf::SourceContext* mutable_source_context(); @@ -257,9 +252,8 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in ::google::protobuf::internal::ArenaStringPtr version_; ::google::protobuf::SourceContext* source_context_; int syntax_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsApiImpl(); }; // ------------------------------------------------------------------- @@ -297,7 +291,7 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc return reinterpret_cast<const Method*>( &_Method_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 1; void Swap(Method* other); @@ -307,32 +301,33 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc // implements Message ---------------------------------------------- - inline Method* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<Method>(NULL); + inline Method* New() const final { + return CreateMaybeMessage<Method>(NULL); } - Method* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<Method>(arena); + Method* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<Method>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Method& from); void MergeFrom(const Method& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Method* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -343,7 +338,7 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -432,9 +427,8 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc bool request_streaming_; bool response_streaming_; int syntax_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethodImpl(); }; // ------------------------------------------------------------------- @@ -472,7 +466,7 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_ return reinterpret_cast<const Mixin*>( &_Mixin_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 2; void Swap(Mixin* other); @@ -482,32 +476,33 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_ // implements Message ---------------------------------------------- - inline Mixin* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<Mixin>(NULL); + inline Mixin* New() const final { + return CreateMaybeMessage<Mixin>(NULL); } - Mixin* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<Mixin>(arena); + Mixin* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<Mixin>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Mixin& from); void MergeFrom(const Mixin& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Mixin* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -518,7 +513,7 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_ } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -558,9 +553,8 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_ ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::internal::ArenaStringPtr root_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixinImpl(); }; // =================================================================== @@ -740,6 +734,9 @@ inline void Api::set_allocated_version(::std::string* version) { inline bool Api::has_source_context() const { return this != internal_default_instance() && source_context_ != NULL; } +inline const ::google::protobuf::SourceContext& Api::_internal_source_context() const { + return *source_context_; +} inline const ::google::protobuf::SourceContext& Api::source_context() const { const ::google::protobuf::SourceContext* p = source_context_; // @@protoc_insertion_point(field_get:google.protobuf.Api.source_context) @@ -756,8 +753,8 @@ inline ::google::protobuf::SourceContext* Api::release_source_context() { inline ::google::protobuf::SourceContext* Api::mutable_source_context() { if (source_context_ == NULL) { - source_context_ = ::google::protobuf::Arena::Create< ::google::protobuf::SourceContext >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::SourceContext>(GetArenaNoVirtual()); + source_context_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.Api.source_context) return source_context_; @@ -1182,4 +1179,4 @@ inline void Mixin::set_allocated_root(::std::string* root) { // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2fapi_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto diff --git a/src/google/protobuf/arena.cc b/src/google/protobuf/arena.cc index e53d7219..c117c9e5 100755 --- a/src/google/protobuf/arena.cc +++ b/src/google/protobuf/arena.cc @@ -48,7 +48,7 @@ namespace protobuf { namespace internal { -google::protobuf::internal::SequenceNumber ArenaImpl::lifecycle_id_generator_; +std::atomic<int64> ArenaImpl::lifecycle_id_generator_; #if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL) ArenaImpl::ThreadCache& ArenaImpl::thread_cache() { static internal::ThreadLocalStorage<ThreadCache>* thread_cache_ = @@ -65,9 +65,10 @@ GOOGLE_THREAD_LOCAL ArenaImpl::ThreadCache ArenaImpl::thread_cache_ = {-1, NULL} #endif void ArenaImpl::Init() { - lifecycle_id_ = lifecycle_id_generator_.GetNext(); - google::protobuf::internal::NoBarrier_Store(&hint_, 0); - google::protobuf::internal::NoBarrier_Store(&threads_, 0); + lifecycle_id_ = + lifecycle_id_generator_.fetch_add(1, std::memory_order_relaxed); + hint_.store(nullptr, std::memory_order_relaxed); + threads_.store(nullptr, std::memory_order_relaxed); if (initial_block_) { // Thread which calls Init() owns the first block. This allows the @@ -77,13 +78,12 @@ void ArenaImpl::Init() { SerialArena* serial = SerialArena::New(initial_block_, &thread_cache(), this); serial->set_next(NULL); - google::protobuf::internal::NoBarrier_Store(&threads_, - reinterpret_cast<google::protobuf::internal::AtomicWord>(serial)); - google::protobuf::internal::NoBarrier_Store(&space_allocated_, - options_.initial_block_size); + threads_.store(serial, std::memory_order_relaxed); + space_allocated_.store(options_.initial_block_size, + std::memory_order_relaxed); CacheSerialArena(serial); } else { - google::protobuf::internal::NoBarrier_Store(&space_allocated_, 0); + space_allocated_.store(0, std::memory_order_relaxed); } } @@ -118,7 +118,7 @@ ArenaImpl::Block* ArenaImpl::NewBlock(Block* last_block, size_t min_bytes) { void* mem = options_.block_alloc(size); Block* b = new (mem) Block(size, last_block); - google::protobuf::internal::NoBarrier_AtomicIncrement(&space_allocated_, size); + space_allocated_.fetch_add(size, std::memory_order_relaxed); return b; } @@ -142,6 +142,7 @@ void ArenaImpl::SerialArena::AddCleanupFallback(void* elem, AddCleanup(elem, cleanup); } +GOOGLE_PROTOBUF_ATTRIBUTE_FUNC_ALIGN(32) void* ArenaImpl::AllocateAligned(size_t n) { SerialArena* arena; if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) { @@ -199,8 +200,7 @@ bool ArenaImpl::GetSerialArenaFast(ArenaImpl::SerialArena** arena) { // Check whether we own the last accessed SerialArena on this arena. This // fast path optimizes the case where a single thread uses multiple arenas. - SerialArena* serial = - reinterpret_cast<SerialArena*>(google::protobuf::internal::Acquire_Load(&hint_)); + SerialArena* serial = hint_.load(std::memory_order_acquire); if (GOOGLE_PREDICT_TRUE(serial != NULL && serial->owner() == tc)) { *arena = serial; return true; @@ -235,12 +235,11 @@ void* ArenaImpl::SerialArena::AllocateAlignedFallback(size_t n) { } uint64 ArenaImpl::SpaceAllocated() const { - return google::protobuf::internal::NoBarrier_Load(&space_allocated_); + return space_allocated_.load(std::memory_order_relaxed); } uint64 ArenaImpl::SpaceUsed() const { - SerialArena* serial = - reinterpret_cast<SerialArena*>(google::protobuf::internal::Acquire_Load(&threads_)); + SerialArena* serial = threads_.load(std::memory_order_acquire); uint64 space_used = 0; for ( ; serial; serial = serial->next()) { space_used += serial->SpaceUsed(); @@ -264,8 +263,7 @@ uint64 ArenaImpl::FreeBlocks() { uint64 space_allocated = 0; // By omitting an Acquire barrier we ensure that any user code that doesn't // properly synchronize Reset() or the destructor will throw a TSAN warning. - SerialArena* serial = - reinterpret_cast<SerialArena*>(google::protobuf::internal::NoBarrier_Load(&threads_)); + SerialArena* serial = threads_.load(std::memory_order_relaxed); while (serial) { // This is inside a block we are freeing, so we need to read it now. @@ -311,8 +309,7 @@ uint64 ArenaImpl::SerialArena::Free(ArenaImpl::SerialArena* serial, void ArenaImpl::CleanupList() { // By omitting an Acquire barrier we ensure that any user code that doesn't // properly synchronize Reset() or the destructor will throw a TSAN warning. - SerialArena* serial = - reinterpret_cast<SerialArena*>(google::protobuf::internal::NoBarrier_Load(&threads_)); + SerialArena* serial = threads_.load(std::memory_order_relaxed); for ( ; serial; serial = serial->next()) { serial->CleanupList(); @@ -368,8 +365,7 @@ ArenaImpl::SerialArena* ArenaImpl::SerialArena::New(Block* b, void* owner, GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ArenaImpl::SerialArena* ArenaImpl::GetSerialArenaFallback(void* me) { // Look for this SerialArena in our linked list. - SerialArena* serial = - reinterpret_cast<SerialArena*>(google::protobuf::internal::Acquire_Load(&threads_)); + SerialArena* serial = threads_.load(std::memory_order_acquire); for ( ; serial; serial = serial->next()) { if (serial->owner() == me) { break; @@ -382,12 +378,11 @@ ArenaImpl::SerialArena* ArenaImpl::GetSerialArenaFallback(void* me) { Block* b = NewBlock(NULL, kSerialArenaSize); serial = SerialArena::New(b, me, this); - google::protobuf::internal::AtomicWord head; + SerialArena* head = threads_.load(std::memory_order_relaxed); do { - head = google::protobuf::internal::NoBarrier_Load(&threads_); - serial->set_next(reinterpret_cast<SerialArena*>(head)); - } while (google::protobuf::internal::Release_CompareAndSwap( - &threads_, head, reinterpret_cast<google::protobuf::internal::AtomicWord>(serial)) != head); + serial->set_next(head); + } while (!threads_.compare_exchange_weak( + head, serial, std::memory_order_release, std::memory_order_relaxed)); } CacheSerialArena(serial); diff --git a/src/google/protobuf/arena.h b/src/google/protobuf/arena.h index f3cdedac..9928c8e6 100644 --- a/src/google/protobuf/arena.h +++ b/src/google/protobuf/arena.h @@ -37,10 +37,7 @@ #ifdef max #undef max // Visual Studio defines this macro #endif -#if LANG_CXX11 -#include <google/protobuf/stubs/type_traits.h> -#endif -#if defined(_MSC_VER) && !_HAS_EXCEPTIONS +#if defined(_MSC_VER) && !defined(_LIBCPP_STD_VER) && !_HAS_EXCEPTIONS // Work around bugs in MSVC <typeinfo> header when _HAS_EXCEPTIONS=0. #include <exception> #include <typeinfo> @@ -53,10 +50,13 @@ using type_info = ::type_info; #include <google/protobuf/arena_impl.h> #include <google/protobuf/stubs/port.h> +#include <type_traits> namespace google { namespace protobuf { -struct ArenaOptions; + +struct ArenaOptions; // defined below + } // namespace protobuf namespace quality_webanswers { @@ -66,27 +66,32 @@ void TempPrivateWorkAround(::google::protobuf::ArenaOptions* arena_options); } // namespace quality_webanswers namespace protobuf { + +class Arena; // defined below +class Message; // defined in message.h +class MessageLite; + namespace arena_metrics { void EnableArenaMetrics(::google::protobuf::ArenaOptions* options); } // namespace arena_metrics -class Arena; // defined below -class Message; // message.h - namespace internal { -struct ArenaStringPtr; // arenastring.h -class LazyField; // lazy_field.h -template<typename Type> -class GenericTypeHandler; // repeated_field.h +struct ArenaStringPtr; // defined in arenastring.h +class LazyField; // defined in lazy_field.h + +template <typename Type> +class GenericTypeHandler; // defined in repeated_field.h // Templated cleanup methods. -template<typename T> void arena_destruct_object(void* object) { +template <typename T> +void arena_destruct_object(void* object) { reinterpret_cast<T*>(object)->~T(); } -template<typename T> void arena_delete_object(void* object) { +template <typename T> +void arena_delete_object(void* object) { delete reinterpret_cast<T*>(object); } inline void arena_free(void* object, size_t size) { @@ -165,12 +170,12 @@ struct ArenaOptions { // intentionally want to avoid monitoring an allocation. (i.e. internal // allocations for managing the arena) void (*on_arena_allocation)(const std::type_info* allocated_type, - uint64 alloc_size, void* cookie); + uint64 alloc_size, void* cookie); // Constants define default starting block size and max block size for // arena allocator behavior -- see descriptions above. static const size_t kDefaultStartBlockSize = 256; - static const size_t kDefaultMaxBlockSize = 8192; + static const size_t kDefaultMaxBlockSize = 8192; friend void ::google::protobuf::arena_metrics::EnableArenaMetrics(ArenaOptions*); friend void quality_webanswers::TempPrivateWorkAround(ArenaOptions*); @@ -285,70 +290,16 @@ class LIBPROTOBUF_EXPORT Arena { // // This function also accepts any type T that satisfies the arena message // allocation protocol, documented above. -#if LANG_CXX11 template <typename T, typename... Args> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessage( - ::google::protobuf::Arena* arena, Args&&... args) { - static_assert( - InternalHelper<T>::is_arena_constructable::value, - "CreateMessage can only construct types that are ArenaConstructable"); - if (arena == NULL) { - return new T(NULL, std::forward<Args>(args)...); - } else { - return arena->CreateMessageInternal<T>(std::forward<Args>(args)...); - } - } -#endif - - template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* CreateMessage(::google::protobuf::Arena* arena) { -#if LANG_CXX11 - static_assert( - InternalHelper<T>::is_arena_constructable::value, - "CreateMessage can only construct types that are ArenaConstructable"); -#endif - if (arena == NULL) { - return new T; - } else { - return arena->CreateMessageInternal<T>(); - } - } - - // One-argument form of CreateMessage. This is useful for constructing objects - // that implement the arena message construction protocol described above but - // take additional constructor arguments. - template <typename T, typename Arg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* CreateMessage(::google::protobuf::Arena* arena, const Arg& arg) { -#if LANG_CXX11 - static_assert( - InternalHelper<T>::is_arena_constructable::value, - "CreateMessage can only construct types that are ArenaConstructable"); -#endif - if (arena == NULL) { - return new T(NULL, arg); - } else { - return arena->CreateMessageInternal<T>(arg); - } - } - - // Two-argument form of CreateMessage. This is useful for constructing objects - // that implement the arena message construction protocol described above but - // take additional constructor arguments. - template <typename T, typename Arg1, typename Arg2> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* CreateMessage(::google::protobuf::Arena* arena, - const Arg1& arg1, - const Arg2& arg2) { -#if LANG_CXX11 + Arena* arena, Args&&... args) { static_assert( InternalHelper<T>::is_arena_constructable::value, "CreateMessage can only construct types that are ArenaConstructable"); -#endif - if (arena == NULL) { - return new T(NULL, arg1, arg2); - } else { - return arena->CreateMessageInternal<T>(arg1, arg2); - } + // We must delegate to CreateMaybeMessage() and NOT CreateMessageInternal() + // because protobuf generated classes specialize CreateMaybeMessage() and we + // need to use that specialization for code size reasons. + return Arena::CreateMaybeMessage<T>(arena, std::forward<Args>(args)...); } // API to create any objects on the arena. Note that only the object will @@ -366,153 +317,11 @@ class LIBPROTOBUF_EXPORT Arena { // (unless the destructor is trivial). Hence, from T's point of view, it is as // if the object were allocated on the heap (except that the underlying memory // is obtained from the arena). -#if LANG_CXX11 template <typename T, typename... Args> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena, Args&&... args) { - if (arena == NULL) { - return new T(std::forward<Args>(args)...); - } else { - return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value, - std::forward<Args>(args)...); - } - } -#endif - - template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena) { - if (arena == NULL) { - return new T(); - } else { - return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value); - } - } - - // Version of the above with one constructor argument for the created object. - template <typename T, typename Arg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena, const Arg& arg) { - if (arena == NULL) { - return new T(arg); - } else { - return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value, - arg); - } - } - - // Version of the above with two constructor arguments for the created object. - template <typename T, typename Arg1, typename Arg2> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena, const Arg1& arg1, const Arg2& arg2) { - if (arena == NULL) { - return new T(arg1, arg2); - } else { - return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value, - arg1, arg2); - } - } - - // Version of the above with three constructor arguments for the created - // object. - template <typename T, typename Arg1, typename Arg2, typename Arg3> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena, - const Arg1& arg1, - const Arg2& arg2, - const Arg3& arg3) { - if (arena == NULL) { - return new T(arg1, arg2, arg3); - } else { - return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value, - arg1, arg2, arg3); - } - } - - // Version of the above with four constructor arguments for the created - // object. - template <typename T, typename Arg1, typename Arg2, typename Arg3, - typename Arg4> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena, - const Arg1& arg1, const Arg2& arg2, - const Arg3& arg3, const Arg4& arg4) { - if (arena == NULL) { - return new T(arg1, arg2, arg3, arg4); - } else { - return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value, - arg1, arg2, arg3, arg4); - } - } - - // Version of the above with five constructor arguments for the created - // object. - template <typename T, typename Arg1, typename Arg2, typename Arg3, - typename Arg4, typename Arg5> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena, - const Arg1& arg1, const Arg2& arg2, - const Arg3& arg3, const Arg4& arg4, - const Arg5& arg5) { - if (arena == NULL) { - return new T(arg1, arg2, arg3, arg4, arg5); - } else { - return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value, - arg1, arg2, arg3, arg4, arg5); - } - } - - // Version of the above with six constructor arguments for the created - // object. - template <typename T, typename Arg1, typename Arg2, typename Arg3, - typename Arg4, typename Arg5, typename Arg6> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena, - const Arg1& arg1, const Arg2& arg2, - const Arg3& arg3, const Arg4& arg4, - const Arg5& arg5, const Arg6& arg6) { - if (arena == NULL) { - return new T(arg1, arg2, arg3, arg4, arg5, arg6); - } else { - return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value, - arg1, arg2, arg3, arg4, arg5, arg6); - } - } - - // Version of the above with seven constructor arguments for the created - // object. - template <typename T, typename Arg1, typename Arg2, typename Arg3, - typename Arg4, typename Arg5, typename Arg6, typename Arg7> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena, - const Arg1& arg1, const Arg2& arg2, - const Arg3& arg3, const Arg4& arg4, - const Arg5& arg5, const Arg6& arg6, - const Arg7& arg7) { - if (arena == NULL) { - return new T(arg1, arg2, arg3, arg4, arg5, arg6, arg7); - } else { - return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value, - arg1, arg2, arg3, arg4, arg5, arg6, arg7); - } - } - - // Version of the above with eight constructor arguments for the created - // object. - template <typename T, typename Arg1, typename Arg2, typename Arg3, - typename Arg4, typename Arg5, typename Arg6, typename Arg7, - typename Arg8> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena, - const Arg1& arg1, const Arg2& arg2, - const Arg3& arg3, const Arg4& arg4, - const Arg5& arg5, const Arg6& arg6, - const Arg7& arg7, const Arg8& arg8) { - if (arena == NULL) { - return new T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); - } else { - return arena->CreateInternal<T>( - google::protobuf::internal::has_trivial_destructor<T>::value, - arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); - } + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* Create(Arena* arena, + Args&&... args) { + return CreateNoMessage<T>(arena, is_arena_constructable<T>(), + std::forward<Args>(args)...); } // Create an array of object type T on the arena *without* invoking the @@ -521,10 +330,14 @@ class LIBPROTOBUF_EXPORT Arena { // To ensure safe uses, this function checks at compile time // (when compiled as C++11) that T is trivially default-constructible and // trivially destructible. - template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* CreateArray(::google::protobuf::Arena* arena, size_t num_elements) { - GOOGLE_CHECK_LE(num_elements, - std::numeric_limits<size_t>::max() / sizeof(T)) + template <typename T> + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateArray( + Arena* arena, size_t num_elements) { + static_assert(std::is_pod<T>::value, + "CreateArray requires a trivially constructible type"); + static_assert(std::is_trivially_destructible<T>::value, + "CreateArray requires a trivially destructible type"); + GOOGLE_CHECK_LE(num_elements, std::numeric_limits<size_t>::max() / sizeof(T)) << "Requested size is too large to fit into size_t."; if (arena == NULL) { return static_cast<T*>(::operator new[](num_elements * sizeof(T))); @@ -566,9 +379,9 @@ class LIBPROTOBUF_EXPORT Arena { // Adds |object| to a list of heap-allocated objects to be freed with |delete| // when the arena is destroyed or reset. - template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE - void Own(T* object) { - OwnInternal(object, google::protobuf::internal::is_convertible<T*, ::google::protobuf::Message*>()); + template <typename T> + GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void Own(T* object) { + OwnInternal(object, std::is_convertible<T*, Message*>()); } // Adds |object| to a list of objects whose destructors will be manually @@ -576,8 +389,8 @@ class LIBPROTOBUF_EXPORT Arena { // that it does not free the underlying memory with |delete|; hence, it is // normally only used for objects that are placement-newed into // arena-allocated memory. - template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE - void OwnDestructor(T* object) { + template <typename T> + GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void OwnDestructor(T* object) { if (object != NULL) { impl_.AddCleanup(object, &internal::arena_destruct_object<T>); } @@ -596,8 +409,9 @@ class LIBPROTOBUF_EXPORT Arena { // message, or NULL otherwise. This differs from value->GetArena() in that the // latter is a virtual call, while this method is a templated call that // resolves at compile-time. - template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static ::google::protobuf::Arena* GetArena(const T* value) { + template <typename T> + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArena( + const T* value) { return GetArenaInternal(value, is_arena_constructable<T>()); } @@ -608,80 +422,89 @@ class LIBPROTOBUF_EXPORT Arena { template <typename U> static double DestructorSkippable(...); - typedef google::protobuf::internal::integral_constant< + typedef std::integral_constant< bool, sizeof(DestructorSkippable<T>(static_cast<const T*>(0))) == sizeof(char) || - google::protobuf::internal::has_trivial_destructor<T>::value> + std::is_trivially_destructible<T>::value> is_destructor_skippable; - template<typename U> + template <typename U> static char ArenaConstructable( const typename U::InternalArenaConstructable_*); - template<typename U> + template <typename U> static double ArenaConstructable(...); - typedef google::protobuf::internal::integral_constant<bool, sizeof(ArenaConstructable<T>( - static_cast<const T*>(0))) == - sizeof(char)> + typedef std::integral_constant<bool, sizeof(ArenaConstructable<T>( + static_cast<const T*>(0))) == + sizeof(char)> is_arena_constructable; -#if LANG_CXX11 template <typename... Args> static T* Construct(void* ptr, Args&&... args) { return new (ptr) T(std::forward<Args>(args)...); } -#else - template <typename Arg1> - static T* Construct(void* ptr, const Arg1& arg1) { - return new (ptr) T(arg1); - } - template <typename Arg1, typename Arg2> - static T* Construct(void* ptr, const Arg1& arg1, const Arg2& arg2) { - return new (ptr) T(arg1, arg2); - } - template <typename Arg1, typename Arg2, typename Arg3> - static T* Construct(void* ptr, const Arg1& arg1, - const Arg2& arg2, const Arg3& arg3) { - return new (ptr) T(arg1, arg2, arg3); - } -#endif // LANG_CXX11 static Arena* GetArena(const T* p) { return p->GetArenaNoVirtual(); } friend class Arena; }; - // Helper typetrait that indicates support for arenas in a type T at compile + // Helper typetraits that indicates support for arenas in a type T at compile // time. This is public only to allow construction of higher-level templated - // utilities. is_arena_constructable<T>::value is true if the message type T - // has arena support enabled, and false otherwise. + // utilities. + // + // is_arena_constructable<T>::value is true if the message type T has arena + // support enabled, and false otherwise. + // + // is_destructor_skippable<T>::value is true if the message type T has told + // the arena that it is safe to skip the destructor, and false otherwise. // // This is inside Arena because only Arena has the friend relationships // necessary to see the underlying generated code traits. template <typename T> struct is_arena_constructable : InternalHelper<T>::is_arena_constructable {}; + template <typename T> + struct is_destructor_skippable : InternalHelper<T>::is_destructor_skippable { + }; private: - template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* CreateMessageInternal(::google::protobuf::Arena* arena) { -#if LANG_CXX11 + template <typename T, typename... Args> + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessageInternal( + Arena* arena, Args&&... args) { static_assert( InternalHelper<T>::is_arena_constructable::value, "CreateMessage can only construct types that are ArenaConstructable"); -#endif if (arena == NULL) { - return new T; + return new T(nullptr, std::forward<Args>(args)...); } else { - return arena->CreateMessageInternal<T>(); + return arena->DoCreateMessage<T>(std::forward<Args>(args)...); } } - template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* CreateInternal(::google::protobuf::Arena* arena) { + // This specialization for no arguments is necessary, because its behavior is + // slightly different. When the arena pointer is nullptr, it calls T() + // instead of T(nullptr). + template <typename T> + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessageInternal( + Arena* arena) { + static_assert( + InternalHelper<T>::is_arena_constructable::value, + "CreateMessage can only construct types that are ArenaConstructable"); if (arena == NULL) { return new T(); } else { - return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value); + return arena->DoCreateMessage<T>(); + } + } + + template <typename T, typename... Args> + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateInternal( + Arena* arena, Args&&... args) { + if (arena == NULL) { + return new T(std::forward<Args>(args)...); + } else { + return arena->DoCreate<T>(std::is_trivially_destructible<T>::value, + std::forward<Args>(args)...); } } @@ -696,8 +519,9 @@ class LIBPROTOBUF_EXPORT Arena { // Allocate and also optionally call on_arena_allocation callback with the // allocated type info when the hooks are in place in ArenaOptions and // the cookie is not null. - template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - void* AllocateInternal(bool skip_explicit_ownership) { + template <typename T> + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void* AllocateInternal( + bool skip_explicit_ownership) { const size_t n = internal::AlignUpTo8(sizeof(T)); AllocHook(RTTI_TYPE_ID(T), n); // Monitor allocation if needed. @@ -714,27 +538,49 @@ class LIBPROTOBUF_EXPORT Arena { // as it can cause confusing API usages, and end up having double free in // user code. These are used only internally from LazyField and Repeated // fields, since they are designed to work in all mode combinations. - template <typename Msg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static Msg* CreateMaybeMessage(Arena* arena, google::protobuf::internal::true_type) { - return CreateMessageInternal<Msg>(arena); + template <typename Msg, typename... Args> + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Msg* DoCreateMaybeMessage( + Arena* arena, std::true_type, Args&&... args) { + return CreateMessageInternal<Msg>(arena, std::forward<Args>(args)...); } - template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* CreateMaybeMessage(Arena* arena, google::protobuf::internal::false_type) { - return CreateInternal<T>(arena); + template <typename T, typename... Args> + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* DoCreateMaybeMessage( + Arena* arena, std::false_type, Args&&... args) { + return CreateInternal<T>(arena, std::forward<Args>(args)...); } - template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* CreateMaybeMessage(Arena* arena) { - return CreateMaybeMessage<T>(arena, is_arena_constructable<T>()); + template <typename T, typename... Args> + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMaybeMessage( + Arena* arena, Args&&... args) { + return DoCreateMaybeMessage<T>(arena, is_arena_constructable<T>(), + std::forward<Args>(args)...); + } + + template <typename T, typename... Args> + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateNoMessage( + Arena* arena, std::true_type, Args&&... args) { + // User is constructing with Create() despite the fact that T supports arena + // construction. In this case we have to delegate to CreateInternal(), and + // we can't use any CreateMaybeMessage() specialization that may be defined. + return CreateInternal<T>(arena, std::forward<Args>(args)...); + } + + template <typename T, typename... Args> + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateNoMessage( + Arena* arena, std::false_type, Args&&... args) { + // User is constructing with Create() and the type does not support arena + // construction. In this case we can delegate to CreateMaybeMessage() and + // use any specialization that may be available for that. + return CreateMaybeMessage<T>(arena, std::forward<Args>(args)...); } // Just allocate the required size for the given type assuming the // type has a trivial constructor. - template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternalRawArray(size_t num_elements) { - GOOGLE_CHECK_LE(num_elements, - std::numeric_limits<size_t>::max() / sizeof(T)) + template <typename T> + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateInternalRawArray( + size_t num_elements) { + GOOGLE_CHECK_LE(num_elements, std::numeric_limits<size_t>::max() / sizeof(T)) << "Requested size is too large to fit into size_t."; const size_t n = internal::AlignUpTo8(sizeof(T) * num_elements); // Monitor allocation if needed. @@ -742,143 +588,18 @@ class LIBPROTOBUF_EXPORT Arena { return static_cast<T*>(impl_.AllocateAligned(n)); } -#if LANG_CXX11 template <typename T, typename... Args> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership, Args&&... args) { + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* DoCreate( + bool skip_explicit_ownership, Args&&... args) { return new (AllocateInternal<T>(skip_explicit_ownership)) T(std::forward<Args>(args)...); } -#else - template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership) { - return new (AllocateInternal<T>(skip_explicit_ownership)) T(); - } - - template <typename T, typename Arg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership, const Arg& arg) { - return new (AllocateInternal<T>(skip_explicit_ownership)) T(arg); - } - - template <typename T, typename Arg1, typename Arg2> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership, - const Arg1& arg1, - const Arg2& arg2) { - return new (AllocateInternal<T>(skip_explicit_ownership)) T(arg1, arg2); - } - - template <typename T, typename Arg1, typename Arg2, typename Arg3> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership, - const Arg1& arg1, - const Arg2& arg2, - const Arg3& arg3) { - return new (AllocateInternal<T>(skip_explicit_ownership)) - T(arg1, arg2, arg3); - } - - template <typename T, typename Arg1, typename Arg2, typename Arg3, - typename Arg4> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership, - const Arg1& arg1, - const Arg2& arg2, - const Arg3& arg3, - const Arg4& arg4) { - return new (AllocateInternal<T>(skip_explicit_ownership)) - T(arg1, arg2, arg3, arg4); - } - - template <typename T, typename Arg1, typename Arg2, typename Arg3, - typename Arg4, typename Arg5> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership, - const Arg1& arg1, - const Arg2& arg2, - const Arg3& arg3, - const Arg4& arg4, - const Arg5& arg5) { - return new (AllocateInternal<T>(skip_explicit_ownership)) - T(arg1, arg2, arg3, arg4, arg5); - } - - template <typename T, typename Arg1, typename Arg2, typename Arg3, - typename Arg4, typename Arg5, typename Arg6> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership, - const Arg1& arg1, - const Arg2& arg2, - const Arg3& arg3, - const Arg4& arg4, - const Arg5& arg5, - const Arg6& arg6) { - return new (AllocateInternal<T>(skip_explicit_ownership)) - T(arg1, arg2, arg3, arg4, arg5, arg6); - } - - template <typename T, typename Arg1, typename Arg2, typename Arg3, - typename Arg4, typename Arg5, typename Arg6, typename Arg7> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership, - const Arg1& arg1, - const Arg2& arg2, - const Arg3& arg3, - const Arg4& arg4, - const Arg5& arg5, - const Arg6& arg6, - const Arg7& arg7) { - return new (AllocateInternal<T>(skip_explicit_ownership)) - T(arg1, arg2, arg3, arg4, arg5, arg6, arg7); - } - - template <typename T, typename Arg1, typename Arg2, typename Arg3, - typename Arg4, typename Arg5, typename Arg6, typename Arg7, - typename Arg8> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership, - const Arg1& arg1, - const Arg2& arg2, - const Arg3& arg3, - const Arg4& arg4, - const Arg5& arg5, - const Arg6& arg6, - const Arg7& arg7, - const Arg8& arg8) { - return new (AllocateInternal<T>(skip_explicit_ownership)) - T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); - } -#endif -#if LANG_CXX11 template <typename T, typename... Args> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateMessageInternal( - Args&&... args) { + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* DoCreateMessage(Args&&... args) { return InternalHelper<T>::Construct( AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value), this, std::forward<Args>(args)...); } -#endif - template <typename T> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateMessageInternal() { - return InternalHelper<T>::Construct( - AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value), - this); - } - - template <typename T, typename Arg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateMessageInternal(const Arg& arg) { - return InternalHelper<T>::Construct( - AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value), - this, arg); - } - - template <typename T, typename Arg1, typename Arg2> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateMessageInternal(const Arg1& arg1, const Arg2& arg2) { - return InternalHelper<T>::Construct( - AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value), - this, arg1, arg2); - } // CreateInArenaStorage is used to implement map field. Without it, // google::protobuf::Map need to call generated message's protected arena constructor, @@ -893,22 +614,22 @@ class LIBPROTOBUF_EXPORT Arena { } template <typename T> - static void CreateInArenaStorageInternal( - T* ptr, Arena* arena, google::protobuf::internal::true_type) { + static void CreateInArenaStorageInternal(T* ptr, Arena* arena, + std::true_type) { InternalHelper<T>::Construct(ptr, arena); } template <typename T> - static void CreateInArenaStorageInternal( - T* ptr, Arena* /* arena */, google::protobuf::internal::false_type) { + static void CreateInArenaStorageInternal(T* ptr, Arena* /* arena */, + std::false_type) { new (ptr) T(); } template <typename T> - static void RegisterDestructorInternal( - T* /* ptr */, Arena* /* arena */, google::protobuf::internal::true_type) {} + static void RegisterDestructorInternal(T* /* ptr */, Arena* /* arena */, + std::true_type) {} template <typename T> - static void RegisterDestructorInternal( - T* ptr, Arena* arena, google::protobuf::internal::false_type) { + static void RegisterDestructorInternal(T* ptr, Arena* arena, + std::false_type) { arena->OwnDestructor(ptr); } @@ -917,15 +638,16 @@ class LIBPROTOBUF_EXPORT Arena { // is a subtype of ::google::protobuf::Message and 'false_type' otherwise. Collapsing // all template instantiations to one for generic Message reduces code size, // using the virtual destructor instead. - template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - void OwnInternal(T* object, google::protobuf::internal::true_type) { + template <typename T> + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void OwnInternal(T* object, + std::true_type) { if (object != NULL) { - impl_.AddCleanup(object, - &internal::arena_delete_object< ::google::protobuf::Message>); + impl_.AddCleanup(object, &internal::arena_delete_object<Message>); } } - template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - void OwnInternal(T* object, google::protobuf::internal::false_type) { + template <typename T> + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void OwnInternal(T* object, + std::false_type) { if (object != NULL) { impl_.AddCleanup(object, &internal::arena_delete_object<T>); } @@ -934,16 +656,15 @@ class LIBPROTOBUF_EXPORT Arena { // Implementation for GetArena(). Only message objects with // InternalArenaConstructable_ tags can be associated with an arena, and such // objects must implement a GetArenaNoVirtual() method. - template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static ::google::protobuf::Arena* GetArenaInternal( - const T* value, google::protobuf::internal::true_type) { + template <typename T> + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArenaInternal( + const T* value, std::true_type) { return InternalHelper<T>::GetArena(value); } template <typename T> - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static ::google::protobuf::Arena* GetArenaInternal( - const T* /* value */, google::protobuf::internal::false_type) { + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArenaInternal( + const T* /* value */, std::false_type) { return NULL; } @@ -965,9 +686,10 @@ class LIBPROTOBUF_EXPORT Arena { void* hooks_cookie_; template <typename Type> - friend class ::google::protobuf::internal::GenericTypeHandler; + friend class internal::GenericTypeHandler; friend struct internal::ArenaStringPtr; // For AllocateAligned. - friend class internal::LazyField; // For CreateMaybeMessage. + friend class internal::LazyField; // For CreateMaybeMessage. + friend class MessageLite; template <typename Key, typename T> friend class Map; }; diff --git a/src/google/protobuf/arena_impl.h b/src/google/protobuf/arena_impl.h index 439b0969..f648f166 100644 --- a/src/google/protobuf/arena_impl.h +++ b/src/google/protobuf/arena_impl.h @@ -33,13 +33,11 @@ #ifndef GOOGLE_PROTOBUF_ARENA_IMPL_H__ #define GOOGLE_PROTOBUF_ARENA_IMPL_H__ +#include <atomic> #include <limits> -#include <google/protobuf/stubs/atomic_sequence_num.h> -#include <google/protobuf/stubs/atomicops.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/logging.h> -#include <google/protobuf/stubs/mutex.h> #include <google/protobuf/stubs/port.h> @@ -248,7 +246,7 @@ class LIBPROTOBUF_EXPORT ArenaImpl { int64 last_lifecycle_id_seen; SerialArena* last_serial_arena; }; - static google::protobuf::internal::SequenceNumber lifecycle_id_generator_; + static std::atomic<int64> lifecycle_id_generator_; #if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL) // Android ndk does not support GOOGLE_THREAD_LOCAL keyword so we use a custom thread // local storage class we implemented. @@ -277,12 +275,15 @@ class LIBPROTOBUF_EXPORT ArenaImpl { // TODO(haberman): evaluate whether we would gain efficiency by getting rid // of hint_. It's the only write we do to ArenaImpl in the allocation path, // which will dirty the cache line. - google::protobuf::internal::Release_Store(&hint_, reinterpret_cast<google::protobuf::internal::AtomicWord>(serial)); + + hint_.store(serial, std::memory_order_release); } - google::protobuf::internal::AtomicWord threads_; // Pointer to a linked list of SerialArena. - google::protobuf::internal::AtomicWord hint_; // Fast thread-local block access - google::protobuf::internal::AtomicWord space_allocated_; // Sum of sizes of all allocated blocks. + + std::atomic<SerialArena*> + threads_; // Pointer to a linked list of SerialArena. + std::atomic<SerialArena*> hint_; // Fast thread-local block access + std::atomic<size_t> space_allocated_; // Total size of all allocated blocks. Block *initial_block_; // If non-NULL, points to the block that came from // user data. @@ -297,18 +298,20 @@ class LIBPROTOBUF_EXPORT ArenaImpl { Options options_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArenaImpl); + // All protos have pointers back to the arena hence Arena must have + // pointer stability. + ArenaImpl(ArenaImpl&&) = delete; + ArenaImpl& operator=(ArenaImpl&&) = delete; public: // kBlockHeaderSize is sizeof(Block), aligned up to the nearest multiple of 8 // to protect the invariant that pos is always at a multiple of 8. static const size_t kBlockHeaderSize = (sizeof(Block) + 7) & -8; static const size_t kSerialArenaSize = (sizeof(SerialArena) + 7) & -8; -#if LANG_CXX11 static_assert(kBlockHeaderSize % 8 == 0, "kBlockHeaderSize must be a multiple of 8."); static_assert(kSerialArenaSize % 8 == 0, "kSerialArenaSize must be a multiple of 8."); -#endif }; } // namespace internal diff --git a/src/google/protobuf/arena_test_util.h b/src/google/protobuf/arena_test_util.h index 8c9f7698..df56ece8 100644 --- a/src/google/protobuf/arena_test_util.h +++ b/src/google/protobuf/arena_test_util.h @@ -50,7 +50,7 @@ void TestParseCorruptedString(const T& message) { s[i] ^= c; google::protobuf::Arena arena; T* message = - google::protobuf::Arena::CreateMessage<T>(use_arena ? &arena : NULL); + google::protobuf::Arena::CreateMessage<T>(use_arena ? &arena : nullptr); if (message->ParseFromString(s)) { ++success_count; } diff --git a/src/google/protobuf/arena_unittest.cc b/src/google/protobuf/arena_unittest.cc index 71e28b0c..eaaffce2 100644 --- a/src/google/protobuf/arena_unittest.cc +++ b/src/google/protobuf/arena_unittest.cc @@ -33,10 +33,8 @@ #include <algorithm> #include <cstring> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <string> +#include <type_traits> #include <typeinfo> #include <vector> @@ -153,9 +151,19 @@ class MustBeConstructedWithOneThroughEight { TEST(ArenaTest, ArenaConstructable) { EXPECT_TRUE(Arena::is_arena_constructable<TestAllTypes>::type::value); EXPECT_TRUE(Arena::is_arena_constructable<const TestAllTypes>::type::value); + EXPECT_FALSE(Arena::is_arena_constructable< + protobuf_unittest_no_arena::TestNoArenaMessage>::type::value); EXPECT_FALSE(Arena::is_arena_constructable<Arena>::type::value); } +TEST(ArenaTest, DestructorSkippable) { + EXPECT_TRUE(Arena::is_destructor_skippable<TestAllTypes>::type::value); + EXPECT_TRUE(Arena::is_destructor_skippable<const TestAllTypes>::type::value); + EXPECT_FALSE(Arena::is_destructor_skippable< + protobuf_unittest_no_arena::TestNoArenaMessage>::type::value); + EXPECT_FALSE(Arena::is_destructor_skippable<Arena>::type::value); +} + TEST(ArenaTest, BasicCreate) { Arena arena; EXPECT_TRUE(Arena::Create<int32>(&arena) != NULL); @@ -197,7 +205,6 @@ TEST(ArenaTest, CreateAndNonConstCopy) { EXPECT_EQ("foo", *s_copy); } -#if LANG_CXX11 TEST(ArenaTest, CreateAndMove) { Arena arena; string s("foo"); @@ -206,7 +213,6 @@ TEST(ArenaTest, CreateAndMove) { EXPECT_TRUE(s.empty()); // NOLINT EXPECT_EQ("foo", *s_move); } -#endif TEST(ArenaTest, CreateWithFourConstructorArguments) { Arena arena; @@ -242,7 +248,6 @@ TEST(ArenaTest, CreateWithEightConstructorArguments) { ASSERT_EQ("8", new_object->eight_); } -#if LANG_CXX11 class PleaseMoveMe { public: explicit PleaseMoveMe(const string& value) : value_(value) {} @@ -263,7 +268,6 @@ TEST(ArenaTest, CreateWithMoveArguments) { EXPECT_TRUE(new_object); ASSERT_EQ("1", new_object->value()); } -#endif TEST(ArenaTest, InitialBlockTooSmall) { // Construct a small (64 byte) initial block of memory to be used by the @@ -442,7 +446,7 @@ TEST(ArenaTest, ReflectionSwapFields) { TestUtil::SetAllFields(arena1_message); reflection->SwapFields(arena1_message, &message, fields); EXPECT_EQ(&arena1, arena1_message->GetArena()); - EXPECT_EQ(NULL, message.GetArena()); + EXPECT_EQ(nullptr, message.GetArena()); arena1_message->SerializeToString(&output); EXPECT_EQ(0, output.size()); TestUtil::ExpectAllFieldsSet(message); @@ -468,7 +472,7 @@ TEST(ArenaTest, ReleaseMessage) { Arena arena; TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena); arena_message->mutable_optional_nested_message()->set_bb(118); - google::protobuf::scoped_ptr<TestAllTypes::NestedMessage> nested( + std::unique_ptr<TestAllTypes::NestedMessage> nested( arena_message->release_optional_nested_message()); EXPECT_EQ(118, nested->bb()); @@ -489,7 +493,7 @@ TEST(ArenaTest, ReleaseString) { Arena arena; TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena); arena_message->set_optional_string("hello"); - google::protobuf::scoped_ptr<string> released_str( + std::unique_ptr<string> released_str( arena_message->release_optional_string()); EXPECT_EQ("hello", *released_str); @@ -600,25 +604,6 @@ TEST(ArenaTest, ReleaseFromArenaMessageUsingReflectionMakesCopy) { } #endif // !GOOGLE_PROTOBUF_NO_RTTI -TEST(ArenaTest, UnsafeArenaReleaseDoesNotMakeCopy) { - Arena arena; - TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena); - TestAllTypes::NestedMessage* nested_msg = NULL; - TestAllTypes::NestedMessage* orig_nested_msg = NULL; - string* nested_string = NULL; - string* orig_nested_string = NULL; - arena_message->mutable_optional_nested_message()->set_bb(42); - *arena_message->mutable_optional_string() = "Hello"; - orig_nested_msg = arena_message->mutable_optional_nested_message(); - orig_nested_string = arena_message->mutable_optional_string(); - nested_msg = arena_message->unsafe_arena_release_optional_nested_message(); - nested_string = arena_message->unsafe_arena_release_optional_string(); - - EXPECT_EQ(orig_nested_msg, nested_msg); - EXPECT_EQ(orig_nested_string, nested_string); - // Released pointers still on arena; no 'delete' calls needed here. -} - TEST(ArenaTest, SetAllocatedAcrossArenas) { Arena arena1; TestAllTypes* arena1_message = Arena::CreateMessage<TestAllTypes>(&arena1); @@ -898,17 +883,18 @@ TEST(ArenaTest, ReleaseLastRepeatedField) { TEST(ArenaTest, UnsafeArenaReleaseAdd) { // Use unsafe_arena_release() and unsafe_arena_set_allocated() to transfer an // arena-allocated string from one message to another. + const char kContent[] = "Test content"; + Arena arena; TestAllTypes* message1 = Arena::CreateMessage<TestAllTypes>(&arena); TestAllTypes* message2 = Arena::CreateMessage<TestAllTypes>(&arena); string* arena_string = Arena::Create<string>(&arena); - *arena_string = "Test content"; + *arena_string = kContent; message1->unsafe_arena_set_allocated_optional_string(arena_string); - EXPECT_EQ(arena_string, message1->mutable_optional_string()); message2->unsafe_arena_set_allocated_optional_string( message1->unsafe_arena_release_optional_string()); - EXPECT_EQ(arena_string, message2->mutable_optional_string()); + EXPECT_EQ(kContent, message2->optional_string()); } TEST(ArenaTest, UnsafeArenaAddAllocated) { @@ -1432,7 +1418,7 @@ TEST(ArenaTest, ArenaHooksSanity) { EXPECT_EQ(1, ArenaHooksTestUtil::num_init); EXPECT_EQ(0, ArenaHooksTestUtil::num_allocations); ::google::protobuf::Arena::Create<uint64>(&arena); - if (google::protobuf::internal::has_trivial_destructor<uint64>::value) { + if (std::is_trivially_destructible<uint64>::value) { EXPECT_EQ(1, ArenaHooksTestUtil::num_allocations); } else { EXPECT_EQ(2, ArenaHooksTestUtil::num_allocations); diff --git a/src/google/protobuf/arenastring.h b/src/google/protobuf/arenastring.h index fb1b64a3..168fc972 100755 --- a/src/google/protobuf/arenastring.h +++ b/src/google/protobuf/arenastring.h @@ -99,6 +99,13 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { if (ptr_ == default_value) { return NULL; } + return ReleaseNonDefault(default_value, arena); + } + + // Similar to Release, but ptr_ cannot be the default_value. + inline ::std::string* ReleaseNonDefault( + const ::std::string* default_value, ::google::protobuf::Arena* arena) { + GOOGLE_DCHECK(!IsDefault(default_value)); ::std::string* released = NULL; if (arena != NULL) { // ptr_ is owned by the arena. @@ -164,6 +171,29 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Swap(ArenaStringPtr* other) { std::swap(ptr_, other->ptr_); } + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Swap( + ArenaStringPtr* other, const ::std::string* default_value, Arena* arena) { +#ifndef NDEBUG + // For debug builds, we swap the contents of the string, rather than the + // string instances themselves. This invalidates previously taken const + // references that are (per our documentation) invalidated by calling Swap() + // on the message. + // + // If both strings are the default_value, swapping is uninteresting. + // Otherwise, we use ArenaStringPtr::Mutable() to access the string, to + // ensure that we do not try to mutate default_value itself. + if (IsDefault(default_value) && other->IsDefault(default_value)) { + return; + } + + ::std::string* this_ptr = Mutable(default_value, arena); + ::std::string* other_ptr = other->Mutable(default_value, arena); + + this_ptr->swap(*other_ptr); +#else + std::swap(ptr_, other->ptr_); +#endif + } // Frees storage (if not on an arena). inline void Destroy(const ::std::string* default_value, @@ -186,6 +216,15 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { } } + // Clears content, assuming that the current value is not the empty string + // default. + inline void ClearNonDefaultToEmpty() { + ptr_->clear(); + } + inline void ClearNonDefaultToEmptyNoArena() { + ptr_->clear(); + } + // Clears content, but keeps allocated string if arena != NULL, to avoid the // overhead of heap operations. After this returns, the content (as seen by // the user) will always be equal to |default_value|. @@ -253,12 +292,19 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { if (ptr_ == default_value) { return NULL; } else { - ::std::string* released = ptr_; - ptr_ = const_cast< ::std::string* >(default_value); - return released; + return ReleaseNonDefaultNoArena(default_value); } } + inline ::std::string* ReleaseNonDefaultNoArena( + const ::std::string* default_value) { + GOOGLE_DCHECK(!IsDefault(default_value)); + ::std::string* released = ptr_; + ptr_ = const_cast< ::std::string* >(default_value); + return released; + } + + inline void SetAllocatedNoArena(const ::std::string* default_value, ::std::string* value) { if (ptr_ != default_value) { @@ -322,10 +368,8 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { void CreateInstance(::google::protobuf::Arena* arena, const ::std::string* initial_value) { GOOGLE_DCHECK(initial_value != NULL); - ptr_ = new ::std::string(*initial_value); - if (arena != NULL) { - arena->Own(ptr_); - } + // uses "new ::std::string" when arena is nullptr + ptr_ = Arena::Create< ::std::string >(arena, *initial_value); } GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void CreateInstanceNoArena(const ::std::string* initial_value) { diff --git a/src/google/protobuf/arenastring_unittest.cc b/src/google/protobuf/arenastring_unittest.cc index d5d995a6..adc44fe2 100644 --- a/src/google/protobuf/arenastring_unittest.cc +++ b/src/google/protobuf/arenastring_unittest.cc @@ -35,9 +35,6 @@ #include <algorithm> #include <cstdlib> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <string> #include <vector> diff --git a/src/google/protobuf/compiler/annotation_test_util.cc b/src/google/protobuf/compiler/annotation_test_util.cc index cc8534cc..a0530b9a 100644 --- a/src/google/protobuf/compiler/annotation_test_util.cc +++ b/src/google/protobuf/compiler/annotation_test_util.cc @@ -31,9 +31,6 @@ #include <google/protobuf/compiler/annotation_test_util.h> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/compiler/code_generator.h> #include <google/protobuf/compiler/command_line_interface.h> #include <google/protobuf/io/printer.h> diff --git a/src/google/protobuf/compiler/code_generator.cc b/src/google/protobuf/compiler/code_generator.cc index 11d0f334..aaabd914 100644 --- a/src/google/protobuf/compiler/code_generator.cc +++ b/src/google/protobuf/compiler/code_generator.cc @@ -34,9 +34,9 @@ #include <google/protobuf/compiler/code_generator.h> -#include <google/protobuf/compiler/plugin.pb.h> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> +#include <google/protobuf/compiler/plugin.pb.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/stubs/strutil.h> diff --git a/src/google/protobuf/compiler/command_line_interface.cc b/src/google/protobuf/compiler/command_line_interface.cc index 1f6d748d..8380367f 100644 --- a/src/google/protobuf/compiler/command_line_interface.cc +++ b/src/google/protobuf/compiler/command_line_interface.cc @@ -58,9 +58,6 @@ #include <limits.h> //For PATH_MAX #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #ifdef __APPLE__ #include <mach-o/dyld.h> @@ -171,8 +168,7 @@ bool VerifyDirectoryExists(const string& path) { // directories listed in |filename|. bool TryCreateParentDirectory(const string& prefix, const string& filename) { // Recursively create parent directories to the output file. - std::vector<string> parts = - Split(filename, "/", true); + std::vector<string> parts = Split(filename, "/", true); string path_so_far = prefix; for (int i = 0; i < parts.size() - 1; i++) { path_so_far += parts[i]; @@ -226,7 +222,7 @@ bool IsInstalledProtoPath(const string& path) { // Add the paths where google/protobuf/descriptor.proto and other well-known // type protos are installed. -void AddDefaultProtoPaths(vector<pair<string, string> >* paths) { +void AddDefaultProtoPaths(std::vector<std::pair<string, string> >* paths) { // TODO(xiaofeng): The code currently only checks relative paths of where // the protoc binary is installed. We probably should make it handle more // cases than that. @@ -242,12 +238,12 @@ void AddDefaultProtoPaths(vector<pair<string, string> >* paths) { path = path.substr(0, pos); // Check the binary's directory. if (IsInstalledProtoPath(path)) { - paths->push_back(pair<string, string>("", path)); + paths->push_back(std::pair<string, string>("", path)); return; } // Check if there is an include subdirectory. if (IsInstalledProtoPath(path + "/include")) { - paths->push_back(pair<string, string>("", path + "/include")); + paths->push_back(std::pair<string, string>("", path + "/include")); return; } // Check if the upper level directory has an "include" subdirectory. @@ -257,7 +253,7 @@ void AddDefaultProtoPaths(vector<pair<string, string> >* paths) { } path = path.substr(0, pos); if (IsInstalledProtoPath(path + "/include")) { - paths->push_back(pair<string, string>("", path + "/include")); + paths->push_back(std::pair<string, string>("", path + "/include")); return; } } @@ -440,7 +436,7 @@ class CommandLineInterface::MemoryOutputStream bool append_mode_; // StringOutputStream writing to data_. - google::protobuf::scoped_ptr<io::StringOutputStream> inner_; + std::unique_ptr<io::StringOutputStream> inner_; }; // ------------------------------------------------------------------- @@ -835,10 +831,10 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) { std::vector<const FileDescriptor*> parsed_files; // null unless descriptor_set_in_names_.empty() - google::protobuf::scoped_ptr<DiskSourceTree> disk_source_tree; - google::protobuf::scoped_ptr<ErrorPrinter> error_collector; - google::protobuf::scoped_ptr<DescriptorPool> descriptor_pool; - google::protobuf::scoped_ptr<DescriptorDatabase> descriptor_database; + std::unique_ptr<DiskSourceTree> disk_source_tree; + std::unique_ptr<ErrorPrinter> error_collector; + std::unique_ptr<DescriptorPool> descriptor_pool; + std::unique_ptr<DescriptorDatabase> descriptor_database; if (descriptor_set_in_names_.empty()) { disk_source_tree.reset(new DiskSourceTree()); if (!InitializeDiskSourceTree(disk_source_tree.get())) { @@ -1395,8 +1391,7 @@ CommandLineInterface::InterpretArgument(const string& name, // with colons. Let's accept that syntax too just to make things more // intuitive. std::vector<string> parts = Split( - value, - CommandLineInterface::kPathSeparator, + value, CommandLineInterface::kPathSeparator, true); for (int i = 0; i < parts.size(); i++) { @@ -1421,7 +1416,7 @@ CommandLineInterface::InterpretArgument(const string& name, // Make sure disk path exists, warn otherwise. if (access(disk_path.c_str(), F_OK) < 0) { - // Try the original path; it may have just happed to have a '=' in it. + // Try the original path; it may have just happened to have a '=' in it. if (access(parts[i].c_str(), F_OK) < 0) { std::cerr << disk_path << ": warning: directory does not exist." << std::endl; @@ -1447,8 +1442,7 @@ CommandLineInterface::InterpretArgument(const string& name, } direct_dependencies_explicitly_set_ = true; - std::vector<string> direct = Split( - value, ":", true); + std::vector<string> direct = Split(value, ":", true); GOOGLE_DCHECK(direct_dependencies_.empty()); direct_dependencies_.insert(direct.begin(), direct.end()); @@ -1481,9 +1475,8 @@ CommandLineInterface::InterpretArgument(const string& name, } descriptor_set_in_names_ = Split( - value, - CommandLineInterface::kPathSeparator, - true); + value, CommandLineInterface::kPathSeparator, + true); } else if (name == "-o" || name == "--descriptor_set_out") { if (!descriptor_set_out_name_.empty()) { @@ -1629,7 +1622,6 @@ CommandLineInterface::InterpretArgument(const string& name, } mode_ = MODE_PRINT; print_mode_ = PRINT_FREE_FIELDS; - } else if (name == "--profile_path") { } else { // Some other flag. Look it up in the generators list. const GeneratorInfo* generator_info = @@ -1908,10 +1900,12 @@ bool CommandLineInterface::GeneratePluginOutput( string* error) { CodeGeneratorRequest request; CodeGeneratorResponse response; + string processed_parameter = parameter; + // Build the request. - if (!parameter.empty()) { - request.set_parameter(parameter); + if (!processed_parameter.empty()) { + request.set_parameter(processed_parameter); } @@ -1948,17 +1942,18 @@ bool CommandLineInterface::GeneratePluginOutput( // Write the files. We do this even if there was a generator error in order // to match the behavior of a compiled-in generator. - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> current_output; + std::unique_ptr<io::ZeroCopyOutputStream> current_output; for (int i = 0; i < response.file_size(); i++) { const CodeGeneratorResponse::File& output_file = response.file(i); if (!output_file.insertion_point().empty()) { + string filename = output_file.name(); // Open a file for insert. // We reset current_output to NULL first so that the old file is closed // before the new one is opened. current_output.reset(); current_output.reset(generator_context->OpenForInsert( - output_file.name(), output_file.insertion_point())); + filename, output_file.insertion_point())); } else if (!output_file.name().empty()) { // Starting a new file. Open it. // We reset current_output to NULL first so that the old file is closed @@ -1997,7 +1992,7 @@ bool CommandLineInterface::EncodeOrDecode(const DescriptorPool* pool) { } DynamicMessageFactory dynamic_factory(pool); - google::protobuf::scoped_ptr<Message> message(dynamic_factory.GetPrototype(type)->New()); + std::unique_ptr<Message> message(dynamic_factory.GetPrototype(type)->New()); if (mode_ == MODE_ENCODE) { SetFdToTextMode(STDIN_FILENO); diff --git a/src/google/protobuf/compiler/command_line_interface.h b/src/google/protobuf/compiler/command_line_interface.h index d5d85f2d..7d3037a9 100644 --- a/src/google/protobuf/compiler/command_line_interface.h +++ b/src/google/protobuf/compiler/command_line_interface.h @@ -413,11 +413,6 @@ class LIBPROTOC_EXPORT CommandLineInterface { // dependency file will be written. Otherwise, empty. string dependency_out_name_; - // Path to a file that contains serialized AccessInfo which provides - // relative hotness of fields per message. This helps protoc to generate - // better code. - string profile_path_; - // True if --include_imports was given, meaning that we should // write all transitive dependencies to the DescriptorSet. Otherwise, only // the .proto files listed on the command-line are added. diff --git a/src/google/protobuf/compiler/command_line_interface_unittest.cc b/src/google/protobuf/compiler/command_line_interface_unittest.cc index ef7579a2..41eb244a 100644 --- a/src/google/protobuf/compiler/command_line_interface_unittest.cc +++ b/src/google/protobuf/compiler/command_line_interface_unittest.cc @@ -40,9 +40,6 @@ #include <unistd.h> #endif #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <vector> #include <google/protobuf/stubs/stringprintf.h> @@ -344,7 +341,7 @@ void CommandLineInterfaceTest::RunWithArgs(std::vector<string> args) { } } - google::protobuf::scoped_array<const char * > argv(new const char* [args.size()]); + std::unique_ptr<const char * []> argv(new const char* [args.size()]); for (int i = 0; i < args.size(); i++) { args[i] = StringReplace(args[i], "$tmpdir", temp_directory_, true); @@ -2298,7 +2295,7 @@ class EncodeDecodeTest : public testing::TestWithParam<EncodeDecodeTestMode> { ADD_FAILURE() << "unexpected EncodeDecodeTestMode: " << GetParam(); } - google::protobuf::scoped_array<const char * > argv(new const char* [args.size()]); + std::unique_ptr<const char * []> argv(new const char* [args.size()]); for (int i = 0; i < args.size(); i++) { argv[i] = args[i].c_str(); } diff --git a/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc index f99159f5..4e150fe3 100644 --- a/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc +++ b/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc @@ -44,6 +44,7 @@ #include <map> +#include <google/protobuf/compiler/cpp/cpp_helpers.h> #include <google/protobuf/compiler/cpp/cpp_generator.h> #include <google/protobuf/compiler/importer.h> #include <google/protobuf/io/zero_copy_stream_impl.h> @@ -97,9 +98,10 @@ class MockGeneratorContext : public GeneratorContext { File::GetContents(TestSourceDir() + "/" + physical_filename, &actual_contents, true)); EXPECT_TRUE(actual_contents == *expected_contents) - << physical_filename << " needs to be regenerated. Please run " - "generate_descriptor_proto.sh. Then add this file " - "to your CL."; + << physical_filename + << " needs to be regenerated. Please run " + "generate_descriptor_proto.sh. " + "Then add this file to your CL."; } // implements GeneratorContext -------------------------------------- @@ -116,37 +118,50 @@ class MockGeneratorContext : public GeneratorContext { std::map<string, string*> files_; }; -TEST(BootstrapTest, GeneratedDescriptorMatches) { - MockErrorCollector error_collector; +const char kDescriptorParameter[] = "dllexport_decl=LIBPROTOBUF_EXPORT"; +const char kPluginParameter[] = "dllexport_decl=LIBPROTOC_EXPORT"; +const char kNormalParameter[] = ""; + +const char* test_protos[][2] = { + {"google/protobuf/descriptor", kDescriptorParameter}, + {"google/protobuf/compiler/plugin", kPluginParameter}, +}; + +TEST(BootstrapTest, GeneratedFilesMatch) { + // We need a mapping from the actual file to virtual and actual path + // of the data to compare to. + std::map<string, string> vpath_map; + std::map<string, string> rpath_map; + rpath_map["third_party/protobuf/src/google/protobuf/test_messages_proto2"] = + "net/proto2/z_generated_example/test_messages_proto2"; + rpath_map["third_party/protobuf/src/google/protobuf/test_messages_proto3"] = + "net/proto2/z_generated_example/test_messages_proto3"; + rpath_map["google/protobuf/proto2_weak"] = + "net/proto2/z_generated_example/proto2_weak"; + DiskSourceTree source_tree; source_tree.MapPath("", TestSourceDir()); - Importer importer(&source_tree, &error_collector); - const FileDescriptor* proto_file = - importer.Import("google/protobuf/descriptor.proto"); - const FileDescriptor* plugin_proto_file = - importer.Import("google/protobuf/compiler/plugin.proto"); - EXPECT_EQ("", error_collector.text_); - ASSERT_TRUE(proto_file != NULL); - ASSERT_TRUE(plugin_proto_file != NULL); - - CppGenerator generator; - MockGeneratorContext context; - string error; - string parameter = "dllexport_decl=LIBPROTOBUF_EXPORT"; - ASSERT_TRUE(generator.Generate(proto_file, parameter, - &context, &error)); - parameter = "dllexport_decl=LIBPROTOC_EXPORT"; - ASSERT_TRUE(generator.Generate(plugin_proto_file, parameter, - &context, &error)); - - context.ExpectFileMatches("google/protobuf/descriptor.pb.h", - "google/protobuf/descriptor.pb.h"); - context.ExpectFileMatches("google/protobuf/descriptor.pb.cc", - "google/protobuf/descriptor.pb.cc"); - context.ExpectFileMatches("google/protobuf/compiler/plugin.pb.h", - "google/protobuf/compiler/plugin.pb.h"); - context.ExpectFileMatches("google/protobuf/compiler/plugin.pb.cc", - "google/protobuf/compiler/plugin.pb.cc"); + + for (auto file_parameter : test_protos) { + MockErrorCollector error_collector; + Importer importer(&source_tree, &error_collector); + const FileDescriptor* file = + importer.Import(file_parameter[0] + string(".proto")); + ASSERT_TRUE(file != nullptr) + << "Can't import file " << file_parameter[0] + string(".proto") << "\n"; + EXPECT_EQ("", error_collector.text_); + CppGenerator generator; + MockGeneratorContext context; + string error; + ASSERT_TRUE(generator.Generate(file, file_parameter[1], &context, &error)); + + string vpath = + FindWithDefault(vpath_map, file_parameter[0], file_parameter[0]); + string rpath = + FindWithDefault(rpath_map, file_parameter[0], file_parameter[0]); + context.ExpectFileMatches(vpath + ".pb.cc", rpath + ".pb.cc"); + context.ExpectFileMatches(vpath + ".pb.h", rpath + ".pb.h"); + } } } // namespace diff --git a/src/google/protobuf/compiler/cpp/cpp_enum.cc b/src/google/protobuf/compiler/cpp/cpp_enum.cc index 8adee0f5..0d6a9e24 100644 --- a/src/google/protobuf/compiler/cpp/cpp_enum.cc +++ b/src/google/protobuf/compiler/cpp/cpp_enum.cc @@ -179,7 +179,7 @@ void EnumGenerator::GenerateDefinition(io::Printer* printer) { void EnumGenerator:: GenerateGetEnumDescriptorSpecializations(io::Printer* printer) { printer->Print( - "template <> struct is_proto_enum< $classname$> : ::google::protobuf::internal::true_type " + "template <> struct is_proto_enum< $classname$> : ::std::true_type " "{};\n", "classname", ClassName(descriptor_, true)); if (HasDescriptorMethods(descriptor_->file(), options_)) { diff --git a/src/google/protobuf/compiler/cpp/cpp_extension.cc b/src/google/protobuf/compiler/cpp/cpp_extension.cc index 0a4e0bb9..c416ba10 100644 --- a/src/google/protobuf/compiler/cpp/cpp_extension.cc +++ b/src/google/protobuf/compiler/cpp/cpp_extension.cc @@ -35,8 +35,8 @@ #include <google/protobuf/compiler/cpp/cpp_extension.h> #include <map> #include <google/protobuf/compiler/cpp/cpp_helpers.h> -#include <google/protobuf/io/printer.h> #include <google/protobuf/descriptor.pb.h> +#include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> @@ -120,7 +120,6 @@ void ExtensionGenerator::GenerateDeclaration(io::Printer* printer) { " ::google::protobuf::internal::$type_traits$, $field_type$, $packed$ >\n" " $name$;\n" ); - } void ExtensionGenerator::GenerateDefinition(io::Printer* printer) { diff --git a/src/google/protobuf/compiler/cpp/cpp_field.cc b/src/google/protobuf/compiler/cpp/cpp_field.cc index 0cf25b33..0de20f84 100644 --- a/src/google/protobuf/compiler/cpp/cpp_field.cc +++ b/src/google/protobuf/compiler/cpp/cpp_field.cc @@ -34,21 +34,18 @@ #include <google/protobuf/compiler/cpp/cpp_field.h> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/compiler/cpp/cpp_helpers.h> #include <google/protobuf/compiler/cpp/cpp_primitive_field.h> #include <google/protobuf/compiler/cpp/cpp_string_field.h> +#include <google/protobuf/stubs/logging.h> +#include <google/protobuf/stubs/common.h> #include <google/protobuf/compiler/cpp/cpp_enum_field.h> #include <google/protobuf/compiler/cpp/cpp_map_field.h> #include <google/protobuf/compiler/cpp/cpp_message_field.h> #include <google/protobuf/descriptor.pb.h> -#include <google/protobuf/wire_format.h> #include <google/protobuf/io/printer.h> -#include <google/protobuf/stubs/logging.h> -#include <google/protobuf/stubs/common.h> +#include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> namespace google { @@ -116,26 +113,29 @@ GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const { } FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor, - const Options& options) + const Options& options, + SCCAnalyzer* scc_analyzer) : descriptor_(descriptor), options_(options), - field_generators_( - new google::protobuf::scoped_ptr<FieldGenerator>[descriptor->field_count()]) { + field_generators_(descriptor->field_count()) { // Construct all the FieldGenerators. for (int i = 0; i < descriptor->field_count(); i++) { - field_generators_[i].reset(MakeGenerator(descriptor->field(i), options)); + field_generators_[i].reset( + MakeGenerator(descriptor->field(i), options, scc_analyzer)); } } FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field, - const Options& options) { + const Options& options, + SCCAnalyzer* scc_analyzer) { if (field->is_repeated()) { switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_MESSAGE: if (field->is_map()) { return new MapFieldGenerator(field, options); } else { - return new RepeatedMessageFieldGenerator(field, options); + return new RepeatedMessageFieldGenerator(field, options, + scc_analyzer); } case FieldDescriptor::CPPTYPE_STRING: switch (field->options().ctype()) { @@ -151,7 +151,7 @@ FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field, } else if (field->containing_oneof()) { switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_MESSAGE: - return new MessageOneofFieldGenerator(field, options); + return new MessageOneofFieldGenerator(field, options, scc_analyzer); case FieldDescriptor::CPPTYPE_STRING: switch (field->options().ctype()) { default: // StringOneofFieldGenerator handles unknown ctypes. @@ -166,7 +166,7 @@ FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field, } else { switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_MESSAGE: - return new MessageFieldGenerator(field, options); + return new MessageFieldGenerator(field, options, scc_analyzer); case FieldDescriptor::CPPTYPE_STRING: switch (field->options().ctype()) { default: // StringFieldGenerator handles unknown ctypes. diff --git a/src/google/protobuf/compiler/cpp/cpp_field.h b/src/google/protobuf/compiler/cpp/cpp_field.h index bccfcb9a..8cdbe886 100644 --- a/src/google/protobuf/compiler/cpp/cpp_field.h +++ b/src/google/protobuf/compiler/cpp/cpp_field.h @@ -37,13 +37,11 @@ #include <map> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <string> -#include <google/protobuf/descriptor.h> +#include <google/protobuf/compiler/cpp/cpp_helpers.h> #include <google/protobuf/compiler/cpp/cpp_options.h> +#include <google/protobuf/descriptor.h> namespace google { namespace protobuf { @@ -82,38 +80,12 @@ class FieldGenerator { // implementation is empty. virtual void GenerateStaticMembers(io::Printer* /*printer*/) const {} - // Generate prototypes for accessors that will manipulate imported - // messages inline. These are for .proto.h headers. - // - // In .proto.h mode, the headers of imports are not #included. However, - // functions that manipulate the imported message types need access to - // the class definition of the imported message, meaning that the headers - // must be #included. To get around this, functions that manipulate - // imported message objects are defined as dependent functions in a base - // template class. By making them dependent template functions, the - // function templates will not be instantiated until they are called, so - // we can defer to those translation units to #include the necessary - // generated headers. - // - // See: - // http://en.cppreference.com/w/cpp/language/class_template#Implicit_instantiation - // - // Most field types don't need this, so the default implementation is empty. - virtual void GenerateDependentAccessorDeclarations( - io::Printer* printer) const {} - // Generate prototypes for all of the accessor functions related to this // field. These are placed inside the class definition. virtual void GenerateAccessorDeclarations(io::Printer* printer) const = 0; - // Generate inline definitions of depenent accessor functions for this field. - // These are placed inside the header after all class definitions. - virtual void GenerateDependentInlineAccessorDefinitions( - io::Printer* printer) const {} - // Generate inline definitions of accessor functions for this field. // These are placed inside the header after all class definitions. - // In non-.proto.h mode, this generates dependent accessor functions as well. virtual void GenerateInlineAccessorDefinitions( io::Printer* printer) const = 0; @@ -207,6 +179,11 @@ class FieldGenerator { // are placed in the message's ByteSize() method. virtual void GenerateByteSize(io::Printer* printer) const = 0; + // Any tags about field layout decisions (such as inlining) to embed in the + // offset. + virtual uint32 CalculateFieldTag() const { return 0; } + virtual bool IsInlined() const { return false; } + protected: const Options& options_; @@ -217,7 +194,8 @@ class FieldGenerator { // Convenience class which constructs FieldGenerators for a Descriptor. class FieldGeneratorMap { public: - FieldGeneratorMap(const Descriptor* descriptor, const Options& options); + FieldGeneratorMap(const Descriptor* descriptor, const Options& options, + SCCAnalyzer* scc_analyzer); ~FieldGeneratorMap(); const FieldGenerator& get(const FieldDescriptor* field) const; @@ -225,10 +203,11 @@ class FieldGeneratorMap { private: const Descriptor* descriptor_; const Options& options_; - google::protobuf::scoped_array<google::protobuf::scoped_ptr<FieldGenerator> > field_generators_; + std::vector<std::unique_ptr<FieldGenerator>> field_generators_; static FieldGenerator* MakeGenerator(const FieldDescriptor* field, - const Options& options); + const Options& options, + SCCAnalyzer* scc_analyzer); GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap); }; diff --git a/src/google/protobuf/compiler/cpp/cpp_file.cc b/src/google/protobuf/compiler/cpp/cpp_file.cc index a922ee97..02f360bb 100644 --- a/src/google/protobuf/compiler/cpp/cpp_file.cc +++ b/src/google/protobuf/compiler/cpp/cpp_file.cc @@ -35,20 +35,17 @@ #include <google/protobuf/compiler/cpp/cpp_file.h> #include <map> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <set> #include <vector> #include <google/protobuf/compiler/cpp/cpp_enum.h> -#include <google/protobuf/compiler/cpp/cpp_service.h> #include <google/protobuf/compiler/cpp/cpp_extension.h> +#include <google/protobuf/compiler/cpp/cpp_field.h> #include <google/protobuf/compiler/cpp/cpp_helpers.h> #include <google/protobuf/compiler/cpp/cpp_message.h> -#include <google/protobuf/compiler/cpp/cpp_field.h> -#include <google/protobuf/io/printer.h> +#include <google/protobuf/compiler/cpp/cpp_service.h> #include <google/protobuf/descriptor.pb.h> +#include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> namespace google { @@ -61,11 +58,11 @@ FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options) options_(options), scc_analyzer_(options), enum_generators_owner_( - new google::protobuf::scoped_ptr<EnumGenerator>[file->enum_type_count()]), + new std::unique_ptr<EnumGenerator>[file->enum_type_count()]), service_generators_owner_( - new google::protobuf::scoped_ptr<ServiceGenerator>[file->service_count()]), + new std::unique_ptr<ServiceGenerator>[file->service_count()]), extension_generators_owner_( - new google::protobuf::scoped_ptr<ExtensionGenerator>[file->extension_count()]) { + new std::unique_ptr<ExtensionGenerator>[file->extension_count()]) { std::vector<const Descriptor*> msgs = FlattenMessagesInFile(file); for (int i = 0; i < msgs.size(); i++) { // Deleted in destructor @@ -141,6 +138,9 @@ void FileGenerator::GenerateHeader(io::Printer* printer) { printer->Print( "// @@protoc_insertion_point(includes)\n"); + printer->Print("#define PROTOBUF_INTERNAL_EXPORT_$filename$ $export$\n", + "filename", FileLevelNamespace(file_), + "export", options_.dllexport_decl); GenerateMacroUndefs(printer); GenerateGlobalStateFunctionDeclarations(printer); @@ -223,8 +223,9 @@ void FileGenerator::GeneratePBHeader(io::Printer* printer, GenerateTopHeaderGuard(printer, filename_identifier); if (options_.proto_h) { + string target_basename = StripProto(file_->name()); printer->Print("#include \"$basename$.proto.h\" // IWYU pragma: export\n", - "basename", StripProto(file_->name())); + "basename", target_basename); } else { GenerateLibraryIncludes(printer); } @@ -256,9 +257,10 @@ void FileGenerator::GeneratePBHeader(io::Printer* printer, } void FileGenerator::GenerateSourceIncludes(io::Printer* printer) { + string target_basename = StripProto(file_->name()); const bool use_system_include = IsWellKnownMessage(file_); - string header = - StripProto(file_->name()) + (options_.proto_h ? ".proto.h" : ".pb.h"); + + string header = target_basename + (options_.proto_h ? ".proto.h" : ".pb.h"); printer->Print( "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" "// source: $filename$\n" @@ -269,7 +271,6 @@ void FileGenerator::GenerateSourceIncludes(io::Printer* printer) { "\n" "#include <google/protobuf/stubs/common.h>\n" "#include <google/protobuf/stubs/port.h>\n" - "#include <google/protobuf/stubs/once.h>\n" "#include <google/protobuf/io/coded_stream.h>\n" "#include <google/protobuf/wire_format_lite_inl.h>\n", "filename", file_->name(), @@ -296,7 +297,8 @@ void FileGenerator::GenerateSourceIncludes(io::Printer* printer) { for (int i = 0; i < file_->dependency_count(); i++) { const FileDescriptor* dep = file_->dependency(i); const char* extension = ".proto.h"; - string dependency = StripProto(dep->name()) + extension; + string basename = StripProto(dep->name()); + string dependency = basename + extension; printer->Print( "#include \"$dependency$\"\n", "dependency", dependency); @@ -338,33 +340,34 @@ namespace { // Generates weak symbol declarations for types that are to be considered weakly // referenced. -void GenerateWeakDeclarations( - const FileDescriptor* file, const Options& options, - SCCAnalyzer* scc_analyzer, - io::Printer* printer) { - std::vector<const FieldDescriptor*> fields; - ListAllFields(file, &fields); - +void GenerateInternalForwardDeclarations( + const std::vector<const FieldDescriptor*>& fields, const Options& options, + SCCAnalyzer* scc_analyzer, io::Printer* printer) { // To ensure determinism and minimize the number of namespace statements, // we output the forward declarations sorted on namespace and type / function // name. std::set<std::pair<string, string> > messages; + std::set<std::pair<string, string> > sccs; std::set<std::pair<string, string> > inits; for (int i = 0; i < fields.size(); ++i) { const FieldDescriptor* field = fields[i]; - bool is_weak = IsImplicitWeakField(field, options); + const Descriptor* msg = field->message_type(); + if (msg == nullptr) continue; + bool is_weak = IsImplicitWeakField(field, options, scc_analyzer); + string flns = FileLevelNamespace(msg); + auto scc = scc_analyzer->GetSCC(msg); + string repr = ClassName(scc->GetRepresentative()); + string weak_attr; if (is_weak) { - const Descriptor* msg = field->message_type(); - string flns = FileLevelNamespace(msg); - string repr = ClassName(scc_analyzer->GetSCC(msg)->GetRepresentative()); - inits.insert(std::make_pair(flns, "InitDefaults" + repr)); inits.insert(std::make_pair(flns, "AddDescriptors")); messages.insert(std::make_pair(Namespace(msg), ClassName(msg))); + weak_attr = " __attribute__((weak))"; } - } - - if (messages.empty()) { - return; + string dllexport = "PROTOBUF_INTERNAL_EXPORT_" + FileLevelNamespace(msg); + sccs.insert(std::make_pair(flns, "extern " + dllexport + weak_attr + + " ::google::protobuf::internal::SCCInfo<" + + SimpleItoa(scc->children.size()) + + "> scc_info_" + repr + ";\n")); } printer->Print("\n"); @@ -384,13 +387,33 @@ void GenerateWeakDeclarations( printer->Print("void $name$() __attribute__((weak));\n", "name", it->second); } + for (const auto& p : sccs) { + ns.ChangeTo(p.first); + printer->Print(p.second.c_str()); + } } } // namespace void FileGenerator::GenerateSourceForMessage(int idx, io::Printer* printer) { GenerateSourceIncludes(printer); - GenerateWeakDeclarations(file_, options_, &scc_analyzer_, printer); + + // Generate weak declarations. We do this for the whole strongly-connected + // component (SCC), because we have a single InitDefaults* function for the + // SCC. + std::vector<const FieldDescriptor*> fields; + for (const Descriptor* message : + scc_analyzer_.GetSCC(message_generators_[idx]->descriptor_) + ->descriptors) { + ListAllFields(message, &fields); + } + GenerateInternalForwardDeclarations(fields, options_, &scc_analyzer_, + printer); + + if (IsSCCRepresentative(message_generators_[idx]->descriptor_)) { + NamespaceOpener ns(FileLevelNamespace(file_), printer); + GenerateInitForSCC(GetSCC(message_generators_[idx]->descriptor_), printer); + } { // package namespace NamespaceOpener ns(Namespace(file_), printer); @@ -411,12 +434,6 @@ void FileGenerator::GenerateSourceForMessage(int idx, io::Printer* printer) { "// @@protoc_insertion_point(namespace_scope)\n"); } // end package namespace - if (IsSCCRepresentative(message_generators_[idx]->descriptor_)) { - NamespaceOpener ns(FileLevelNamespace(file_), printer); - GenerateInitForSCC(GetSCC(message_generators_[idx]->descriptor_), printer); - } - - printer->Print( "namespace google {\nnamespace protobuf {\n"); message_generators_[idx]->GenerateSourceInProto2Namespace(printer); @@ -430,15 +447,16 @@ void FileGenerator::GenerateSourceForMessage(int idx, io::Printer* printer) { void FileGenerator::GenerateGlobalSource(io::Printer* printer) { GenerateSourceIncludes(printer); - GenerateWeakDeclarations(file_, options_, &scc_analyzer_, printer); - // TODO(gerbens) Generate tables here - - // Define the code to initialize reflection. This code uses a global - // constructor to register reflection data with the runtime pre-main. - if (HasDescriptorMethods(file_, options_)) { + { NamespaceOpener ns(FileLevelNamespace(file_), printer); - GenerateReflectionInitializationCode(printer); + GenerateTables(printer); + + // Define the code to initialize reflection. This code uses a global + // constructor to register reflection data with the runtime pre-main. + if (HasDescriptorMethods(file_, options_)) { + GenerateReflectionInitializationCode(printer); + } } NamespaceOpener ns(Namespace(file_), printer); @@ -466,7 +484,10 @@ void FileGenerator::GenerateGlobalSource(io::Printer* printer) { void FileGenerator::GenerateSource(io::Printer* printer) { GenerateSourceIncludes(printer); - GenerateWeakDeclarations(file_, options_, &scc_analyzer_, printer); + std::vector<const FieldDescriptor*> fields; + ListAllFields(file_, &fields); + GenerateInternalForwardDeclarations(fields, options_, &scc_analyzer_, + printer); { NamespaceOpener ns(Namespace(file_), printer); @@ -483,9 +504,25 @@ void FileGenerator::GenerateSource(io::Printer* printer) { { NamespaceOpener ns(FileLevelNamespace(file_), printer); - // Define the initialization code to initialize the default instances. - // This code doesn't use a global constructor. - GenerateInitializationCode(printer); + GenerateTables(printer); + + // Now generate the InitDefaults for each SCC. + for (int i = 0; i < message_generators_.size(); i++) { + if (IsSCCRepresentative(message_generators_[i]->descriptor_)) { + GenerateInitForSCC(GetSCC(message_generators_[i]->descriptor_), + printer); + } + } + + printer->Print("void InitDefaults() {\n"); + for (int i = 0; i < message_generators_.size(); i++) { + if (!IsSCCRepresentative(message_generators_[i]->descriptor_)) continue; + string scc_name = ClassName(message_generators_[i]->descriptor_); + printer->Print( + " ::google::protobuf::internal::InitSCC(&scc_info_$scc_name$.base);\n", + "scc_name", scc_name); + } + printer->Print("}\n\n"); // Define the code to initialize reflection. This code uses a global // constructor to register reflection data with the runtime pre-main. @@ -560,7 +597,7 @@ class FileGenerator::ForwardDeclarations { ForwardDeclarations* AddOrGetNamespace(const string& ns_name) { ForwardDeclarations*& ns = namespaces_[ns_name]; - if (ns == NULL) { + if (ns == nullptr) { ns = new ForwardDeclarations; } return ns; @@ -648,17 +685,12 @@ class FileGenerator::ForwardDeclarations { end = classes_.end(); it != end; ++it) { const Descriptor* d = it->second; - string extra_class_qualifier; - // "class" is to disambiguate in case there is also a function with this - // name. There is code out there that does this! printer->Print( "template<> " "$dllexport_decl$" - "$class$$classname$* Arena::$func$< $class$$classname$>(Arena*);\n", - "classname", QualifiedClassName(d), - "func", MessageCreateFunction(d), - "class", extra_class_qualifier, - "dllexport_decl", + "$classname$* Arena::CreateMaybeMessage<$classname$>" + "(Arena*);\n", + "classname", QualifiedClassName(d), "dllexport_decl", options.dllexport_decl.empty() ? "" : options.dllexport_decl + " "); } printer->Print( @@ -758,18 +790,16 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) { // protobuf_AssignDescriptorsOnce(): The first time it is called, calls // AssignDescriptors(). All later times, waits for the first call to // complete and then returns. - string message_factory = "NULL"; printer->Print( - "void protobuf_AssignDescriptors() {\n" + "static void protobuf_AssignDescriptors() {\n" // Make sure the file has found its way into the pool. If a descriptor // is requested *during* static init then AddDescriptors() may not have // been called yet, so we call it manually. Note that it's fine if // AddDescriptors() is called multiple times. " AddDescriptors();\n" - " ::google::protobuf::MessageFactory* factory = $factory$;\n" " AssignDescriptors(\n" " \"$filename$\", schemas, file_default_instances, " - "TableStruct::offsets, factory,\n" + "TableStruct::offsets,\n" " $metadata$, $enum_descriptors$, $service_descriptors$);\n", "filename", file_->name(), "metadata", !message_generators_.empty() ? "file_level_metadata" : "NULL", @@ -778,14 +808,13 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) { "service_descriptors", HasGenericServices(file_, options_) && file_->service_count() > 0 ? "file_level_service_descriptors" - : "NULL", - "factory", message_factory); + : "NULL"); printer->Print( "}\n" "\n" - "void protobuf_AssignDescriptorsOnce() {\n" - " static GOOGLE_PROTOBUF_DECLARE_ONCE(once);\n" - " ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);\n" + "static void protobuf_AssignDescriptorsOnce() {\n" + " static ::google::protobuf::internal::once_flag once;\n" + " ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);\n" "}\n" "\n", "filename", file_->name(), "metadata", @@ -795,8 +824,7 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) { "service_descriptors", HasGenericServices(file_, options_) && file_->service_count() > 0 ? "file_level_service_descriptors" - : "NULL", - "factory", message_factory); + : "NULL"); // Only here because of useless string reference that we don't want in // protobuf_AssignDescriptorsOnce, because that is called from all the @@ -822,7 +850,7 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) { // Now generate the AddDescriptors() function. printer->Print( - "void AddDescriptorsImpl() {\n" + "static void AddDescriptorsImpl() {\n" " InitDefaults();\n"); printer->Indent(); @@ -891,8 +919,8 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) { "}\n" "\n" "void AddDescriptors() {\n" - " static GOOGLE_PROTOBUF_DECLARE_ONCE(once);\n" - " ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);\n" + " static ::google::protobuf::internal::once_flag once;\n" + " ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);\n" "}\n"); printer->Print( @@ -907,47 +935,16 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) { void FileGenerator::GenerateInitForSCC(const SCC* scc, io::Printer* printer) { const string scc_name = ClassName(scc->GetRepresentative()); + // We use static and not anonymous namespace because symbol names are + // substantially shorter. printer->Print( - "void InitDefaults$scc_name$Impl() {\n" + "static void InitDefaults$scc_name$() {\n" " GOOGLE_PROTOBUF_VERIFY_VERSION;\n\n" - "#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS\n" - " ::google::protobuf::internal::InitProtobufDefaultsForceUnique();\n" - "#else\n" - " ::google::protobuf::internal::InitProtobufDefaults();\n" - "#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS\n", - // Force initialization of primitive values we depend on. + , // awkward comma due to macro "scc_name", scc_name); printer->Indent(); - // Call the InitDefaults() methods for all of our dependencies, to make - // sure they get added first. - for (int i = 0; i < scc->children.size(); i++) { - const SCC* child_scc = scc->children[i]; - const FileDescriptor* dependency = child_scc->GetRepresentative()->file(); - // Print the namespace prefix for the dependency. - string file_namespace = FileLevelNamespace(dependency); - std::map<string, string> variables; - variables["file_namespace"] = file_namespace; - variables["scc_name"] = ClassName(child_scc->GetRepresentative(), false); - bool using_weak_fields = UsingImplicitWeakFields(file_, options_); - if (using_weak_fields) { - // We're building for lite with implicit weak fields, so we need to handle - // the possibility that this InitDefaults function is not linked into the - // binary. Some of these might actually be guaranteed to be non-null since - // we might have a strong reference to the dependency (via a required - // field, for example), but it's simplest to just assume that any of them - // could be null. - printer->Print( - variables, - "if (&$file_namespace$::InitDefaults$scc_name$ != NULL) {\n" - " $file_namespace$::InitDefaults$scc_name$();\n" - "}\n"); - } else { - printer->Print(variables, - "$file_namespace$::InitDefaults$scc_name$();\n"); - } - } // First construct all the necessary default instances. for (int i = 0; i < message_generators_.size(); i++) { @@ -982,23 +979,24 @@ void FileGenerator::GenerateInitForSCC(const SCC* scc, io::Printer* printer) { } printer->Outdent(); printer->Print("}\n\n"); + printer->Print( - "void InitDefaults$scc_name$() {\n" - " static GOOGLE_PROTOBUF_DECLARE_ONCE(once);\n" - " ::google::protobuf::GoogleOnceInit(&once, " - "&InitDefaults$scc_name$Impl);\n" - "}\n\n", - "scc_name", scc_name); + "$dllexport_decl$::google::protobuf::internal::SCCInfo<$size$> " + "scc_info_$scc_name$ =\n" + " {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), " + "$size$, InitDefaults$scc_name$}, {", + "size", SimpleItoa(scc->children.size()), "scc_name", + ClassName(scc->GetRepresentative()), "dllexport_decl", + options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " "); + for (const SCC* child : scc->children) { + auto repr = child->GetRepresentative(); + printer->Print("\n &$ns$::scc_info_$child$.base,", "ns", + FileLevelNamespace(repr), "child", ClassName(repr)); + } + printer->Print("}};\n\n"); } -void FileGenerator::GenerateInitializationCode(io::Printer* printer) { - // Messages depend on the existence of a default instance, which has to - // initialized properly. The default instances are allocated in the data - // segment, but we can't quite allocate the type directly. The destructors - // cannot run at program exit as this could lead to segfaults in a threaded - // environment. Hence these instances must be inplace constructed at first - // use. - +void FileGenerator::GenerateTables(io::Printer* printer) { if (options_.table_driven_parsing) { // TODO(ckennelly): Gate this with the same options flag to enable // table-driven parsing. @@ -1105,16 +1103,6 @@ void FileGenerator::GenerateInitializationCode(io::Printer* printer) { "};\n" "\n"); } - - // ----------------------------------------------------------------- - // All functionality that need private access. - - // Now generate the InitDefaults for each SCC. - for (int i = 0; i < message_generators_.size(); i++) { - if (IsSCCRepresentative(message_generators_[i]->descriptor_)) { - GenerateInitForSCC(GetSCC(message_generators_[i]->descriptor_), printer); - } - } } void FileGenerator::GenerateForwardDeclarations(io::Printer* printer) { @@ -1145,8 +1133,8 @@ void FileGenerator::GenerateTopHeaderGuard(io::Printer* printer, "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" "// source: $filename$\n" "\n" - "#ifndef PROTOBUF_$filename_identifier$_INCLUDED\n" - "#define PROTOBUF_$filename_identifier$_INCLUDED\n" + "#ifndef PROTOBUF_INCLUDED_$filename_identifier$\n" + "#define PROTOBUF_INCLUDED_$filename_identifier$\n" "\n" "#include <string>\n", "filename", file_->name(), "filename_identifier", filename_identifier); @@ -1156,7 +1144,7 @@ void FileGenerator::GenerateTopHeaderGuard(io::Printer* printer, void FileGenerator::GenerateBottomHeaderGuard( io::Printer* printer, const string& filename_identifier) { printer->Print( - "#endif // PROTOBUF_$filename_identifier$_INCLUDED\n", + "#endif // PROTOBUF_INCLUDED_$filename_identifier$\n", "filename_identifier", filename_identifier); } @@ -1193,7 +1181,9 @@ void FileGenerator::GenerateLibraryIncludes(io::Printer* printer) { "#include <google/protobuf/arena.h>\n" "#include <google/protobuf/arenastring.h>\n" "#include <google/protobuf/generated_message_table_driven.h>\n" - "#include <google/protobuf/generated_message_util.h>\n"); + "#include <google/protobuf/generated_message_util.h>\n" + "#include <google/protobuf/inlined_string_field.h>\n"); + if (HasDescriptorMethods(file_, options_)) { printer->Print( @@ -1280,11 +1270,12 @@ void FileGenerator::GenerateDependencyIncludes(io::Printer* printer) { const bool use_system_include = IsWellKnownMessage(file_->dependency(i)); const string& name = file_->dependency(i)->name(); bool public_import = (public_import_names.count(name) != 0); + string basename = StripProto(name); printer->Print( "#include $left$$dependency$.pb.h$right$$iwyu$\n", - "dependency", StripProto(name), + "dependency", basename, "iwyu", (public_import) ? " // IWYU pragma: export" : "", "left", use_system_include ? "<" : "\"", "right", use_system_include ? ">" : "\""); @@ -1318,28 +1309,6 @@ void FileGenerator::GenerateGlobalStateFunctionDeclarations( "void $dllexport_decl$AddDescriptors();\n", "dllexport_decl", options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " "); } - for (int i = 0; i < message_generators_.size(); i++) { - if (!IsSCCRepresentative(message_generators_[i]->descriptor_)) continue; - string scc_name = ClassName(message_generators_[i]->descriptor_); - // TODO(gerbens) Remove the Impl from header. This is solely because - // it currently still needs to be a friend of the protos. - printer->Print( - "void $dllexport_decl$InitDefaults$scc_name$Impl();\n" - "void $dllexport_decl$InitDefaults$scc_name$();\n", - "scc_name", scc_name, "dllexport_decl", - options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " "); - } - // TODO(gerbens) This is for proto1 interoperability. Remove when proto1 - // is gone. - printer->Print( - "inline void $dllexport_decl$InitDefaults() {\n", "dllexport_decl", - options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " "); - for (int i = 0; i < message_generators_.size(); i++) { - if (!IsSCCRepresentative(message_generators_[i]->descriptor_)) continue; - string scc_name = ClassName(message_generators_[i]->descriptor_); - printer->Print(" InitDefaults$scc_name$();\n", "scc_name", scc_name); - } - printer->Print("}\n"); printer->Print( "} // namespace $file_namespace$\n", "file_namespace", FileLevelNamespace(file_)); @@ -1416,8 +1385,6 @@ void FileGenerator::GenerateInlineFunctionDefinitions(io::Printer* printer) { printer->Print(kThinSeparator); printer->Print("\n"); } - // Methods of the dependent base class must always be inline in the header. - message_generators_[i]->GenerateDependentInlineMethods(printer); } } diff --git a/src/google/protobuf/compiler/cpp/cpp_file.h b/src/google/protobuf/compiler/cpp/cpp_file.h index 7e61cbad..94da9a14 100644 --- a/src/google/protobuf/compiler/cpp/cpp_file.h +++ b/src/google/protobuf/compiler/cpp/cpp_file.h @@ -37,9 +37,6 @@ #include <algorithm> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <set> #include <string> #include <vector> @@ -97,7 +94,7 @@ class FileGenerator { void GenerateSourceDefaultInstance(int idx, io::Printer* printer); void GenerateInitForSCC(const SCC* scc, io::Printer* printer); - void GenerateInitializationCode(io::Printer* printer); + void GenerateTables(io::Printer* printer); void GenerateReflectionInitializationCode(io::Printer* printer); // For other imports, generates their forward-declarations. @@ -176,10 +173,10 @@ class FileGenerator { // These members are just for owning (and thus proper deleting). // Nested (enum/extension)_generators are owned by child messages. - google::protobuf::scoped_array<google::protobuf::scoped_ptr<EnumGenerator> > enum_generators_owner_; - google::protobuf::scoped_array<google::protobuf::scoped_ptr<ServiceGenerator> > + std::unique_ptr<std::unique_ptr<EnumGenerator> []> enum_generators_owner_; + std::unique_ptr<std::unique_ptr<ServiceGenerator> []> service_generators_owner_; - google::protobuf::scoped_array<google::protobuf::scoped_ptr<ExtensionGenerator> > + std::unique_ptr<std::unique_ptr<ExtensionGenerator> []> extension_generators_owner_; // E.g. if the package is foo.bar, package_parts_ is {"foo", "bar"}. diff --git a/src/google/protobuf/compiler/cpp/cpp_generator.cc b/src/google/protobuf/compiler/cpp/cpp_generator.cc index 5d8ea300..20bb8a1a 100644 --- a/src/google/protobuf/compiler/cpp/cpp_generator.cc +++ b/src/google/protobuf/compiler/cpp/cpp_generator.cc @@ -36,17 +36,15 @@ #include <vector> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <utility> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/compiler/cpp/cpp_file.h> #include <google/protobuf/compiler/cpp/cpp_helpers.h> +#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/io/zero_copy_stream.h> -#include <google/protobuf/descriptor.pb.h> + namespace google { namespace protobuf { @@ -66,12 +64,6 @@ bool CppGenerator::Generate(const FileDescriptor* file, // ----------------------------------------------------------------- // parse generator options - // TODO(kenton): If we ever have more options, we may want to create a - // class that encapsulates them which we can pass down to all the - // generator classes. Currently we pass dllexport_decl down to all of - // them via the constructors, but we don't want to have to add another - // constructor parameter for every option. - // If the dllexport_decl option is passed to the compiler, we need to write // it in front of every symbol that should be exported if this .proto is // compiled into a Windows DLL. E.g., if the user invokes the protocol @@ -127,11 +119,12 @@ bool CppGenerator::Generate(const FileDescriptor* file, string basename = StripProto(file->name()); + FileGenerator file_generator(file, file_options); // Generate header(s). if (file_options.proto_h) { - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( generator_context->Open(basename + ".proto.h")); GeneratedCodeInfo annotations; io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector( @@ -143,14 +136,14 @@ bool CppGenerator::Generate(const FileDescriptor* file, file_generator.GenerateProtoHeader( &printer, file_options.annotate_headers ? info_path : ""); if (file_options.annotate_headers) { - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output( + std::unique_ptr<io::ZeroCopyOutputStream> info_output( generator_context->Open(info_path)); annotations.SerializeToZeroCopyStream(info_output.get()); } } { - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( generator_context->Open(basename + ".pb.h")); GeneratedCodeInfo annotations; io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector( @@ -162,7 +155,7 @@ bool CppGenerator::Generate(const FileDescriptor* file, file_generator.GeneratePBHeader( &printer, file_options.annotate_headers ? info_path : ""); if (file_options.annotate_headers) { - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output( + std::unique_ptr<io::ZeroCopyOutputStream> info_output( generator_context->Open(info_path)); annotations.SerializeToZeroCopyStream(info_output.get()); } @@ -172,7 +165,7 @@ bool CppGenerator::Generate(const FileDescriptor* file, if (UsingImplicitWeakFields(file, file_options)) { { // This is the global .cc file, containing enum/services/tables/reflection - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( generator_context->Open(basename + ".pb.cc")); io::Printer printer(output.get(), '$'); file_generator.GenerateGlobalSource(&printer); @@ -191,7 +184,7 @@ bool CppGenerator::Generate(const FileDescriptor* file, } for (int i = 0; i < num_cc_files; i++) { // TODO(gerbens) Agree on naming scheme. - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( generator_context->Open(basename + "." + SimpleItoa(i) + ".cc")); io::Printer printer(output.get(), '$'); if (i < file_generator.NumMessages()) { @@ -199,7 +192,7 @@ bool CppGenerator::Generate(const FileDescriptor* file, } } } else { - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( generator_context->Open(basename + ".pb.cc")); io::Printer printer(output.get(), '$'); file_generator.GenerateSource(&printer); diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.cc b/src/google/protobuf/compiler/cpp/cpp_helpers.cc index 172acedd..163dac0a 100644 --- a/src/google/protobuf/compiler/cpp/cpp_helpers.cc +++ b/src/google/protobuf/compiler/cpp/cpp_helpers.cc @@ -42,6 +42,7 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/compiler/cpp/cpp_helpers.h> #include <google/protobuf/io/printer.h> +#include <google/protobuf/io/zero_copy_stream.h> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/substitute.h> @@ -73,7 +74,7 @@ const char* const kKeywordList[] = { "constexpr", "const_cast", "continue", "decltype", "default", "delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", "float", "for", "friend", "goto", "if", "inline", "int", "long", - "mutable", "namespace", "new", "noexcept", "not", "not_eq", "NULL", + "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr", "operator", "or", "or_eq", "private", "protected", "public", "register", "reinterpret_cast", "return", "short", "signed", "sizeof", "static", "static_assert", "static_cast", "struct", "switch", "template", "this", @@ -219,24 +220,12 @@ string ReferenceFunctionName(const Descriptor* descriptor) { return QualifiedClassName(descriptor) + "_ReferenceStrong"; } -string DependentBaseClassTemplateName(const Descriptor* descriptor) { - return ClassName(descriptor, false) + "_InternalBase"; -} - string SuperClassName(const Descriptor* descriptor, const Options& options) { return HasDescriptorMethods(descriptor->file(), options) ? "::google::protobuf::Message" : "::google::protobuf::MessageLite"; } -string DependentBaseDownCast() { - return "reinterpret_cast<T*>(this)->"; -} - -string DependentBaseConstDownCast() { - return "reinterpret_cast<const T*>(this)->"; -} - string FieldName(const FieldDescriptor* field) { string result = field->name(); LowerString(&result); @@ -294,60 +283,6 @@ string FieldConstantName(const FieldDescriptor *field) { return result; } -bool IsFieldDependent(const FieldDescriptor* field) { - if (field->containing_oneof() != NULL && - field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) { - return true; - } - if (field->is_map()) { - const Descriptor* map_descriptor = field->message_type(); - for (int i = 0; i < map_descriptor->field_count(); i++) { - if (IsFieldDependent(map_descriptor->field(i))) { - return true; - } - } - return false; - } - if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) { - return false; - } - if (field->containing_oneof() != NULL) { - // Oneof fields will always be dependent. - // - // This is a unique case for field codegen. Field generators are - // responsible for generating all the field-specific accessor - // functions, except for the clear_*() function; instead, field - // generators produce inline clearing code. - // - // For non-oneof fields, the Message class uses the inline clearing - // code to define the field's clear_*() function, as well as in the - // destructor. For oneof fields, the Message class generates a much - // more complicated clear_*() function, which clears only the oneof - // member that is set, in addition to clearing methods for each of the - // oneof members individually. - // - // Since oneofs do not have their own generator class, the Message code - // generation logic would be significantly complicated in order to - // split dependent and non-dependent manipulation logic based on - // whether the oneof truly needs to be dependent; so, for oneof fields, - // we just assume it (and its constituents) should be manipulated by a - // dependent base class function. - // - // This is less precise than how dependent message-typed fields are - // handled, but the cost is limited to only the generated code for the - // oneof field, which seems like an acceptable tradeoff. - return true; - } - if (field->file() == field->message_type()->file()) { - return false; - } - return true; -} - -string DependentTypeName(const FieldDescriptor* field) { - return "InternalBase_" + field->name() + "_T"; -} - string FieldMessageTypeName(const FieldDescriptor* field) { // Note: The Google-internal version of Protocol Buffers uses this function // as a hook point for hacks to support legacy code. @@ -748,12 +683,17 @@ bool UsingImplicitWeakFields(const FileDescriptor* file, GetOptimizeFor(file, options) == FileOptions::LITE_RUNTIME; } - -bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options) { +bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options, + SCCAnalyzer* scc_analyzer) { return UsingImplicitWeakFields(field->file(), options) && field->type() == FieldDescriptor::TYPE_MESSAGE && !field->is_required() && !field->is_map() && - field->containing_oneof() == NULL; + field->containing_oneof() == NULL && + !IsWellKnownMessage(field->message_type()->file()) && + // We do not support implicit weak fields between messages in the same + // strongly-connected component. + scc_analyzer->GetSCC(field->containing_type()) != + scc_analyzer->GetSCC(field->message_type()); } struct CompareDescriptors { @@ -920,6 +860,7 @@ void ListAllTypesForServices(const FileDescriptor* fd, } } + } // namespace cpp } // namespace compiler } // namespace protobuf diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.h b/src/google/protobuf/compiler/cpp/cpp_helpers.h index 4026d0ed..eac65124 100644 --- a/src/google/protobuf/compiler/cpp/cpp_helpers.h +++ b/src/google/protobuf/compiler/cpp/cpp_helpers.h @@ -38,8 +38,9 @@ #include <map> #include <string> #include <google/protobuf/compiler/cpp/cpp_options.h> -#include <google/protobuf/io/printer.h> +#include <google/protobuf/compiler/code_generator.h> #include <google/protobuf/descriptor.pb.h> +#include <google/protobuf/io/printer.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/stubs/strutil.h> @@ -53,6 +54,7 @@ namespace cpp { extern const char kThickSeparator[]; extern const char kThinSeparator[]; + // Name space of the proto file. This namespace is such that the string // "<namespace>::some_name" is the correct fully qualified namespace. // This means if the package is empty the namespace is "", and otherwise @@ -102,19 +104,9 @@ string DefaultInstanceName(const Descriptor* descriptor); // fields. string ReferenceFunctionName(const Descriptor* descriptor); -// Name of the CRTP class template (for use with proto_h). -// This is a class name, like "ProtoName_InternalBase". -string DependentBaseClassTemplateName(const Descriptor* descriptor); - -// Name of the base class: either the dependent base class (for use with -// proto_h) or google::protobuf::Message. +// Name of the base class: google::protobuf::Message or google::protobuf::MessageLite. string SuperClassName(const Descriptor* descriptor, const Options& options); -// Returns a string that down-casts from the dependent base class to the -// derived class. -string DependentBaseDownCast(); -string DependentBaseConstDownCast(); - // Get the (unqualified) name that should be used for this field in C++ code. // The name is coerced to lower-case to emulate proto1 behavior. People // should be using lowercase-with-underscores style for proto field names @@ -141,20 +133,6 @@ inline const Descriptor* FieldScope(const FieldDescriptor* field) { field->extension_scope() : field->containing_type(); } -// Returns true if the given 'field_descriptor' has a message type that is -// a dependency of the file where the field is defined (i.e., the field -// type is defined in a different file than the message holding the field). -// -// This only applies to Message-typed fields. Enum-typed fields may refer -// to an enum in a dependency; however, enums are specified and -// forward-declared with an enum-base, so the definition is not required to -// manipulate the field value. -bool IsFieldDependent(const FieldDescriptor* field_descriptor); - -// Returns the name that should be used for forcing dependent lookup from a -// dependent base class. -string DependentTypeName(const FieldDescriptor* field); - // Returns the fully-qualified type name field->message_type(). Usually this // is just ClassName(field->message_type(), true); string FieldMessageTypeName(const FieldDescriptor* field); @@ -314,6 +292,11 @@ inline string MessageCreateFunction(const Descriptor* d) { return SupportsArenas(d) ? "CreateMessage" : "Create"; } +inline string MakeDefaultName(const FieldDescriptor* field) { + return "_i_give_permission_to_break_this_code_default_" + FieldName(field) + + "_"; +} + bool IsAnyMessage(const FileDescriptor* descriptor); bool IsAnyMessage(const Descriptor* descriptor); @@ -350,13 +333,6 @@ inline std::vector<const Descriptor*> FlattenMessagesInFile( bool HasWeakFields(const Descriptor* desc); bool HasWeakFields(const FileDescriptor* desc); -// Indicates whether we should use implicit weak fields for this file. -bool UsingImplicitWeakFields(const FileDescriptor* file, - const Options& options); - -// Indicates whether to treat this field as implicitly weak. -bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options); - // Returns true if the "required" restriction check should be ignored for the // given field. inline static bool ShouldIgnoreRequiredFieldCheck(const FieldDescriptor* field, @@ -462,11 +438,21 @@ class LIBPROTOC_EXPORT SCCAnalyzer { void AddChildren(SCC* scc); }; +void ListAllFields(const Descriptor* d, + std::vector<const FieldDescriptor*>* fields); void ListAllFields(const FileDescriptor* d, std::vector<const FieldDescriptor*>* fields); void ListAllTypesForServices(const FileDescriptor* fd, std::vector<const Descriptor*>* types); +// Indicates whether we should use implicit weak fields for this file. +bool UsingImplicitWeakFields(const FileDescriptor* file, + const Options& options); + +// Indicates whether to treat this field as implicitly weak. +bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options, + SCCAnalyzer* scc_analyzer); + } // namespace cpp } // namespace compiler } // namespace protobuf diff --git a/src/google/protobuf/compiler/cpp/cpp_map_field.cc b/src/google/protobuf/compiler/cpp/cpp_map_field.cc index b22c0754..0e485cac 100644 --- a/src/google/protobuf/compiler/cpp/cpp_map_field.cc +++ b/src/google/protobuf/compiler/cpp/cpp_map_field.cc @@ -104,9 +104,7 @@ void SetMessageVariables(const FieldDescriptor* descriptor, MapFieldGenerator::MapFieldGenerator(const FieldDescriptor* descriptor, const Options& options) - : FieldGenerator(options), - descriptor_(descriptor), - dependent_field_(options.proto_h && IsFieldDependent(descriptor)) { + : FieldGenerator(options), descriptor_(descriptor) { SetMessageVariables(descriptor, &variables_, options); } @@ -202,7 +200,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) const { key = "entry->key()"; value = "entry->value()"; printer->Print(variables_, - "::google::protobuf::scoped_ptr<$map_classname$> entry($name$_.NewEntry());\n"); + "::std::unique_ptr<$map_classname$> entry($name$_.NewEntry());\n"); printer->Print(variables_, "{\n" " ::std::string data;\n" @@ -258,7 +256,7 @@ static void GenerateSerializationLoop(io::Printer* printer, const string& ptr, bool loop_via_iterators) { printer->Print(variables, - StrCat("::google::protobuf::scoped_ptr<$map_classname$> entry;\n", + StrCat("::std::unique_ptr<$map_classname$> entry;\n", loop_header, " {\n").c_str()); printer->Indent(); @@ -365,7 +363,7 @@ void MapFieldGenerator::GenerateSerializeWithCachedSizes( "\n" "if ($deterministic$ &&\n" " this->$name$().size() > 1) {\n" - " ::google::protobuf::scoped_array<SortItem> items(\n" + " ::std::unique_ptr<SortItem[]> items(\n" " new SortItem[this->$name$().size()]);\n" " typedef ::google::protobuf::Map< $key_cpp$, $val_cpp$ >::size_type size_type;\n" " size_type n = 0;\n" @@ -402,7 +400,7 @@ GenerateByteSize(io::Printer* printer) const { "total_size += $tag_size$ *\n" " ::google::protobuf::internal::FromIntSize(this->$name$_size());\n" "{\n" - " ::google::protobuf::scoped_ptr<$map_classname$> entry;\n" + " ::std::unique_ptr<$map_classname$> entry;\n" " for (::google::protobuf::Map< $key_cpp$, $val_cpp$ >::const_iterator\n" " it = this->$name$().begin();\n" " it != this->$name$().end(); ++it) {\n"); diff --git a/src/google/protobuf/compiler/cpp/cpp_map_field.h b/src/google/protobuf/compiler/cpp/cpp_map_field.h index 88e3b464..0d54f0ea 100644 --- a/src/google/protobuf/compiler/cpp/cpp_map_field.h +++ b/src/google/protobuf/compiler/cpp/cpp_map_field.h @@ -66,7 +66,6 @@ class MapFieldGenerator : public FieldGenerator { io::Printer* printer, const std::map<string, string>& variables) const; const FieldDescriptor* descriptor_; - const bool dependent_field_; std::map<string, string> variables_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldGenerator); diff --git a/src/google/protobuf/compiler/cpp/cpp_message.cc b/src/google/protobuf/compiler/cpp/cpp_message.cc index 9b2f090e..778fc406 100644 --- a/src/google/protobuf/compiler/cpp/cpp_message.cc +++ b/src/google/protobuf/compiler/cpp/cpp_message.cc @@ -38,9 +38,6 @@ #include <google/protobuf/stubs/hash.h> #include <map> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <utility> #include <vector> @@ -49,9 +46,9 @@ #include <google/protobuf/compiler/cpp/cpp_field.h> #include <google/protobuf/compiler/cpp/cpp_helpers.h> #include <google/protobuf/compiler/cpp/cpp_padding_optimizer.h> +#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/printer.h> -#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/map_entry_lite.h> @@ -60,6 +57,7 @@ #include <google/protobuf/stubs/substitute.h> + namespace google { namespace protobuf { namespace compiler { @@ -440,13 +438,12 @@ MessageGenerator::MessageGenerator(const Descriptor* descriptor, index_in_file_messages_(index_in_file_messages), classname_(ClassName(descriptor, false)), options_(options), - field_generators_(descriptor, options), + field_generators_(descriptor, options, scc_analyzer), max_has_bit_index_(0), enum_generators_( - new google::protobuf::scoped_ptr<EnumGenerator>[descriptor->enum_type_count()]), - extension_generators_(new google::protobuf::scoped_ptr< + new std::unique_ptr<EnumGenerator>[descriptor->enum_type_count()]), + extension_generators_(new std::unique_ptr< ExtensionGenerator>[descriptor->extension_count()]), - use_dependent_base_(false), num_weak_fields_(0), message_layout_helper_(new PaddingOptimizer()), scc_analyzer_(scc_analyzer) { @@ -492,13 +489,6 @@ MessageGenerator::MessageGenerator(const Descriptor* descriptor, if (descriptor->field(i)->is_required()) { ++num_required_fields_; } - if (options.proto_h && IsFieldDependent(descriptor->field(i))) { - use_dependent_base_ = true; - } - } - if (options.proto_h && descriptor->oneof_decl_count() > 0) { - // Always make oneofs dependent. - use_dependent_base_ = true; } table_driven_ = TableDrivenParsingEnabled(descriptor_, options_); @@ -539,22 +529,6 @@ void MessageGenerator::FillMessageForwardDeclarations( } void MessageGenerator:: -GenerateDependentFieldAccessorDeclarations(io::Printer* printer) { - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - - PrintFieldComment(printer, field); - - std::map<string, string> vars; - SetCommonFieldVariables(field, &vars, options_); - - // Generate type-specific accessor declarations. - field_generators_.get(field).GenerateDependentAccessorDeclarations(printer); - printer->Print("\n"); - } -} - -void MessageGenerator:: GenerateFieldAccessorDeclarations(io::Printer* printer) { // optimized_fields_ does not contain fields where // field->containing_oneof() != NULL @@ -585,21 +559,6 @@ GenerateFieldAccessorDeclarations(io::Printer* printer) { SetCommonFieldVariables(field, &vars, options_); vars["constant_name"] = FieldConstantName(field); - bool dependent_field = use_dependent_base_ && IsFieldDependent(field); - if (dependent_field && - field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && - !field->is_map()) { - // If this field is dependent, the dependent base class determines - // the message type from the derived class (which is a template - // parameter). This typedef is for that: - printer->Print( - "private:\n" - "typedef $field_type$ $dependent_type$;\n" - "public:\n", - "field_type", FieldMessageTypeName(field), - "dependent_type", DependentTypeName(field)); - } - if (field->is_repeated()) { printer->Print(vars, "$deprecated_attr$int ${$$name$_size$}$() const;\n"); printer->Annotate("{", "}", field); @@ -637,6 +596,7 @@ GenerateFieldAccessorDeclarations(io::Printer* printer) { for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { printer->Print( + "void clear_$oneof_name$();\n" "$camel_oneof_name$Case $oneof_name$_case() const;\n", "camel_oneof_name", UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true), @@ -645,32 +605,6 @@ GenerateFieldAccessorDeclarations(io::Printer* printer) { } void MessageGenerator:: -GenerateDependentFieldAccessorDefinitions(io::Printer* printer) { - if (!use_dependent_base_) return; - - printer->Print("// $classname$\n\n", "classname", - DependentBaseClassTemplateName(descriptor_)); - - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - - if (field->options().weak()) continue; - - PrintFieldComment(printer, field); - // Generate type-specific accessors. - field_generators_.get(field) - .GenerateDependentInlineAccessorDefinitions(printer); - - printer->Print("\n"); - } - - // Generate has_$name$() and clear_has_$name$() functions for oneofs - // Similar to other has-bits, these must always be in the header if we - // are using a dependent base class. - GenerateOneofHasBits(printer); -} - -void MessageGenerator:: GenerateSingularFieldHasBits(const FieldDescriptor* field, std::map<string, string> vars, io::Printer* printer) { @@ -812,18 +746,6 @@ GenerateFieldAccessorDefinitions(io::Printer* printer) { std::map<string, string> vars; SetCommonFieldVariables(field, &vars, options_); - if (use_dependent_base_ && IsFieldDependent(field)) { - vars["tmpl"] = "template<class T>\n"; - vars["dependent_classname"] = - DependentBaseClassTemplateName(descriptor_) + "<T>"; - vars["this_message"] = "reinterpret_cast<T*>(this)->"; - vars["this_const_message"] = "reinterpret_cast<const T*>(this)->"; - } else { - vars["tmpl"] = ""; - vars["dependent_classname"] = vars["classname"]; - vars["this_message"] = ""; - vars["this_const_message"] = ""; - } // Generate has_$name$() or $name$_size(). if (field->is_repeated()) { @@ -851,42 +773,8 @@ GenerateFieldAccessorDefinitions(io::Printer* printer) { printer->Print("\n"); } - if (!use_dependent_base_) { - // Generate has_$name$() and clear_has_$name$() functions for oneofs - // If we aren't using a dependent base, they can be with the other functions - // that are #ifdef-guarded. - GenerateOneofHasBits(printer); - } -} - -void MessageGenerator:: -GenerateDependentBaseClassDefinition(io::Printer* printer) { - if (!use_dependent_base_) { - return; - } - - std::map<string, string> vars; - vars["classname"] = DependentBaseClassTemplateName(descriptor_); - vars["full_name"] = descriptor_->full_name(); - vars["superclass"] = SuperClassName(descriptor_, options_); - - printer->Print(vars, - "template <class T>\n" - "class $classname$ : public $superclass$ " - "/* @@protoc_insertion_point(dep_base_class_definition:$full_name$) */ {\n" - " public:\n"); - printer->Indent(); - - printer->Print(vars, - "$classname$() {}\n" - "virtual ~$classname$() {}\n" - "\n"); - - // Generate dependent accessor methods for all fields. - GenerateDependentFieldAccessorDeclarations(printer); - - printer->Outdent(); - printer->Print("};\n"); + // Generate has_$name$() and clear_has_$name$() functions for oneofs. + GenerateOneofHasBits(printer); } void MessageGenerator:: @@ -919,7 +807,7 @@ GenerateClassDefinition(io::Printer* printer) { "$classname$*>(&_$classname$_default_instance_); }\n"); if (HasDescriptorMethods(descriptor_->file(), options_)) { printer->Print( - " void MergeFrom(const ::google::protobuf::Message& other) PROTOBUF_FINAL;\n" + " void MergeFrom(const ::google::protobuf::Message& other) final;\n" " ::google::protobuf::Metadata GetMetadata() const;\n" "};\n"); } else { @@ -927,10 +815,6 @@ GenerateClassDefinition(io::Printer* printer) { } return; } - if (use_dependent_base_) { - GenerateDependentBaseClassDefinition(printer); - printer->Print("\n"); - } std::map<string, string> vars; vars["classname"] = classname_; @@ -942,20 +826,12 @@ GenerateClassDefinition(io::Printer* printer) { } else { vars["dllexport"] = options_.dllexport_decl + " "; } - if (use_dependent_base_) { - vars["superclass"] = - DependentBaseClassTemplateName(descriptor_) + "<" + classname_ + ">"; - } else { - vars["superclass"] = SuperClassName(descriptor_, options_); - } + vars["superclass"] = SuperClassName(descriptor_, options_); printer->Print(vars, "class $dllexport$$classname$ : public $superclass$ " "/* @@protoc_insertion_point(class_definition:$full_name$) */ " "{\n"); printer->Annotate("classname", descriptor_); - if (use_dependent_base_) { - printer->Print(vars, " friend class $superclass$;\n"); - } printer->Print(" public:\n"); printer->Indent(); @@ -1016,10 +892,10 @@ GenerateClassDefinition(io::Printer* printer) { // virtual method version of GetArenaNoVirtual(), required for generic dispatch given a // MessageLite* (e.g., in RepeatedField::AddAllocated()). printer->Print( - "inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {\n" + "inline ::google::protobuf::Arena* GetArena() const final {\n" " return GetArenaNoVirtual();\n" "}\n" - "inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {\n" + "inline void* GetMaybeArenaPointer() const final {\n" " return MaybeArenaPtr();\n" "}\n"); } @@ -1071,7 +947,7 @@ GenerateClassDefinition(io::Printer* printer) { " return reinterpret_cast<const $classname$*>(\n" " &_$classname$_default_instance_);\n" "}\n" - "static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =\n" + "static constexpr int kIndexInFileMessages =\n" " $message_index$;\n" "\n"); @@ -1091,12 +967,13 @@ GenerateClassDefinition(io::Printer* printer) { "template<typename T> bool Is() const {\n" " return _any_metadata_.Is<T>();\n" "}\n" + "static bool ParseAnyTypeUrl(const string& type_url,\n" + " string* full_type_name);\n" "\n"); } - vars["new_final"] = " PROTOBUF_FINAL"; + vars["new_final"] = " final"; - vars["create_func"] = MessageCreateFunction(descriptor_); printer->Print(vars, "void Swap($classname$* other);\n" "friend void swap($classname$& a, $classname$& b) {\n" @@ -1106,32 +983,32 @@ GenerateClassDefinition(io::Printer* printer) { "// implements Message ----------------------------------------------\n" "\n" "inline $classname$* New() const$new_final$ {\n" - " return ::google::protobuf::Arena::$create_func$<$classname$>(NULL);\n" + " return CreateMaybeMessage<$classname$>(NULL);\n" "}\n" "\n" "$classname$* New(::google::protobuf::Arena* arena) const$new_final$ {\n" - " return ::google::protobuf::Arena::$create_func$<$classname$>(arena);\n" + " return CreateMaybeMessage<$classname$>(arena);\n" "}\n"); // For instances that derive from Message (rather than MessageLite), some // methods are virtual and should be marked as final. string use_final = HasDescriptorMethods(descriptor_->file(), options_) ? - " PROTOBUF_FINAL" : ""; + " final" : ""; if (HasGeneratedMethods(descriptor_->file(), options_)) { if (HasDescriptorMethods(descriptor_->file(), options_)) { printer->Print(vars, - "void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;\n" - "void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;\n"); + "void CopyFrom(const ::google::protobuf::Message& from) final;\n" + "void MergeFrom(const ::google::protobuf::Message& from) final;\n"); } else { printer->Print(vars, "void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from)\n" - " PROTOBUF_FINAL;\n"); + " final;\n"); } - vars["clear_final"] = " PROTOBUF_FINAL"; - vars["is_initialized_final"] = " PROTOBUF_FINAL"; - vars["merge_partial_final"] = " PROTOBUF_FINAL"; + vars["clear_final"] = " final"; + vars["is_initialized_final"] = " final"; + vars["merge_partial_final"] = " final"; printer->Print( vars, @@ -1140,7 +1017,7 @@ GenerateClassDefinition(io::Printer* printer) { "void Clear()$clear_final$;\n" "bool IsInitialized() const$is_initialized_final$;\n" "\n" - "size_t ByteSizeLong() const PROTOBUF_FINAL;\n" + "size_t ByteSizeLong() const final;\n" "bool MergePartialFromCodedStream(\n" " ::google::protobuf::io::CodedInputStream* input)$merge_partial_final$;\n"); if (!options_.table_driven_serialization || @@ -1148,7 +1025,7 @@ GenerateClassDefinition(io::Printer* printer) { printer->Print( "void SerializeWithCachedSizes(\n" " ::google::protobuf::io::CodedOutputStream* output) const " - "PROTOBUF_FINAL;\n"); + "final;\n"); } // DiscardUnknownFields() is implemented in message.cc using reflections. We // need to implement this function in generated code for messages. @@ -1160,19 +1037,18 @@ GenerateClassDefinition(io::Printer* printer) { if (HasFastArraySerialization(descriptor_->file(), options_)) { printer->Print( "::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(\n" - " bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;\n"); + " bool deterministic, ::google::protobuf::uint8* target) const final;\n"); } } printer->Print( - "int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }\n" - "private:\n" - "void SharedCtor();\n" - "void SharedDtor();\n" - "void SetCachedSize(int size) const$final$;\n" - "void InternalSwap($classname$* other);\n", - "classname", classname_, - "final", use_final); + "int GetCachedSize() const final { return _cached_size_.Get(); }" + "\n\nprivate:\n" + "void SharedCtor();\n" + "void SharedDtor();\n" + "void SetCachedSize(int size) const$final$;\n" + "void InternalSwap($classname$* other);\n", + "classname", classname_, "final", use_final); if (SupportsArenas(descriptor_)) { printer->Print( // TODO(gerbens) Make this private! Currently people are deriving from @@ -1212,11 +1088,11 @@ GenerateClassDefinition(io::Printer* printer) { if (HasDescriptorMethods(descriptor_->file(), options_)) { printer->Print( - "::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;\n" + "::google::protobuf::Metadata GetMetadata() const final;\n" "\n"); } else { printer->Print( - "::std::string GetTypeName() const PROTOBUF_FINAL;\n" + "::std::string GetTypeName() const final;\n" "\n"); } @@ -1295,7 +1171,6 @@ GenerateClassDefinition(io::Printer* printer) { for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { printer->Print( "inline bool has_$oneof_name$() const;\n" - "void clear_$oneof_name$();\n" "inline void clear_has_$oneof_name$();\n\n", "oneof_name", descriptor_->oneof_decl(i)->name()); } @@ -1313,7 +1188,8 @@ GenerateClassDefinition(io::Printer* printer) { bool need_to_emit_cached_size = true; // TODO(kenton): Make _cached_size_ an atomic<int> when C++ supports it. - const string cached_size_decl = "mutable int _cached_size_;\n"; + const string cached_size_decl = + "mutable ::google::protobuf::internal::CachedSize _cached_size_;\n"; const size_t sizeof_has_bits = HasBitsSize(); const string has_bits_decl = sizeof_has_bits == 0 ? "" : @@ -1423,13 +1299,10 @@ GenerateClassDefinition(io::Printer* printer) { // The TableStruct struct needs access to the private parts, in order to // construct the offsets of all members. - // TODO(gerbens) Remove the friend for InitDefaults. - printer->Print( - "friend struct ::$file_namespace$::TableStruct;\n" - "friend void ::$file_namespace$::InitDefaults$scc_name$Impl();\n", - // Vars. - "scc_name", scc_name_, "file_namespace", - FileLevelNamespace(descriptor_)); + printer->Print("friend struct ::$file_namespace$::TableStruct;\n", + // Vars. + "scc_name", scc_name_, "file_namespace", + FileLevelNamespace(descriptor_)); printer->Outdent(); printer->Print("};"); @@ -1437,18 +1310,6 @@ GenerateClassDefinition(io::Printer* printer) { } void MessageGenerator:: -GenerateDependentInlineMethods(io::Printer* printer) { - if (IsMapEntryMessage(descriptor_)) return; - for (int i = 0; i < descriptor_->field_count(); i++) { - if (descriptor_->field(i)->options().weak()) { - field_generators_.get(descriptor_->field(i)) - .GenerateDependentInlineAccessorDefinitions(printer); - } - } - GenerateDependentFieldAccessorDefinitions(printer); -} - -void MessageGenerator:: GenerateInlineMethods(io::Printer* printer) { if (IsMapEntryMessage(descriptor_)) return; GenerateFieldAccessorDefinitions(printer); @@ -1603,7 +1464,8 @@ uint32 CalculateType(uint32 type, uint32 type_class) { return (type - 1) + type_class * 20; } -uint32 CalcFieldNum(const FieldDescriptor* field, const Options& options) { +uint32 CalcFieldNum(const FieldGenerator&, const FieldDescriptor* field, + const Options& options) { bool is_a_map = IsMapEntryMessage(field->containing_type()); int type = field->type(); if (field->containing_oneof()) { @@ -1624,9 +1486,16 @@ uint32 CalcFieldNum(const FieldDescriptor* field, const Options& options) { #else // We need to calculate for each field what function the table driven code // should use to serialize it. This returns the index in a lookup table. -uint32 CalcFieldNum(const FieldDescriptor* field, const Options& options) { +uint32 CalcFieldNum(const FieldGenerator& generator, + const FieldDescriptor* field, const Options& options) { bool is_a_map = IsMapEntryMessage(field->containing_type()); int type = field->type(); + if (type == FieldDescriptor::TYPE_STRING || + type == FieldDescriptor::TYPE_BYTES) { + if (generator.IsInlined()) { + type = internal::FieldMetadata::kInlinedType; + } + } if (field->containing_oneof()) { return internal::FieldMetadata::CalculateType( type, internal::FieldMetadata::kOneOf); @@ -1668,6 +1537,8 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) { if (IsMapEntryMessage(descriptor_)) { for (int i = 0; i < 2; i++) { const FieldDescriptor* field = sorted[i]; + const FieldGenerator& generator = field_generators_.get(field); + uint32 tag = internal::WireFormatLite::MakeTag( field->number(), WireFormat::WireTypeForFieldType(field->type())); @@ -1676,7 +1547,7 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) { vars["field_name"] = FieldName(field); vars["tag"] = SimpleItoa(tag); vars["hasbit"] = SimpleItoa(i); - vars["type"] = SimpleItoa(CalcFieldNum(field, options_)); + vars["type"] = SimpleItoa(CalcFieldNum(generator, field, options_)); vars["ptr"] = "NULL"; if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { GOOGLE_CHECK(!IsMapEntryMessage(field->message_type())); @@ -1765,7 +1636,9 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) { SimpleItoa(FindMessageIndexInFile(field->message_type())); } } - vars["type"] = SimpleItoa(CalcFieldNum(field, options_)); + + const FieldGenerator& generator = field_generators_.get(field); + vars["type"] = SimpleItoa(CalcFieldNum(generator, field, options_)); if (field->options().weak()) { @@ -1912,6 +1785,11 @@ GenerateClassMethods(io::Printer* printer) { "bool $classname$::UnpackTo(::google::protobuf::Message* message) const {\n" " return _any_metadata_.UnpackTo(message);\n" "}\n" + "bool $classname$::ParseAnyTypeUrl(const string& type_url,\n" + " string* full_type_name) {\n" + " return ::google::protobuf::internal::ParseAnyTypeUrl(type_url,\n" + " full_type_name);\n" + "}\n" "\n", "classname", classname_); } @@ -2049,16 +1927,26 @@ size_t MessageGenerator::GenerateParseOffsets(io::Printer* printer) { } processing_type = static_cast<unsigned>(field->type()); + const FieldGenerator& generator = field_generators_.get(field); if (field->type() == FieldDescriptor::TYPE_STRING) { switch (EffectiveStringCType(field)) { case FieldOptions::STRING: - default: + default: { + if (generator.IsInlined()) { + processing_type = internal::TYPE_STRING_INLINED; + break; + } break; + } } } else if (field->type() == FieldDescriptor::TYPE_BYTES) { switch (EffectiveStringCType(field)) { case FieldOptions::STRING: default: + if (generator.IsInlined()) { + processing_type = internal::TYPE_BYTES_INLINED; + break; + } break; } } @@ -2093,7 +1981,7 @@ size_t MessageGenerator::GenerateParseOffsets(io::Printer* printer) { "{\n" " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(\n" " $classname$, $name$_),\n" - " static_cast< ::google::protobuf::uint32>($presence$),\n" + " static_cast<::google::protobuf::uint32>($presence$),\n" " $nwtype$, $pwtype$, $ptype$, $tag_size$\n" "},\n"); } @@ -2150,20 +2038,7 @@ size_t MessageGenerator::GenerateParseAuxTable(io::Printer* printer) { printer->Print( vars, "{::google::protobuf::internal::AuxillaryParseTableField::message_aux{\n" - " &$ns$::_$classname$_default_instance_,\n"); - - bool dont_emit_table = - !TableDrivenParsingEnabled(field->message_type(), options_); - - if (dont_emit_table) { - printer->Print(" NULL,\n"); - } else { - printer->Print(vars, - " ::$file_namespace$::TableStruct::schema +\n" - " $ns$::$classname$::kIndexInFileMessages,\n"); - } - - printer->Print("}},\n"); + " &$ns$::_$classname$_default_instance_}},\n"); last_field_number++; break; } @@ -2174,7 +2049,7 @@ size_t MessageGenerator::GenerateParseAuxTable(io::Printer* printer) { field->default_value_string().empty() ? "&::google::protobuf::internal::fixed_address_empty_string" : "&" + Namespace(field) + " ::" + classname_ + - "::_default_" + FieldName(field) + "_"; + "::" + MakeDefaultName(field); break; case FieldOptions::CORD: case FieldOptions::STRING_PIECE: @@ -2245,14 +2120,20 @@ std::pair<size_t, size_t> MessageGenerator::GenerateOffsets( for (int i = 0; i < descriptor_->field_count(); i++) { const FieldDescriptor* field = descriptor_->field(i); if (field->containing_oneof() || field->options().weak()) { - printer->Print("offsetof($classname$DefaultTypeInternal, $name$_),\n", + printer->Print("offsetof($classname$DefaultTypeInternal, $name$_)", "classname", full_classname, "name", FieldName(field)); } else { printer->Print( - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, " - "$name$_),\n", + "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, $name$_)", "classname", full_classname, "name", FieldName(field)); } + + uint32 tag = field_generators_.get(field).CalculateFieldTag(); + if (tag != 0) { + printer->Print(" | $tag$", "tag", SimpleItoa(tag)); + } + + printer->Print(",\n"); } for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { @@ -2286,15 +2167,6 @@ GenerateSharedConstructorCode(io::Printer* printer) { "classname", classname_); printer->Indent(); - bool need_to_clear_cached_size = true; - // We reproduce the logic used for laying out _cached_sized_ in the class - // definition, as to initialize it in-order. - if (HasFieldPresence(descriptor_->file()) && - (HasBitsSize() % 8) != 0) { - printer->Print("_cached_size_ = 0;\n"); - need_to_clear_cached_size = false; - } - std::vector<bool> processed(optimized_order_.size(), false); GenerateConstructorBody(printer, processed, false); @@ -2304,10 +2176,6 @@ GenerateSharedConstructorCode(io::Printer* printer) { "oneof_name", descriptor_->oneof_decl(i)->name()); } - if (need_to_clear_cached_size) { - printer->Print("_cached_size_ = 0;\n"); - } - printer->Outdent(); printer->Print("}\n\n"); } @@ -2412,7 +2280,7 @@ GenerateArenaDestructorCode(io::Printer* printer) { "classname", classname_); } else { printer->Print( - "void $classname$::RegisterArenaDtor(::google::protobuf::Arena* arena) {\n" + "void $classname$::RegisterArenaDtor(::google::protobuf::Arena*) {\n" "}\n", "classname", classname_); } @@ -2491,12 +2359,7 @@ void MessageGenerator::GenerateConstructorBody(io::Printer* printer, void MessageGenerator:: GenerateStructors(io::Printer* printer) { string superclass; - if (use_dependent_base_) { - superclass = - DependentBaseClassTemplateName(descriptor_) + "<" + classname_ + ">"; - } else { - superclass = SuperClassName(descriptor_, options_); - } + superclass = SuperClassName(descriptor_, options_); string initializer_with_arena = superclass + "()"; if (descriptor_->extension_range_count() > 0) { @@ -2528,15 +2391,14 @@ GenerateStructors(io::Printer* printer) { initializer_null += ", _any_metadata_(&type_url_, &value_)"; } if (num_weak_fields_ > 0) { - initializer_null += ", _weak_field_map_(NULL)"; + initializer_null += ", _weak_field_map_(nullptr)"; } printer->Print( "$classname$::$classname$()\n" " : $initializer$ {\n" - " if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {\n" - " ::$file_namespace$::InitDefaults$scc_name$();\n" - " }\n" + " ::google::protobuf::internal::InitSCC(\n" + " &$file_namespace$::scc_info_$scc_name$.base);\n" " SharedCtor();\n" " // @@protoc_insertion_point(constructor:$full_name$)\n" "}\n", @@ -2548,7 +2410,9 @@ GenerateStructors(io::Printer* printer) { printer->Print( "$classname$::$classname$(::google::protobuf::Arena* arena)\n" " : $initializer$ {\n" - " ::$file_namespace$::InitDefaults$scc_name$();\n" + " " + "::google::protobuf::internal::InitSCC(&$file_namespace$::scc_info_$scc_name$." + "base);\n" " SharedCtor();\n" " RegisterArenaDtor(arena);\n" " // @@protoc_insertion_point(arena_constructor:$full_name$)\n" @@ -2589,16 +2453,6 @@ GenerateStructors(io::Printer* printer) { printer->Print(",\n_has_bits_(from._has_bits_)"); } - bool need_to_emit_cached_size = true; - const string cached_size_decl = ",\n_cached_size_(0)"; - // We reproduce the logic used for laying out _cached_sized_ in the class - // definition, as to initialize it in-order. - if (HasFieldPresence(descriptor_->file()) && - (HasBitsSize() % 8) != 0) { - printer->Print(cached_size_decl.c_str()); - need_to_emit_cached_size = false; - } - std::vector<bool> processed(optimized_order_.size(), false); for (int i = 0; i < optimized_order_.size(); ++i) { const FieldDescriptor* field = optimized_order_[i]; @@ -2613,11 +2467,6 @@ GenerateStructors(io::Printer* printer) { "name", FieldName(field)); } - if (need_to_emit_cached_size) { - printer->Print(cached_size_decl.c_str()); - need_to_emit_cached_size = false; - } - if (IsAnyMessage(descriptor_)) { printer->Print(",\n_any_metadata_(&type_url_, &value_)"); } @@ -2702,12 +2551,10 @@ GenerateStructors(io::Printer* printer) { // Generate SetCachedSize. printer->Print( - "void $classname$::SetCachedSize(int size) const {\n" - " GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n" - " _cached_size_ = size;\n" - " GOOGLE_SAFE_CONCURRENT_WRITES_END();\n" - "}\n", - "classname", classname_); + "void $classname$::SetCachedSize(int size) const {\n" + " _cached_size_.Set(size);\n" + "}\n", + "classname", classname_); // Only generate this member if it's not disabled. if (HasDescriptorMethods(descriptor_->file(), options_) && @@ -2726,7 +2573,9 @@ GenerateStructors(io::Printer* printer) { printer->Print( "const $classname$& $classname$::default_instance() {\n" - " ::$file_namespace$::InitDefaults$scc_name$();\n" + " " + "::google::protobuf::internal::InitSCC(&$file_namespace$::scc_info_$scc_name$.base)" + ";\n" " return *internal_default_instance();\n" "}\n\n", "classname", classname_, "scc_name", scc_name_, "file_namespace", @@ -2737,7 +2586,7 @@ void MessageGenerator::GenerateSourceInProto2Namespace(io::Printer* printer) { printer->Print( "template<> " "GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE " - "$classname$* Arena::$create_func$< $classname$ >(Arena* arena) {\n" + "$classname$* Arena::CreateMaybeMessage< $classname$ >(Arena* arena) {\n" " return Arena::$create_func$Internal< $classname$ >(arena);\n" "}\n", "classname", QualifiedClassName(descriptor_), @@ -2823,10 +2672,10 @@ GenerateClear(io::Printer* printer) { chunks.push_back(chunks_frag[i]); const FieldDescriptor* field = chunks_frag[i].front(); const FieldDescriptor* next_field = - (i + 1) < chunks_frag.size() ? chunks_frag[i + 1].front() : NULL; + (i + 1) < chunks_frag.size() ? chunks_frag[i + 1].front() : nullptr; if (CanInitializeByZeroing(field) && (chunks_frag[i].size() == 1 || unconditional_budget < 0) && - next_field != NULL && + next_field != nullptr && has_bit_indices_[field->index()] / 8 == has_bit_indices_[next_field->index()] / 8) { GOOGLE_CHECK(!CanInitializeByZeroing(next_field)); @@ -3111,7 +2960,6 @@ GenerateSwap(io::Printer* printer) { printer->Print("_internal_metadata_.Swap(&other->_internal_metadata_);\n"); - printer->Print("swap(_cached_size_, other->_cached_size_);\n"); if (descriptor_->extension_range_count() > 0) { printer->Print("_extensions_.Swap(&other->_extensions_);\n"); } @@ -3492,8 +3340,12 @@ GenerateMergeFromCodedStream(io::Printer* printer) { printer->Print("for (;;) {\n"); printer->Indent(); - uint32 maxtag = descriptor_->field_count() == 0 ? 0 : - WireFormat::MakeTag(ordered_fields[descriptor_->field_count() - 1]); + // To calculate the maximum tag to expect, we look at the highest-numbered + // field. We need to be prepared to handle more than one wire type if that + // field is a packable repeated field, so to simplify things we assume the + // highest possible wire type of 5. + uint32 maxtag = + ordered_fields.empty() ? 0 : ordered_fields.back()->number() * 8 + 5; const int kCutoff0 = 127; // fits in 1-byte varint const int kCutoff1 = (127 << 7) + 127; // fits in 2-byte varint @@ -3511,6 +3363,15 @@ GenerateMergeFromCodedStream(io::Printer* printer) { break; } } + + for (int i = 0; i < parent->extension_count(); i++) { + const FieldDescriptor* field = parent->extension(i); + if (field->type() == FieldDescriptor::TYPE_GROUP && + field->message_type() == descriptor_) { + capture_last_tag = true; + break; + } + } } for (int i = 0; i < descriptor_->file()->extension_count(); i++) { @@ -3522,7 +3383,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) { } } - printer->Print("::std::pair< ::google::protobuf::uint32, bool> p = " + printer->Print("::std::pair<::google::protobuf::uint32, bool> p = " "input->ReadTagWithCutoffNoLastTag($max$u);\n" "tag = p.first;\n" "if (!p.second) goto handle_unusual;\n", @@ -3621,7 +3482,6 @@ GenerateMergeFromCodedStream(io::Printer* printer) { printer->Outdent(); printer->Print("}\n\n"); } - printer->Print("default: {\n"); printer->Indent(); } @@ -4012,7 +3872,7 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) { // Merge the fields and the extension ranges, both sorted by field number. { LazySerializerEmitter e(this, printer, to_array); - const FieldDescriptor* last_weak_field = NULL; + const FieldDescriptor* last_weak_field = nullptr; int i, j; for (i = 0, j = 0; i < ordered_fields.size() || j < sorted_extensions.size();) { @@ -4024,16 +3884,16 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) { last_weak_field = field; PrintFieldComment(printer, field); } else { - if (last_weak_field != NULL) { + if (last_weak_field != nullptr) { e.Emit(last_weak_field); - last_weak_field = NULL; + last_weak_field = nullptr; } e.Emit(field); } } else { - if (last_weak_field != NULL) { + if (last_weak_field != nullptr) { e.Emit(last_weak_field); - last_weak_field = NULL; + last_weak_field = nullptr; } e.Flush(); GenerateSerializeOneExtensionRange(printer, @@ -4041,7 +3901,7 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) { to_array); } } - if (last_weak_field != NULL) { + if (last_weak_field != nullptr) { e.Emit(last_weak_field); } } @@ -4103,8 +3963,9 @@ static string ConditionalToCheckBitmasks(const std::vector<uint32>& masks) { } GOOGLE_CHECK(!parts.empty()); // If we have multiple parts, each expected to be 0, then bitwise-or them. - string result = parts.size() == 1 ? parts[0] : - StrCat("(", Join(parts, "\n | "), ")"); + string result = parts.size() == 1 + ? parts[0] + : StrCat("(", Join(parts, "\n | "), ")"); return result + " == 0"; } @@ -4117,20 +3978,19 @@ GenerateByteSize(io::Printer* printer) { SetUnknkownFieldsVariable(descriptor_, options_, &vars); vars["classname"] = classname_; vars["full_name"] = descriptor_->full_name(); - printer->Print(vars, - "size_t $classname$::ByteSizeLong() const {\n" - "// @@protoc_insertion_point(message_set_byte_size_start:$full_name$)\n" - " size_t total_size = _extensions_.MessageSetByteSize();\n" - " if ($have_unknown_fields$) {\n" - " total_size += ::google::protobuf::internal::WireFormat::\n" - " ComputeUnknownMessageSetItemsSize($unknown_fields$);\n" - " }\n" - " int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n" - " GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n" - " _cached_size_ = cached_size;\n" - " GOOGLE_SAFE_CONCURRENT_WRITES_END();\n" - " return total_size;\n" - "}\n"); + printer->Print( + vars, + "size_t $classname$::ByteSizeLong() const {\n" + "// @@protoc_insertion_point(message_set_byte_size_start:$full_name$)\n" + " size_t total_size = _extensions_.MessageSetByteSize();\n" + " if ($have_unknown_fields$) {\n" + " total_size += ::google::protobuf::internal::WireFormat::\n" + " ComputeUnknownMessageSetItemsSize($unknown_fields$);\n" + " }\n" + " int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n" + " SetCachedSize(cached_size);\n" + " return total_size;\n" + "}\n"); return; } @@ -4362,17 +4222,18 @@ GenerateByteSize(io::Printer* printer) { printer->Print("total_size += _weak_field_map_.ByteSizeLong();\n"); } - // We update _cached_size_ even though this is a const method. In theory, - // this is not thread-compatible, because concurrent writes have undefined - // results. In practice, since any concurrent writes will be writing the - // exact same value, it works on all common processors. In a future version - // of C++, _cached_size_ should be made into an atomic<int>. + // We update _cached_size_ even though this is a const method. Because + // const methods might be called concurrently this needs to be atomic + // operations or the program is undefined. In practice, since any concurrent + // writes will be writing the exact same value, normal writes will work on + // all common processors. We use a dedicated wrapper class to abstract away + // the underlying atomic. This makes it easier on platforms where even relaxed + // memory order might have perf impact to replace it with ordinary loads and + // stores. printer->Print( - "int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n" - "GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n" - "_cached_size_ = cached_size;\n" - "GOOGLE_SAFE_CONCURRENT_WRITES_END();\n" - "return total_size;\n"); + "int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n" + "SetCachedSize(cached_size);\n" + "return total_size;\n"); printer->Outdent(); printer->Print("}\n"); @@ -4421,7 +4282,7 @@ GenerateIsInitialized(io::Printer* printer) { !ShouldIgnoreRequiredFieldCheck(field, options_) && scc_analyzer_->HasRequiredFields(field->message_type())) { if (field->is_repeated()) { - if (IsImplicitWeakField(field, options_)) { + if (IsImplicitWeakField(field, options_, scc_analyzer_)) { printer->Print( "if (!::google::protobuf::internal::AllAreInitializedWeak(this->$name$_))" " return false;\n", diff --git a/src/google/protobuf/compiler/cpp/cpp_message.h b/src/google/protobuf/compiler/cpp/cpp_message.h index 06e2030b..ca2ca2c9 100644 --- a/src/google/protobuf/compiler/cpp/cpp_message.h +++ b/src/google/protobuf/compiler/cpp/cpp_message.h @@ -36,9 +36,6 @@ #define GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__ #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <set> #include <string> #include <google/protobuf/compiler/cpp/cpp_field.h> @@ -87,9 +84,6 @@ class MessageGenerator { // file). void GenerateInlineMethods(io::Printer* printer); - // Dependent methods are always inline. - void GenerateDependentInlineMethods(io::Printer* printer); - // Source file stuff. // Generate extra fields @@ -111,10 +105,7 @@ class MessageGenerator { private: // Generate declarations and definitions of accessors for fields. - void GenerateDependentBaseClassDefinition(io::Printer* printer); - void GenerateDependentFieldAccessorDeclarations(io::Printer* printer); void GenerateFieldAccessorDeclarations(io::Printer* printer); - void GenerateDependentFieldAccessorDefinitions(io::Printer* printer); void GenerateFieldAccessorDefinitions(io::Printer* printer); // Generate the table-driven parsing array. Returns the number of entries @@ -222,15 +213,14 @@ class MessageGenerator { std::vector<const FieldDescriptor *> optimized_order_; std::vector<int> has_bit_indices_; int max_has_bit_index_; - google::protobuf::scoped_array<google::protobuf::scoped_ptr<EnumGenerator> > enum_generators_; - google::protobuf::scoped_array<google::protobuf::scoped_ptr<ExtensionGenerator> > extension_generators_; + std::unique_ptr<std::unique_ptr<EnumGenerator> []> enum_generators_; + std::unique_ptr<std::unique_ptr<ExtensionGenerator> []> extension_generators_; int num_required_fields_; - bool use_dependent_base_; int num_weak_fields_; // table_driven_ indicates the generated message uses table-driven parsing. bool table_driven_; - google::protobuf::scoped_ptr<MessageLayoutHelper> message_layout_helper_; + std::unique_ptr<MessageLayoutHelper> message_layout_helper_; SCCAnalyzer* scc_analyzer_; string scc_name_; diff --git a/src/google/protobuf/compiler/cpp/cpp_message_field.cc b/src/google/protobuf/compiler/cpp/cpp_message_field.cc index 530a6392..c1e15c52 100644 --- a/src/google/protobuf/compiler/cpp/cpp_message_field.cc +++ b/src/google/protobuf/compiler/cpp/cpp_message_field.cc @@ -70,17 +70,16 @@ string ReinterpretCast(const string& type, const string& expression, } void SetMessageVariables(const FieldDescriptor* descriptor, - std::map<string, string>* variables, - const Options& options) { + const Options& options, bool implicit_weak, + std::map<string, string>* variables) { SetCommonFieldVariables(descriptor, variables, options); (*variables)["type"] = FieldMessageTypeName(descriptor); - (*variables)["casted_member"] = - ReinterpretCast((*variables)["type"] + "*", (*variables)["name"] + "_", - IsImplicitWeakField(descriptor, options)); + (*variables)["casted_member"] = ReinterpretCast( + (*variables)["type"] + "*", (*variables)["name"] + "_", implicit_weak); (*variables)["type_default_instance"] = DefaultInstanceName(descriptor->message_type()); (*variables)["type_reference_function"] = - IsImplicitWeakField(descriptor, options) + implicit_weak ? (" " + ReferenceFunctionName(descriptor->message_type()) + "();\n") : ""; (*variables)["stream_writer"] = @@ -94,8 +93,6 @@ void SetMessageVariables(const FieldDescriptor* descriptor, SafeFunctionName(descriptor->containing_type(), descriptor, "release_"); (*variables)["full_name"] = descriptor->full_name(); - (*variables)["create_func"] = - MessageCreateFunction(descriptor->message_type()); } } // namespace @@ -103,11 +100,13 @@ void SetMessageVariables(const FieldDescriptor* descriptor, // =================================================================== MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor, - const Options& options) + const Options& options, + SCCAnalyzer* scc_analyzer) : FieldGenerator(options), descriptor_(descriptor), - implicit_weak_field_(IsImplicitWeakField(descriptor, options)) { - SetMessageVariables(descriptor, &variables_, options); + implicit_weak_field_( + IsImplicitWeakField(descriptor, options, scc_analyzer)) { + SetMessageVariables(descriptor, options, implicit_weak_field_, &variables_); } MessageFieldGenerator::~MessageFieldGenerator() {} @@ -115,7 +114,7 @@ MessageFieldGenerator::~MessageFieldGenerator() {} void MessageFieldGenerator:: GeneratePrivateMembers(io::Printer* printer) const { if (implicit_weak_field_) { - printer->Print(variables_, "google::protobuf::MessageLite* $name$_;\n"); + printer->Print(variables_, "::google::protobuf::MessageLite* $name$_;\n"); } else { printer->Print(variables_, "$type$* $name$_;\n"); } @@ -129,8 +128,16 @@ GenerateAccessorDeclarations(io::Printer* printer) const { // the field without creating a strong dependency on the message type. printer->Print(variables_, "private:\n" - "const google::protobuf::MessageLite& _internal_$name$() const;\n" - "google::protobuf::MessageLite* _internal_mutable_$name$();\n" + "const ::google::protobuf::MessageLite& _internal_$name$() const;\n" + "::google::protobuf::MessageLite* _internal_mutable_$name$();\n" + "public:\n"); + } else { + // This inline accessor directly returns member field and is used in + // Serialize such that AFDO profile correctly captures access information to + // message fields under serialize. + printer->Print(variables_, + "private:\n" + "const $type$& _internal_$name$() const;\n" "public:\n"); } printer->Print(variables_, @@ -162,22 +169,22 @@ void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions( io::Printer* printer) const { if (implicit_weak_field_) { printer->Print(variables_, - "const google::protobuf::MessageLite& $classname$::_internal_$name$() const {\n" + "const ::google::protobuf::MessageLite& $classname$::_internal_$name$() const {\n" " if ($name$_ != NULL) {\n" " return *$name$_;\n" " } else if (&$type_default_instance$ != NULL) {\n" - " return *reinterpret_cast<const google::protobuf::MessageLite*>(\n" + " return *reinterpret_cast<const ::google::protobuf::MessageLite*>(\n" " &$type_default_instance$);\n" " } else {\n" - " return *reinterpret_cast<const google::protobuf::MessageLite*>(\n" - " &::google::protobuf::internal::implicit_weak_message_default_instance);\n" + " return " + "*::google::protobuf::internal::ImplicitWeakMessage::default_instance();\n" " }\n" "}\n"); } if (SupportsArenas(descriptor_)) { if (implicit_weak_field_) { printer->Print(variables_, - "google::protobuf::MessageLite* $classname$::_internal_mutable_$name$() {\n" + "::google::protobuf::MessageLite* $classname$::_internal_mutable_$name$() {\n" " $set_hasbit$\n" " if ($name$_ == NULL) {\n" " if (&$type_default_instance$ == NULL) {\n" @@ -185,7 +192,7 @@ void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions( " ::google::protobuf::internal::ImplicitWeakMessage>(\n" " GetArenaNoVirtual());\n" " } else {\n" - " $name$_ = reinterpret_cast<const google::protobuf::MessageLite*>(\n" + " $name$_ = reinterpret_cast<const ::google::protobuf::MessageLite*>(\n" " &$type_default_instance$)->New(GetArenaNoVirtual());\n" " }\n" " }\n" @@ -212,13 +219,13 @@ void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions( "}\n"); } else if (implicit_weak_field_) { printer->Print(variables_, - "google::protobuf::MessageLite* $classname$::_internal_mutable_$name$() {\n" + "::google::protobuf::MessageLite* $classname$::_internal_mutable_$name$() {\n" " $set_hasbit$\n" " if ($name$_ == NULL) {\n" " if (&$type_default_instance$ == NULL) {\n" " $name$_ = new ::google::protobuf::internal::ImplicitWeakMessage;\n" " } else {\n" - " $name$_ = reinterpret_cast<const google::protobuf::MessageLite*>(\n" + " $name$_ = reinterpret_cast<const ::google::protobuf::MessageLite*>(\n" " &$type_default_instance$)->New();\n" " }\n" " }\n" @@ -229,9 +236,14 @@ void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions( void MessageFieldGenerator:: GenerateInlineAccessorDefinitions(io::Printer* printer) const { + if (!implicit_weak_field_) { + printer->Print(variables_, + "inline const $type$& $classname$::_internal_$name$() const {\n" + " return *$field_member$;\n" + "}\n"); + } printer->Print(variables_, "inline const $type$& $classname$::$name$() const {\n" - "$type_reference_function$" " const $type$* p = $casted_member$;\n" " // @@protoc_insertion_point(field_get:$full_name$)\n" " return p != NULL ? *p : *reinterpret_cast<const $type$*>(\n" @@ -247,7 +259,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { if (SupportsArenas(descriptor_)) { printer->Print(variables_, " if (GetArenaNoVirtual() != NULL) {\n" - " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);\n" + " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);\n" " }\n"); } printer->Print(variables_, @@ -269,16 +281,15 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { printer->Print(variables_, "inline $type$* $classname$::mutable_$name$() {\n" - "$type_reference_function$" " $set_hasbit$\n" - " if ($name$_ == NULL) {\n"); + " if ($name$_ == NULL) {\n" + " auto* p = CreateMaybeMessage<$type$>(GetArenaNoVirtual());\n"); if (implicit_weak_field_) { printer->Print(variables_, - " _internal_mutable_$name$();\n"); + " $name$_ = reinterpret_cast<::google::protobuf::MessageLite*>(p);\n"); } else { printer->Print(variables_, - " $name$_ = ::google::protobuf::Arena::$create_func$< $type$ >(\n" - " GetArenaNoVirtual());\n"); + " $name$_ = p;\n"); } printer->Print(variables_, " }\n" @@ -309,7 +320,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { // isn't defined in this file. printer->Print(variables_, " ::google::protobuf::Arena* submessage_arena =\n" - " reinterpret_cast< ::google::protobuf::MessageLite*>($name$)->GetArena();\n"); + " reinterpret_cast<::google::protobuf::MessageLite*>($name$)->GetArena();\n"); } else if (!SupportsArenas(descriptor_->message_type())) { printer->Print(variables_, " ::google::protobuf::Arena* submessage_arena = NULL;\n"); @@ -436,7 +447,7 @@ void MessageFieldGenerator:: GenerateSerializeWithCachedSizes(io::Printer* printer) const { printer->Print(variables_, "::google::protobuf::internal::WireFormatLite::Write$stream_writer$(\n" - " $number$, *$field_member$, output);\n"); + " $number$, this->_internal_$name$(), output);\n"); } void MessageFieldGenerator:: @@ -444,7 +455,7 @@ GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { printer->Print(variables_, "target = ::google::protobuf::internal::WireFormatLite::\n" " InternalWrite$declared_type$ToArray(\n" - " $number$, *$field_member$, deterministic, target);\n"); + " $number$, this->_internal_$name$(), deterministic, target);\n"); } void MessageFieldGenerator:: @@ -457,11 +468,10 @@ GenerateByteSize(io::Printer* printer) const { // =================================================================== -MessageOneofFieldGenerator:: -MessageOneofFieldGenerator(const FieldDescriptor* descriptor, - const Options& options) - : MessageFieldGenerator(descriptor, options), - dependent_base_(options.proto_h) { +MessageOneofFieldGenerator::MessageOneofFieldGenerator( + const FieldDescriptor* descriptor, const Options& options, + SCCAnalyzer* scc_analyzer) + : MessageFieldGenerator(descriptor, options, scc_analyzer) { SetCommonOneofFieldVariables(descriptor, &variables_); } @@ -480,7 +490,7 @@ void MessageOneofFieldGenerator::GenerateNonInlineAccessorDefinitions( // isn't defined in this file. printer->Print(variables_, " ::google::protobuf::Arena* submessage_arena =\n" - " reinterpret_cast< ::google::protobuf::MessageLite*>($name$)->GetArena();\n"); + " reinterpret_cast<::google::protobuf::MessageLite*>($name$)->GetArena();\n"); } else if (!SupportsArenas(descriptor_->message_type())) { printer->Print(variables_, " ::google::protobuf::Arena* submessage_arena = NULL;\n"); @@ -503,6 +513,12 @@ void MessageOneofFieldGenerator::GenerateNonInlineAccessorDefinitions( void MessageOneofFieldGenerator:: GenerateInlineAccessorDefinitions(io::Printer* printer) const { + if (!implicit_weak_field_) { + printer->Print(variables_, + "inline const $type$& $classname$::_internal_$name$() const {\n" + " return *$field_member$;\n" + "}\n"); + } printer->Print(variables_, "inline $type$* $classname$::$release_name$() {\n" " // @@protoc_insertion_point(field_release:$full_name$)\n" @@ -512,7 +528,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { if (SupportsArenas(descriptor_)) { printer->Print(variables_, " if (GetArenaNoVirtual() != NULL) {\n" - " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);\n" + " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);\n" " }\n"); } printer->Print(variables_, @@ -565,7 +581,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { " if (!has_$name$()) {\n" " clear_$oneof_name$();\n" " set_has_$name$();\n" - " $field_member$ = ::google::protobuf::Arena::$create_func$< $type$ >(\n" + " $field_member$ = CreateMaybeMessage< $type$ >(\n" " GetArenaNoVirtual());\n" " }\n" " // @@protoc_insertion_point(field_mutable:$full_name$)\n" @@ -611,12 +627,13 @@ GenerateConstructorCode(io::Printer* printer) const { // =================================================================== RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator( - const FieldDescriptor* descriptor, const Options& options) + const FieldDescriptor* descriptor, const Options& options, + SCCAnalyzer* scc_analyzer) : FieldGenerator(options), descriptor_(descriptor), - dependent_field_(options.proto_h && IsFieldDependent(descriptor)), - implicit_weak_field_(IsImplicitWeakField(descriptor, options)) { - SetMessageVariables(descriptor, &variables_, options); + implicit_weak_field_( + IsImplicitWeakField(descriptor, options, scc_analyzer)) { + SetMessageVariables(descriptor, options, implicit_weak_field_, &variables_); } RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() {} @@ -628,19 +645,6 @@ GeneratePrivateMembers(io::Printer* printer) const { } void RepeatedMessageFieldGenerator:: -InternalGenerateTypeDependentAccessorDeclarations(io::Printer* printer) const { - printer->Print(variables_, "$deprecated_attr$$type$* ${$add_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); -} - -void RepeatedMessageFieldGenerator:: -GenerateDependentAccessorDeclarations(io::Printer* printer) const { - if (dependent_field_) { - InternalGenerateTypeDependentAccessorDeclarations(printer); - } -} - -void RepeatedMessageFieldGenerator:: GenerateAccessorDeclarations(io::Printer* printer) const { printer->Print(variables_, "$deprecated_attr$$type$* ${$mutable_$name$$}$(int index);\n"); @@ -653,9 +657,8 @@ GenerateAccessorDeclarations(io::Printer* printer) const { printer->Print(variables_, "$deprecated_attr$const $type$& $name$(int index) const;\n"); printer->Annotate("name", descriptor_); - if (!dependent_field_) { - InternalGenerateTypeDependentAccessorDeclarations(printer); - } + printer->Print(variables_, "$deprecated_attr$$type$* ${$add_$name$$}$();\n"); + printer->Annotate("{", "}", descriptor_); printer->Print(variables_, "$deprecated_attr$const ::google::protobuf::RepeatedPtrField< $type$ >&\n" " $name$() const;\n"); @@ -663,29 +666,6 @@ GenerateAccessorDeclarations(io::Printer* printer) const { } void RepeatedMessageFieldGenerator:: -GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const { - if (!dependent_field_) { - return; - } - std::map<string, string> variables(variables_); - // For the CRTP base class, all mutation methods are dependent, and so - // they must be in the header. - variables["dependent_classname"] = - DependentBaseClassTemplateName(descriptor_->containing_type()) + "<T>"; - variables["this_message"] = DependentBaseDownCast(); - variables["this_const_message"] = DependentBaseConstDownCast(); - - // Generate per-element accessors: - printer->Print(variables, - "template <class T>\n" - "inline $type$* $dependent_classname$::add_$name$() {\n" - " // @@protoc_insertion_point(field_add:$full_name$)\n" - "$type_reference_function$" - " return $this_message$$name$_.Add();\n" - "}\n"); -} - -void RepeatedMessageFieldGenerator:: GenerateInlineAccessorDefinitions(io::Printer* printer) const { printer->Print(variables_, "inline $type$* $classname$::mutable_$name$(int index) {\n" @@ -705,7 +685,6 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { printer->Print(variables_, "inline const $type$& $classname$::$name$(int index) const {\n" " // @@protoc_insertion_point(field_get:$full_name$)\n" - "$type_reference_function$" " return $name$_.InternalCheckedGet(index,\n" " *reinterpret_cast<const $type$*>(&$type_default_instance$));\n" "}\n"); @@ -718,14 +697,11 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { "}\n"); } - if (!dependent_field_) { - printer->Print(variables_, - "inline $type$* $classname$::add_$name$() {\n" - " // @@protoc_insertion_point(field_add:$full_name$)\n" - "$type_reference_function$" - " return $name$_.Add();\n" - "}\n"); - } + printer->Print(variables_, + "inline $type$* $classname$::add_$name$() {\n" + " // @@protoc_insertion_point(field_add:$full_name$)\n" + " return $name$_.Add();\n" + "}\n"); printer->Print(variables_, "inline const ::google::protobuf::RepeatedPtrField< $type$ >&\n" diff --git a/src/google/protobuf/compiler/cpp/cpp_message_field.h b/src/google/protobuf/compiler/cpp/cpp_message_field.h index e165404f..6879539c 100644 --- a/src/google/protobuf/compiler/cpp/cpp_message_field.h +++ b/src/google/protobuf/compiler/cpp/cpp_message_field.h @@ -38,18 +38,17 @@ #include <map> #include <string> #include <google/protobuf/compiler/cpp/cpp_field.h> +#include <google/protobuf/compiler/cpp/cpp_helpers.h> namespace google { namespace protobuf { namespace compiler { namespace cpp { -bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options); - class MessageFieldGenerator : public FieldGenerator { public: MessageFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); + const Options& options, SCCAnalyzer* scc_analyzer); ~MessageFieldGenerator(); // implements FieldGenerator --------------------------------------- @@ -81,7 +80,7 @@ class MessageFieldGenerator : public FieldGenerator { class MessageOneofFieldGenerator : public MessageFieldGenerator { public: MessageOneofFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); + const Options& options, SCCAnalyzer* scc_analyzer); ~MessageOneofFieldGenerator(); // implements FieldGenerator --------------------------------------- @@ -97,21 +96,19 @@ class MessageOneofFieldGenerator : public MessageFieldGenerator { void GenerateConstructorCode(io::Printer* printer) const; private: - const bool dependent_base_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageOneofFieldGenerator); }; class RepeatedMessageFieldGenerator : public FieldGenerator { public: RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); + const Options& options, + SCCAnalyzer* scc_analyzer); ~RepeatedMessageFieldGenerator(); // implements FieldGenerator --------------------------------------- void GeneratePrivateMembers(io::Printer* printer) const; - void GenerateDependentAccessorDeclarations(io::Printer* printer) const; void GenerateAccessorDeclarations(io::Printer* printer) const; - void GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const; void GenerateInlineAccessorDefinitions(io::Printer* printer) const; void GenerateClearingCode(io::Printer* printer) const; void GenerateMergingCode(io::Printer* printer) const; @@ -124,11 +121,7 @@ class RepeatedMessageFieldGenerator : public FieldGenerator { void GenerateByteSize(io::Printer* printer) const; private: - void InternalGenerateTypeDependentAccessorDeclarations( - io::Printer* printer) const; - const FieldDescriptor* descriptor_; - const bool dependent_field_; const bool implicit_weak_field_; std::map<string, string> variables_; diff --git a/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc index f72a7d60..eb7cd1c7 100644 --- a/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc +++ b/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc @@ -34,7 +34,7 @@ #include <gtest/gtest.h> #if LANG_CXX11 -#include <google/protobuf/stubs/type_traits.h> +#include <type_traits> #endif namespace google { diff --git a/src/google/protobuf/compiler/cpp/cpp_options.h b/src/google/protobuf/compiler/cpp/cpp_options.h index b0dd8836..f09885be 100644 --- a/src/google/protobuf/compiler/cpp/cpp_options.h +++ b/src/google/protobuf/compiler/cpp/cpp_options.h @@ -54,6 +54,7 @@ struct Options { table_driven_parsing(false), table_driven_serialization(false), lite_implicit_weak_fields(false), + bootstrap(false), num_cc_files(0), access_info_map(NULL) {} @@ -66,6 +67,7 @@ struct Options { bool table_driven_parsing; bool table_driven_serialization; bool lite_implicit_weak_fields; + bool bootstrap; int num_cc_files; string annotation_pragma_name; string annotation_guard_name; diff --git a/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h b/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h index 9641ba40..42a3b5cd 100644 --- a/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h +++ b/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h @@ -50,10 +50,10 @@ namespace cpp { class PaddingOptimizer : public MessageLayoutHelper { public: PaddingOptimizer() {} - ~PaddingOptimizer() {} + ~PaddingOptimizer() override {} void OptimizeLayout(std::vector<const FieldDescriptor*>* fields, - const Options& options); + const Options& options) override; }; } // namespace cpp diff --git a/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc index ceb2270e..ff6ba0f8 100644 --- a/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc +++ b/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc @@ -35,9 +35,6 @@ // worth. #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/compiler/cpp/cpp_generator.h> #include <google/protobuf/compiler/command_line_interface.h> @@ -172,7 +169,7 @@ class TestGenerator : public CodeGenerator { void TryInsert(const string& filename, const string& insertion_point, GeneratorContext* context) const { - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( context->OpenForInsert(filename, insertion_point)); io::Printer printer(output.get(), '$'); printer.Print("// inserted $name$\n", "name", insertion_point); diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.cc b/src/google/protobuf/compiler/cpp/cpp_string_field.cc index c9901e84..cf6c4b33 100644 --- a/src/google/protobuf/compiler/cpp/cpp_string_field.cc +++ b/src/google/protobuf/compiler/cpp/cpp_string_field.cc @@ -34,8 +34,8 @@ #include <google/protobuf/compiler/cpp/cpp_string_field.h> #include <google/protobuf/compiler/cpp/cpp_helpers.h> -#include <google/protobuf/io/printer.h> #include <google/protobuf/descriptor.pb.h> +#include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> @@ -53,7 +53,7 @@ void SetStringVariables(const FieldDescriptor* descriptor, (*variables)["default"] = DefaultValue(descriptor); (*variables)["default_length"] = SimpleItoa(descriptor->default_value_string().length()); - string default_variable_string = "_default_" + FieldName(descriptor) + "_"; + string default_variable_string = MakeDefaultName(descriptor); (*variables)["default_variable_name"] = default_variable_string; (*variables)["default_variable"] = descriptor->default_value_string().empty() @@ -82,8 +82,24 @@ void SetStringVariables(const FieldDescriptor* descriptor, StringFieldGenerator::StringFieldGenerator(const FieldDescriptor* descriptor, const Options& options) - : FieldGenerator(options), descriptor_(descriptor), - lite_(!HasDescriptorMethods(descriptor->file(), options)) { + : FieldGenerator(options), + descriptor_(descriptor), + lite_(!HasDescriptorMethods(descriptor->file(), options)), + inlined_(false) { + + // TODO(ckennelly): Handle inlining for any.proto. + if (IsAnyMessage(descriptor_->containing_type())) { + inlined_ = false; + } + if (descriptor_->containing_type()->options().map_entry()) { + inlined_ = false; + } + + // Limit to proto2, as we rely on has bits to distinguish field presence for + // release_$name$. On proto3, we cannot use the address of the string + // instance when the field has been inlined. + inlined_ = inlined_ && HasFieldPresence(descriptor_->file()); + SetStringVariables(descriptor, &variables_, options); } @@ -91,27 +107,36 @@ StringFieldGenerator::~StringFieldGenerator() {} void StringFieldGenerator:: GeneratePrivateMembers(io::Printer* printer) const { - // N.B. that we continue to use |ArenaStringPtr| instead of |string*| for - // string fields, even when SupportArenas(descriptor_) == false. Why? - // The simple answer is to avoid unmaintainable complexity. The reflection - // code assumes ArenaStringPtrs. These are *almost* in-memory-compatible with - // string*, except for the pointer tags and related ownership semantics. We - // could modify the runtime code to use string* for the not-supporting-arenas - // case, but this would require a way to detect which type of class was - // generated (adding overhead and complexity to GeneratedMessageReflection) - // and littering the runtime code paths with conditionals. It's simpler to - // stick with this but use lightweight accessors that assume arena == NULL. - // There should be very little overhead anyway because it's just a tagged - // pointer in-memory. - printer->Print(variables_, "::google::protobuf::internal::ArenaStringPtr $name$_;\n"); + if (inlined_) { + printer->Print(variables_, + "::google::protobuf::internal::InlinedStringField $name$_;\n"); + } else { + // N.B. that we continue to use |ArenaStringPtr| instead of |string*| for + // string fields, even when SupportArenas(descriptor_) == false. Why? The + // simple answer is to avoid unmaintainable complexity. The reflection code + // assumes ArenaStringPtrs. These are *almost* in-memory-compatible with + // string*, except for the pointer tags and related ownership semantics. We + // could modify the runtime code to use string* for the + // not-supporting-arenas case, but this would require a way to detect which + // type of class was generated (adding overhead and complexity to + // GeneratedMessageReflection) and littering the runtime code paths with + // conditionals. It's simpler to stick with this but use lightweight + // accessors that assume arena == NULL. There should be very little + // overhead anyway because it's just a tagged pointer in-memory. + printer->Print(variables_, "::google::protobuf::internal::ArenaStringPtr $name$_;\n"); + } } void StringFieldGenerator:: GenerateStaticMembers(io::Printer* printer) const { if (!descriptor_->default_value_string().empty()) { + // We make the default instance public, so it can be initialized by + // non-friend code. printer->Print(variables_, + "public:\n" "static ::google::protobuf::internal::ExplicitlyConstructed< ::std::string>" - " $default_variable_name$;\n"); + " $default_variable_name$;\n" + "private:\n"); } } @@ -246,9 +271,23 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { " return $name$_.Mutable($default_variable$, GetArenaNoVirtual());\n" "}\n" "inline ::std::string* $classname$::$release_name$() {\n" - " // @@protoc_insertion_point(field_release:$full_name$)\n" + " // @@protoc_insertion_point(field_release:$full_name$)\n"); + + if (HasFieldPresence(descriptor_->file())) { + printer->Print(variables_, + " if (!has_$name$()) {\n" + " return NULL;\n" + " }\n" + " $clear_hasbit$\n" + " return $name$_.ReleaseNonDefault(" + "$default_variable$, GetArenaNoVirtual());\n"); + } else { + printer->Print(variables_, " $clear_hasbit$\n" - " return $name$_.Release($default_variable$, GetArenaNoVirtual());\n" + " return $name$_.Release($default_variable$, GetArenaNoVirtual());\n"); + } + + printer->Print(variables_, "}\n" "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n" " if ($name$ != NULL) {\n" @@ -322,9 +361,22 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { " return $name$_.MutableNoArena($default_variable$);\n" "}\n" "inline ::std::string* $classname$::$release_name$() {\n" - " // @@protoc_insertion_point(field_release:$full_name$)\n" + " // @@protoc_insertion_point(field_release:$full_name$)\n"); + + if (HasFieldPresence(descriptor_->file())) { + printer->Print(variables_, + " if (!has_$name$()) {\n" + " return NULL;\n" + " }\n" " $clear_hasbit$\n" - " return $name$_.ReleaseNoArena($default_variable$);\n" + " return $name$_.ReleaseNonDefaultNoArena($default_variable$);\n"); + } else { + printer->Print(variables_, + " $clear_hasbit$\n" + " return $name$_.ReleaseNoArena($default_variable$);\n"); + } + + printer->Print(variables_, "}\n" "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n" " if ($name$ != NULL) {\n" @@ -343,7 +395,7 @@ GenerateNonInlineAccessorDefinitions(io::Printer* printer) const { if (!descriptor_->default_value_string().empty()) { // Initialized in GenerateDefaultInstanceAllocator. printer->Print(variables_, - "::google::protobuf::internal::ExplicitlyConstructed< ::std::string> " + "::google::protobuf::internal::ExplicitlyConstructed<::std::string> " "$classname$::$default_variable_name$;\n"); } } @@ -383,18 +435,34 @@ GenerateMessageClearingCode(io::Printer* printer) const { // If we have field presence, then the Clear() method of the protocol buffer // will have checked that this field is set. If so, we can avoid redundant // checks against default_variable. - const bool must_be_present = HasFieldPresence(descriptor_->file()); - - if (must_be_present) { + const bool must_be_present = + HasFieldPresence(descriptor_->file()); + + if (inlined_ && must_be_present) { + // Calling mutable_$name$() gives us a string reference and sets the has bit + // for $name$ (in proto2). We may get here when the string field is inlined + // but the string's contents have not been changed by the user, so we cannot + // make an assertion about the contents of the string and could never make + // an assertion about the string instance. + // + // For non-inlined strings, we distinguish from non-default by comparing + // instances, rather than contents. printer->Print(variables_, "GOOGLE_DCHECK(!$name$_.IsDefault($default_variable$));\n"); } if (SupportsArenas(descriptor_)) { if (descriptor_->default_value_string().empty()) { - printer->Print(variables_, - "$name$_.ClearToEmpty($default_variable$, GetArenaNoVirtual());\n"); + if (must_be_present) { + printer->Print(variables_, + "$name$_.ClearNonDefaultToEmpty();\n"); + } else { + printer->Print(variables_, + "$name$_.ClearToEmpty($default_variable$, GetArenaNoVirtual());\n"); + } } else { + // Clear to a non-empty default is more involved, as we try to use the + // Arena if one is present and may need to reallocate the string. printer->Print(variables_, "$name$_.ClearToDefault($default_variable$, GetArenaNoVirtual());\n"); } @@ -402,7 +470,7 @@ GenerateMessageClearingCode(io::Printer* printer) const { // When Arenas are disabled and field presence has been checked, we can // safely treat the ArenaStringPtr as a string*. if (descriptor_->default_value_string().empty()) { - printer->Print(variables_, "$name$_.UnsafeMutablePointer()->clear();\n"); + printer->Print(variables_, "$name$_.ClearNonDefaultToEmptyNoArena();\n"); } else { printer->Print( variables_, @@ -433,13 +501,29 @@ GenerateMergingCode(io::Printer* printer) const { void StringFieldGenerator:: GenerateSwappingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.Swap(&other->$name$_);\n"); + if (inlined_) { + printer->Print( + variables_, + "$name$_.Swap(&other->$name$_);\n"); + } else { + printer->Print( + variables_, + "$name$_.Swap(&other->$name$_, $default_variable$,\n" + " GetArenaNoVirtual());\n"); + } } void StringFieldGenerator:: GenerateConstructorCode(io::Printer* printer) const { + // TODO(ckennelly): Construct non-empty strings as part of the initializer + // list. + if (inlined_ && descriptor_->default_value_string().empty()) { + // Automatic initialization will construct the string. + return; + } + printer->Print(variables_, - "$name$_.UnsafeSetDefault($default_variable$);\n"); + "$name$_.UnsafeSetDefault($default_variable$);\n"); } void StringFieldGenerator:: @@ -472,8 +556,23 @@ GenerateCopyConstructorCode(io::Printer* printer) const { void StringFieldGenerator:: GenerateDestructorCode(io::Printer* printer) const { + if (inlined_) { + // The destructor is automatically invoked. + return; + } + + printer->Print(variables_, "$name$_.DestroyNoArena($default_variable$);\n"); +} + +bool StringFieldGenerator::GenerateArenaDestructorCode( + io::Printer* printer) const { + if (!inlined_) { + return false; + } + printer->Print(variables_, - "$name$_.DestroyNoArena($default_variable$);\n"); + "_this->$name$_.DestroyNoArena($default_variable$);\n"); + return true; } void StringFieldGenerator:: @@ -544,13 +643,17 @@ GenerateByteSize(io::Printer* printer) const { " this->$name$());\n"); } +uint32 StringFieldGenerator::CalculateFieldTag() const { + return inlined_ ? 1 : 0; +} + // =================================================================== -StringOneofFieldGenerator:: -StringOneofFieldGenerator(const FieldDescriptor* descriptor, - const Options& options) - : StringFieldGenerator(descriptor, options), - dependent_field_(options.proto_h) { +StringOneofFieldGenerator::StringOneofFieldGenerator( + const FieldDescriptor* descriptor, const Options& options) + : StringFieldGenerator(descriptor, options) { + inlined_ = false; + SetCommonOneofFieldVariables(descriptor, &variables_); } diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.h b/src/google/protobuf/compiler/cpp/cpp_string_field.h index 0c6e9ced..6cbf722f 100644 --- a/src/google/protobuf/compiler/cpp/cpp_string_field.h +++ b/src/google/protobuf/compiler/cpp/cpp_string_field.h @@ -63,11 +63,14 @@ class StringFieldGenerator : public FieldGenerator { void GenerateConstructorCode(io::Printer* printer) const; void GenerateCopyConstructorCode(io::Printer* printer) const; void GenerateDestructorCode(io::Printer* printer) const; + bool GenerateArenaDestructorCode(io::Printer* printer) const; void GenerateDefaultInstanceAllocator(io::Printer* printer) const; void GenerateMergeFromCodedStream(io::Printer* printer) const; void GenerateSerializeWithCachedSizes(io::Printer* printer) const; void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const; void GenerateByteSize(io::Printer* printer) const; + uint32 CalculateFieldTag() const; + bool IsInlined() const { return inlined_; } bool MergeFromCodedStreamNeedsArena() const; @@ -75,6 +78,7 @@ class StringFieldGenerator : public FieldGenerator { const FieldDescriptor* descriptor_; std::map<string, string> variables_; const bool lite_; + bool inlined_; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringFieldGenerator); @@ -99,7 +103,6 @@ class StringOneofFieldGenerator : public StringFieldGenerator { void GenerateMergeFromCodedStream(io::Printer* printer) const; private: - const bool dependent_field_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringOneofFieldGenerator); }; diff --git a/src/google/protobuf/compiler/cpp/cpp_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_unittest.cc index 2ad7ea4e..22b759a9 100644 --- a/src/google/protobuf/compiler/cpp/cpp_unittest.cc +++ b/src/google/protobuf/compiler/cpp/cpp_unittest.cc @@ -46,40 +46,26 @@ #include <google/protobuf/compiler/cpp/cpp_unittest.h> -#include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif -#include <vector> - #include <google/protobuf/unittest.pb.h> -#include <google/protobuf/unittest_no_arena.pb.h> #include <google/protobuf/unittest_optimize_for.pb.h> #include <google/protobuf/unittest_embed_optimize_for.pb.h> -#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER) -// We exclude this large proto from cmake build because it's too large for -// visual studio to compile (report internal errors). -#include <google/protobuf/unittest_enormous_descriptor.pb.h> -#endif -#include <google/protobuf/unittest_no_generic_services.pb.h> + #include <google/protobuf/test_util.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> -#include <google/protobuf/compiler/cpp/cpp_test_bad_identifiers.pb.h> -#include <google/protobuf/compiler/importer.h> -#include <google/protobuf/io/coded_stream.h> -#include <google/protobuf/io/zero_copy_stream_impl.h> -#include <google/protobuf/arena.h> -#include <google/protobuf/descriptor.h> -#include <google/protobuf/descriptor.pb.h> -#include <google/protobuf/dynamic_message.h> -#include <google/protobuf/stubs/callback.h> -#include <google/protobuf/stubs/common.h> -#include <google/protobuf/stubs/logging.h> -#include <google/protobuf/stubs/substitute.h> -#include <google/protobuf/testing/googletest.h> -#include <gtest/gtest.h> -#include <google/protobuf/stubs/stl_util.h> +#define MESSAGE_TEST_NAME MessageTest +#define GENERATED_DESCRIPTOR_TEST_NAME GeneratedDescriptorTest +#define GENERATED_MESSAGE_TEST_NAME GeneratedMessageTest +#define GENERATED_ENUM_TEST_NAME GeneratedEnumTest +#define GENERATED_SERVICE_TEST_NAME GeneratedServiceTest +#define HELPERS_TEST_NAME HelpersTest +#define DESCRIPTOR_INIT_TEST_NAME DescriptorInitializationTest + +#define UNITTEST_PROTO_PATH "google/protobuf/unittest.proto" +#define UNITTEST ::protobuf_unittest +#define UNITTEST_IMPORT ::protobuf_unittest_import + +// Must include after the above macros. +#include <google/protobuf/compiler/cpp/cpp_unittest.inc> namespace google { namespace protobuf { @@ -91,848 +77,14 @@ namespace cpp_unittest { namespace protobuf_unittest = ::protobuf_unittest; - -class MockErrorCollector : public MultiFileErrorCollector { - public: - MockErrorCollector() {} - ~MockErrorCollector() {} - - string text_; - - // implements ErrorCollector --------------------------------------- - void AddError(const string& filename, int line, int column, - const string& message) { - strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", - filename, line, column, message); - } -}; - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - -// Test that generated code has proper descriptors: -// Parse a descriptor directly (using google::protobuf::compiler::Importer) and -// compare it to the one that was produced by generated code. -TEST(GeneratedDescriptorTest, IdenticalDescriptors) { - const FileDescriptor* generated_descriptor = - unittest::TestAllTypes::descriptor()->file(); - - // Set up the Importer. - MockErrorCollector error_collector; - DiskSourceTree source_tree; - source_tree.MapPath("", TestSourceDir()); - Importer importer(&source_tree, &error_collector); - - // Import (parse) unittest.proto. - const FileDescriptor* parsed_descriptor = - importer.Import("google/protobuf/unittest.proto"); - EXPECT_EQ("", error_collector.text_); - ASSERT_TRUE(parsed_descriptor != NULL); - - // Test that descriptors are generated correctly by converting them to - // FileDescriptorProtos and comparing. - FileDescriptorProto generated_descriptor_proto, parsed_descriptor_proto; - generated_descriptor->CopyTo(&generated_descriptor_proto); - parsed_descriptor->CopyTo(&parsed_descriptor_proto); - - EXPECT_EQ(parsed_descriptor_proto.DebugString(), - generated_descriptor_proto.DebugString()); -} - -#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER) -// Test that generated code has proper descriptors: -// Touch a descriptor generated from an enormous message to validate special -// handling for descriptors exceeding the C++ standard's recommended minimum -// limit for string literal size -TEST(GeneratedDescriptorTest, EnormousDescriptor) { - const Descriptor* generated_descriptor = - TestEnormousDescriptor::descriptor(); - - EXPECT_TRUE(generated_descriptor != NULL); -} -#endif - -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS - -// =================================================================== - -TEST(GeneratedMessageTest, Defaults) { - // Check that all default values are set correctly in the initial message. - unittest::TestAllTypes message; - - TestUtil::ExpectClear(message); - - // Messages should return pointers to default instances until first use. - // (This is not checked by ExpectClear() since it is not actually true after - // the fields have been set and then cleared.) - EXPECT_EQ(&unittest::TestAllTypes::OptionalGroup::default_instance(), - &message.optionalgroup()); - EXPECT_EQ(&unittest::TestAllTypes::NestedMessage::default_instance(), - &message.optional_nested_message()); - EXPECT_EQ(&unittest::ForeignMessage::default_instance(), - &message.optional_foreign_message()); - EXPECT_EQ(&unittest_import::ImportMessage::default_instance(), - &message.optional_import_message()); -} - -#ifndef PROTOBUF_USE_DLLS -TEST(GeneratedMessageTest, Int32StringConversion) { - EXPECT_EQ("971", Int32ToString(971)); - EXPECT_EQ("(~0x7fffffff)", Int32ToString(kint32min)); - EXPECT_EQ("2147483647", Int32ToString(kint32max)); -} - -TEST(GeneratedMessageTest, Int64StringConversion) { - EXPECT_EQ("GOOGLE_LONGLONG(971)", Int64ToString(971)); - EXPECT_EQ("GOOGLE_LONGLONG(-2147483648)", Int64ToString(kint32min)); - EXPECT_EQ("GOOGLE_LONGLONG(~0x7fffffffffffffff)", Int64ToString(kint64min)); - EXPECT_EQ("GOOGLE_LONGLONG(9223372036854775807)", Int64ToString(kint64max)); -} -#endif // !PROTOBUF_USE_DLLS - -TEST(GeneratedMessageTest, FloatingPointDefaults) { - const unittest::TestExtremeDefaultValues& extreme_default = - unittest::TestExtremeDefaultValues::default_instance(); - - EXPECT_EQ(0.0f, extreme_default.zero_float()); - EXPECT_EQ(1.0f, extreme_default.one_float()); - EXPECT_EQ(1.5f, extreme_default.small_float()); - EXPECT_EQ(-1.0f, extreme_default.negative_one_float()); - EXPECT_EQ(-1.5f, extreme_default.negative_float()); - EXPECT_EQ(2.0e8f, extreme_default.large_float()); - EXPECT_EQ(-8e-28f, extreme_default.small_negative_float()); - EXPECT_EQ(std::numeric_limits<double>::infinity(), - extreme_default.inf_double()); - EXPECT_EQ(-std::numeric_limits<double>::infinity(), - extreme_default.neg_inf_double()); - EXPECT_TRUE(extreme_default.nan_double() != extreme_default.nan_double()); - EXPECT_EQ(std::numeric_limits<float>::infinity(), - extreme_default.inf_float()); - EXPECT_EQ(-std::numeric_limits<float>::infinity(), - extreme_default.neg_inf_float()); - EXPECT_TRUE(extreme_default.nan_float() != extreme_default.nan_float()); -} - -TEST(GeneratedMessageTest, Trigraph) { - const unittest::TestExtremeDefaultValues& extreme_default = - unittest::TestExtremeDefaultValues::default_instance(); - - EXPECT_EQ("? ? ?? ?? ??? ?\?/ ?\?-", extreme_default.cpp_trigraph()); -} - -TEST(GeneratedMessageTest, ExtremeSmallIntegerDefault) { - const unittest::TestExtremeDefaultValues& extreme_default = - unittest::TestExtremeDefaultValues::default_instance(); - EXPECT_EQ(~0x7fffffff, kint32min); - EXPECT_EQ(GOOGLE_LONGLONG(~0x7fffffffffffffff), kint64min); - EXPECT_EQ(kint32min, extreme_default.really_small_int32()); - EXPECT_EQ(kint64min, extreme_default.really_small_int64()); -} - -TEST(GeneratedMessageTest, Accessors) { - // Set every field to a unique value then go back and check all those - // values. - unittest::TestAllTypes message; - - TestUtil::SetAllFields(&message); - TestUtil::ExpectAllFieldsSet(message); - - TestUtil::ModifyRepeatedFields(&message); - TestUtil::ExpectRepeatedFieldsModified(message); -} - -TEST(GeneratedMessageTest, MutableStringDefault) { - // mutable_foo() for a string should return a string initialized to its - // default value. - unittest::TestAllTypes message; - - EXPECT_EQ("hello", *message.mutable_default_string()); - - // Note that the first time we call mutable_foo(), we get a newly-allocated - // string, but if we clear it and call it again, we get the same object again. - // We should verify that it has its default value in both cases. - message.set_default_string("blah"); - message.Clear(); - - EXPECT_EQ("hello", *message.mutable_default_string()); -} - -TEST(GeneratedMessageTest, StringDefaults) { - unittest::TestExtremeDefaultValues message; - // Check if '\000' can be used in default string value. - EXPECT_EQ(string("hel\000lo", 6), message.string_with_zero()); - EXPECT_EQ(string("wor\000ld", 6), message.bytes_with_zero()); -} - -TEST(GeneratedMessageTest, ReleaseString) { - // Check that release_foo() starts out NULL, and gives us a value - // that we can delete after it's been set. - unittest::TestAllTypes message; - - EXPECT_EQ(NULL, message.release_default_string()); - EXPECT_FALSE(message.has_default_string()); - EXPECT_EQ("hello", message.default_string()); - - message.set_default_string("blah"); - EXPECT_TRUE(message.has_default_string()); - google::protobuf::scoped_ptr<string> str(message.release_default_string()); - EXPECT_FALSE(message.has_default_string()); - ASSERT_TRUE(str != NULL); - EXPECT_EQ("blah", *str); - - EXPECT_EQ(NULL, message.release_default_string()); - EXPECT_FALSE(message.has_default_string()); - EXPECT_EQ("hello", message.default_string()); -} - -TEST(GeneratedMessageTest, ReleaseMessage) { - // Check that release_foo() starts out NULL, and gives us a value - // that we can delete after it's been set. - unittest::TestAllTypes message; - - EXPECT_EQ(NULL, message.release_optional_nested_message()); - EXPECT_FALSE(message.has_optional_nested_message()); - - message.mutable_optional_nested_message()->set_bb(1); - google::protobuf::scoped_ptr<unittest::TestAllTypes::NestedMessage> nest( - message.release_optional_nested_message()); - EXPECT_FALSE(message.has_optional_nested_message()); - ASSERT_TRUE(nest != NULL); - EXPECT_EQ(1, nest->bb()); - - EXPECT_EQ(NULL, message.release_optional_nested_message()); - EXPECT_FALSE(message.has_optional_nested_message()); -} - -TEST(GeneratedMessageTest, SetAllocatedString) { - // Check that set_allocated_foo() works for strings. - unittest::TestAllTypes message; - - EXPECT_FALSE(message.has_optional_string()); - const string kHello("hello"); - message.set_optional_string(kHello); - EXPECT_TRUE(message.has_optional_string()); - - message.set_allocated_optional_string(NULL); - EXPECT_FALSE(message.has_optional_string()); - EXPECT_EQ("", message.optional_string()); - - message.set_allocated_optional_string(new string(kHello)); - EXPECT_TRUE(message.has_optional_string()); - EXPECT_EQ(kHello, message.optional_string()); -} - -TEST(GeneratedMessageTest, SetAllocatedMessage) { - // Check that set_allocated_foo() can be called in all cases. - unittest::TestAllTypes message; - - EXPECT_FALSE(message.has_optional_nested_message()); - - message.mutable_optional_nested_message()->set_bb(1); - EXPECT_TRUE(message.has_optional_nested_message()); - - message.set_allocated_optional_nested_message(NULL); - EXPECT_FALSE(message.has_optional_nested_message()); - EXPECT_EQ(&unittest::TestAllTypes::NestedMessage::default_instance(), - &message.optional_nested_message()); - - message.mutable_optional_nested_message()->set_bb(1); - unittest::TestAllTypes::NestedMessage* nest = - message.release_optional_nested_message(); - ASSERT_TRUE(nest != NULL); - EXPECT_FALSE(message.has_optional_nested_message()); - - message.set_allocated_optional_nested_message(nest); - EXPECT_TRUE(message.has_optional_nested_message()); - EXPECT_EQ(1, message.optional_nested_message().bb()); -} - -TEST(GeneratedMessageTest, Clear) { - // Set every field to a unique value, clear the message, then check that - // it is cleared. - unittest::TestAllTypes message; - - TestUtil::SetAllFields(&message); - message.Clear(); - TestUtil::ExpectClear(message); - - // Unlike with the defaults test, we do NOT expect that requesting embedded - // messages will return a pointer to the default instance. Instead, they - // should return the objects that were created when mutable_blah() was - // called. - EXPECT_NE(&unittest::TestAllTypes::OptionalGroup::default_instance(), - &message.optionalgroup()); - EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(), - &message.optional_nested_message()); - EXPECT_NE(&unittest::ForeignMessage::default_instance(), - &message.optional_foreign_message()); - EXPECT_NE(&unittest_import::ImportMessage::default_instance(), - &message.optional_import_message()); -} - -TEST(GeneratedMessageTest, EmbeddedNullsInBytesCharStar) { - unittest::TestAllTypes message; - - const char* value = "\0lalala\0\0"; - message.set_optional_bytes(value, 9); - ASSERT_EQ(9, message.optional_bytes().size()); - EXPECT_EQ(0, memcmp(value, message.optional_bytes().data(), 9)); - - message.add_repeated_bytes(value, 9); - ASSERT_EQ(9, message.repeated_bytes(0).size()); - EXPECT_EQ(0, memcmp(value, message.repeated_bytes(0).data(), 9)); -} - -TEST(GeneratedMessageTest, ClearOneField) { - // Set every field to a unique value, then clear one value and insure that - // only that one value is cleared. - unittest::TestAllTypes message; - - TestUtil::SetAllFields(&message); - int64 original_value = message.optional_int64(); - - // Clear the field and make sure it shows up as cleared. - message.clear_optional_int64(); - EXPECT_FALSE(message.has_optional_int64()); - EXPECT_EQ(0, message.optional_int64()); - - // Other adjacent fields should not be cleared. - EXPECT_TRUE(message.has_optional_int32()); - EXPECT_TRUE(message.has_optional_uint32()); - - // Make sure if we set it again, then all fields are set. - message.set_optional_int64(original_value); - TestUtil::ExpectAllFieldsSet(message); -} - -TEST(GeneratedMessageTest, StringCharStarLength) { - // Verify that we can use a char*,length to set one of the string fields. - unittest::TestAllTypes message; - message.set_optional_string("abcdef", 3); - EXPECT_EQ("abc", message.optional_string()); - - // Verify that we can use a char*,length to add to a repeated string field. - message.add_repeated_string("abcdef", 3); - EXPECT_EQ(1, message.repeated_string_size()); - EXPECT_EQ("abc", message.repeated_string(0)); - - // Verify that we can use a char*,length to set a repeated string field. - message.set_repeated_string(0, "wxyz", 2); - EXPECT_EQ("wx", message.repeated_string(0)); -} - -#if LANG_CXX11 -TEST(GeneratedMessageTest, StringMove) { - // Verify that we trigger the move behavior on a scalar setter. - protobuf_unittest_no_arena::TestAllTypes message; - { - string tmp(32, 'a'); - - const char* old_data = tmp.data(); - message.set_optional_string(std::move(tmp)); - const char* new_data = message.optional_string().data(); - - EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'a'), message.optional_string()); - - string tmp2(32, 'b'); - old_data = tmp2.data(); - message.set_optional_string(std::move(tmp2)); - new_data = message.optional_string().data(); - - EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'b'), message.optional_string()); - } - - // Verify that we trigger the move behavior on a oneof setter. - { - string tmp(32, 'a'); - - const char* old_data = tmp.data(); - message.set_oneof_string(std::move(tmp)); - const char* new_data = message.oneof_string().data(); - - EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'a'), message.oneof_string()); - - string tmp2(32, 'b'); - old_data = tmp2.data(); - message.set_oneof_string(std::move(tmp2)); - new_data = message.oneof_string().data(); - - EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'b'), message.oneof_string()); - } - - // Verify that we trigger the move behavior on a repeated setter. - { - string tmp(32, 'a'); - - const char* old_data = tmp.data(); - message.add_repeated_string(std::move(tmp)); - const char* new_data = message.repeated_string(0).data(); - - EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'a'), message.repeated_string(0)); - - string tmp2(32, 'b'); - old_data = tmp2.data(); - message.set_repeated_string(0, std::move(tmp2)); - new_data = message.repeated_string(0).data(); - - EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'b'), message.repeated_string(0)); - } -} -#endif - - -TEST(GeneratedMessageTest, CopyFrom) { - unittest::TestAllTypes message1, message2; - - TestUtil::SetAllFields(&message1); - message2.CopyFrom(message1); - TestUtil::ExpectAllFieldsSet(message2); - - // Copying from self should be a no-op. - message2.CopyFrom(message2); - TestUtil::ExpectAllFieldsSet(message2); -} - - -TEST(GeneratedMessageTest, SwapWithEmpty) { - unittest::TestAllTypes message1, message2; - TestUtil::SetAllFields(&message1); - - TestUtil::ExpectAllFieldsSet(message1); - TestUtil::ExpectClear(message2); - message1.Swap(&message2); - TestUtil::ExpectAllFieldsSet(message2); - TestUtil::ExpectClear(message1); -} - -TEST(GeneratedMessageTest, SwapWithSelf) { - unittest::TestAllTypes message; - TestUtil::SetAllFields(&message); - TestUtil::ExpectAllFieldsSet(message); - message.Swap(&message); - TestUtil::ExpectAllFieldsSet(message); -} - -TEST(GeneratedMessageTest, SwapWithOther) { - unittest::TestAllTypes message1, message2; - - message1.set_optional_int32(123); - message1.set_optional_string("abc"); - message1.mutable_optional_nested_message()->set_bb(1); - message1.set_optional_nested_enum(unittest::TestAllTypes::FOO); - message1.add_repeated_int32(1); - message1.add_repeated_int32(2); - message1.add_repeated_string("a"); - message1.add_repeated_string("b"); - message1.add_repeated_nested_message()->set_bb(7); - message1.add_repeated_nested_message()->set_bb(8); - message1.add_repeated_nested_enum(unittest::TestAllTypes::FOO); - message1.add_repeated_nested_enum(unittest::TestAllTypes::BAR); - - message2.set_optional_int32(456); - message2.set_optional_string("def"); - message2.mutable_optional_nested_message()->set_bb(2); - message2.set_optional_nested_enum(unittest::TestAllTypes::BAR); - message2.add_repeated_int32(3); - message2.add_repeated_string("c"); - message2.add_repeated_nested_message()->set_bb(9); - message2.add_repeated_nested_enum(unittest::TestAllTypes::BAZ); - - message1.Swap(&message2); - - EXPECT_EQ(456, message1.optional_int32()); - EXPECT_EQ("def", message1.optional_string()); - EXPECT_EQ(2, message1.optional_nested_message().bb()); - EXPECT_EQ(unittest::TestAllTypes::BAR, message1.optional_nested_enum()); - ASSERT_EQ(1, message1.repeated_int32_size()); - EXPECT_EQ(3, message1.repeated_int32(0)); - ASSERT_EQ(1, message1.repeated_string_size()); - EXPECT_EQ("c", message1.repeated_string(0)); - ASSERT_EQ(1, message1.repeated_nested_message_size()); - EXPECT_EQ(9, message1.repeated_nested_message(0).bb()); - ASSERT_EQ(1, message1.repeated_nested_enum_size()); - EXPECT_EQ(unittest::TestAllTypes::BAZ, message1.repeated_nested_enum(0)); - - EXPECT_EQ(123, message2.optional_int32()); - EXPECT_EQ("abc", message2.optional_string()); - EXPECT_EQ(1, message2.optional_nested_message().bb()); - EXPECT_EQ(unittest::TestAllTypes::FOO, message2.optional_nested_enum()); - ASSERT_EQ(2, message2.repeated_int32_size()); - EXPECT_EQ(1, message2.repeated_int32(0)); - EXPECT_EQ(2, message2.repeated_int32(1)); - ASSERT_EQ(2, message2.repeated_string_size()); - EXPECT_EQ("a", message2.repeated_string(0)); - EXPECT_EQ("b", message2.repeated_string(1)); - ASSERT_EQ(2, message2.repeated_nested_message_size()); - EXPECT_EQ(7, message2.repeated_nested_message(0).bb()); - EXPECT_EQ(8, message2.repeated_nested_message(1).bb()); - ASSERT_EQ(2, message2.repeated_nested_enum_size()); - EXPECT_EQ(unittest::TestAllTypes::FOO, message2.repeated_nested_enum(0)); - EXPECT_EQ(unittest::TestAllTypes::BAR, message2.repeated_nested_enum(1)); -} - -TEST(GeneratedMessageTest, ADLSwap) { - unittest::TestAllTypes message1, message2; - TestUtil::SetAllFields(&message1); - - // Note the address of one of the repeated fields, to verify it was swapped - // rather than copied. - const int32* addr = &message1.repeated_int32().Get(0); - - using std::swap; - swap(message1, message2); - - TestUtil::ExpectAllFieldsSet(message2); - TestUtil::ExpectClear(message1); - - EXPECT_EQ(addr, &message2.repeated_int32().Get(0)); -} - -TEST(GeneratedMessageTest, CopyConstructor) { - // All set. - { - unittest::TestAllTypes message1; - TestUtil::SetAllFields(&message1); - - unittest::TestAllTypes message2(message1); - TestUtil::ExpectAllFieldsSet(message2); - } - - // None set. - { - unittest::TestAllTypes message1; - unittest::TestAllTypes message2(message1); - - EXPECT_FALSE(message1.has_optional_string()); - EXPECT_FALSE(message2.has_optional_string()); - EXPECT_EQ(&message1.optional_string(), - &message2.optional_string()); - - EXPECT_FALSE(message1.has_optional_bytes()); - EXPECT_FALSE(message2.has_optional_bytes()); - EXPECT_EQ(&message1.optional_bytes(), - &message2.optional_bytes()); - - EXPECT_FALSE(message1.has_optional_nested_message()); - EXPECT_FALSE(message2.has_optional_nested_message()); - EXPECT_EQ(&message1.optional_nested_message(), - &message2.optional_nested_message()); - - EXPECT_FALSE(message1.has_optional_foreign_message()); - EXPECT_FALSE(message2.has_optional_foreign_message()); - EXPECT_EQ(&message1.optional_foreign_message(), - &message2.optional_foreign_message()); - - EXPECT_FALSE(message1.has_optional_import_message()); - EXPECT_FALSE(message2.has_optional_import_message()); - EXPECT_EQ(&message1.optional_import_message(), - &message2.optional_import_message()); - - EXPECT_FALSE(message1.has_optional_public_import_message()); - EXPECT_FALSE(message2.has_optional_public_import_message()); - EXPECT_EQ(&message1.optional_public_import_message(), - &message2.optional_public_import_message()); - - EXPECT_FALSE(message1.has_optional_lazy_message()); - EXPECT_FALSE(message2.has_optional_lazy_message()); - EXPECT_EQ(&message1.optional_lazy_message(), - &message2.optional_lazy_message()); - } -} - -TEST(GeneratedMessageTest, CopyConstructorWithArenas) { - Arena arena; - unittest::TestAllTypes* message1 = - Arena::CreateMessage<unittest::TestAllTypes>(&arena); - TestUtil::SetAllFields(message1); - - unittest::TestAllTypes message2_stack(*message1); - TestUtil::ExpectAllFieldsSet(message2_stack); - - google::protobuf::scoped_ptr<unittest::TestAllTypes> message2_heap( - new unittest::TestAllTypes(*message1)); - TestUtil::ExpectAllFieldsSet(*message2_heap); - - arena.Reset(); - - // Verify that the copies are still intact. - TestUtil::ExpectAllFieldsSet(message2_stack); - TestUtil::ExpectAllFieldsSet(*message2_heap); -} - -TEST(GeneratedMessageTest, CopyAssignmentOperator) { - unittest::TestAllTypes message1; - TestUtil::SetAllFields(&message1); - - unittest::TestAllTypes message2; - message2 = message1; - TestUtil::ExpectAllFieldsSet(message2); - - // Make sure that self-assignment does something sane. - message2.operator=(message2); - TestUtil::ExpectAllFieldsSet(message2); -} - -#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \ - !defined(GOOGLE_PROTOBUF_NO_RTTI) -TEST(GeneratedMessageTest, UpcastCopyFrom) { - // Test the CopyFrom method that takes in the generic const Message& - // parameter. - unittest::TestAllTypes message1, message2; - - TestUtil::SetAllFields(&message1); - - const Message* source = implicit_cast<const Message*>(&message1); - message2.CopyFrom(*source); - - TestUtil::ExpectAllFieldsSet(message2); -} -#endif - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - -TEST(GeneratedMessageTest, DynamicMessageCopyFrom) { - // Test copying from a DynamicMessage, which must fall back to using - // reflection. - unittest::TestAllTypes message2; - - // Construct a new version of the dynamic message via the factory. - DynamicMessageFactory factory; - google::protobuf::scoped_ptr<Message> message1; - message1.reset(factory.GetPrototype( - unittest::TestAllTypes::descriptor())->New()); - - TestUtil::ReflectionTester reflection_tester( - unittest::TestAllTypes::descriptor()); - reflection_tester.SetAllFieldsViaReflection(message1.get()); - - message2.CopyFrom(*message1); - - TestUtil::ExpectAllFieldsSet(message2); -} - -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS - -TEST(GeneratedMessageTest, NonEmptyMergeFrom) { - // Test merging with a non-empty message. Code is a modified form - // of that found in google/protobuf/reflection_ops_unittest.cc. - unittest::TestAllTypes message1, message2; - - TestUtil::SetAllFields(&message1); - - // This field will test merging into an empty spot. - message2.set_optional_int32(message1.optional_int32()); - message1.clear_optional_int32(); - - // This tests overwriting. - message2.set_optional_string(message1.optional_string()); - message1.set_optional_string("something else"); - - // This tests concatenating. - message2.add_repeated_int32(message1.repeated_int32(1)); - int32 i = message1.repeated_int32(0); - message1.clear_repeated_int32(); - message1.add_repeated_int32(i); - - message1.MergeFrom(message2); - - TestUtil::ExpectAllFieldsSet(message1); -} - - -// Test the generated SerializeWithCachedSizesToArray(), -TEST(GeneratedMessageTest, SerializationToArray) { - unittest::TestAllTypes message1, message2; - string data; - TestUtil::SetAllFields(&message1); - int size = message1.ByteSize(); - data.resize(size); - uint8* start = reinterpret_cast<uint8*>(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - TestUtil::ExpectAllFieldsSet(message2); - -} - -TEST(GeneratedMessageTest, PackedFieldsSerializationToArray) { - unittest::TestPackedTypes packed_message1, packed_message2; - string packed_data; - TestUtil::SetPackedFields(&packed_message1); - int packed_size = packed_message1.ByteSize(); - packed_data.resize(packed_size); - uint8* start = reinterpret_cast<uint8*>(string_as_array(&packed_data)); - uint8* end = packed_message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(packed_size, end - start); - EXPECT_TRUE(packed_message2.ParseFromString(packed_data)); - TestUtil::ExpectPackedFieldsSet(packed_message2); -} - -// Test the generated SerializeWithCachedSizes() by forcing the buffer to write -// one byte at a time. -TEST(GeneratedMessageTest, SerializationToStream) { - unittest::TestAllTypes message1, message2; - TestUtil::SetAllFields(&message1); - int size = message1.ByteSize(); - string data; - data.resize(size); - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - message1.SerializeWithCachedSizes(&output_stream); - EXPECT_FALSE(output_stream.HadError()); - EXPECT_EQ(size, output_stream.ByteCount()); - } - EXPECT_TRUE(message2.ParseFromString(data)); - TestUtil::ExpectAllFieldsSet(message2); - -} - -TEST(GeneratedMessageTest, PackedFieldsSerializationToStream) { - unittest::TestPackedTypes message1, message2; - TestUtil::SetPackedFields(&message1); - int size = message1.ByteSize(); - string data; - data.resize(size); - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - message1.SerializeWithCachedSizes(&output_stream); - EXPECT_FALSE(output_stream.HadError()); - EXPECT_EQ(size, output_stream.ByteCount()); - } - EXPECT_TRUE(message2.ParseFromString(data)); - TestUtil::ExpectPackedFieldsSet(message2); -} - - -TEST(GeneratedMessageTest, Required) { - // Test that IsInitialized() returns false if required fields are missing. - unittest::TestRequired message; - - EXPECT_FALSE(message.IsInitialized()); - message.set_a(1); - EXPECT_FALSE(message.IsInitialized()); - message.set_b(2); - EXPECT_FALSE(message.IsInitialized()); - message.set_c(3); - EXPECT_TRUE(message.IsInitialized()); -} - -TEST(GeneratedMessageTest, RequiredForeign) { - // Test that IsInitialized() returns false if required fields in nested - // messages are missing. - unittest::TestRequiredForeign message; - - EXPECT_TRUE(message.IsInitialized()); - - message.mutable_optional_message(); - EXPECT_FALSE(message.IsInitialized()); - - message.mutable_optional_message()->set_a(1); - message.mutable_optional_message()->set_b(2); - message.mutable_optional_message()->set_c(3); - EXPECT_TRUE(message.IsInitialized()); - - message.add_repeated_message(); - EXPECT_FALSE(message.IsInitialized()); - - message.mutable_repeated_message(0)->set_a(1); - message.mutable_repeated_message(0)->set_b(2); - message.mutable_repeated_message(0)->set_c(3); - EXPECT_TRUE(message.IsInitialized()); -} - -TEST(GeneratedMessageTest, ForeignNested) { - // Test that TestAllTypes::NestedMessage can be embedded directly into - // another message. - unittest::TestForeignNested message; - - // If this compiles and runs without crashing, it must work. We have - // nothing more to test. - unittest::TestAllTypes::NestedMessage* nested = - message.mutable_foreign_nested(); - nested->set_bb(1); -} - -TEST(GeneratedMessageTest, ReallyLargeTagNumber) { - // Test that really large tag numbers don't break anything. - unittest::TestReallyLargeTagNumber message1, message2; - string data; - - // For the most part, if this compiles and runs then we're probably good. - // (The most likely cause for failure would be if something were attempting - // to allocate a lookup table of some sort using tag numbers as the index.) - // We'll try serializing just for fun. - message1.set_a(1234); - message1.set_bb(5678); - message1.SerializeToString(&data); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(1234, message2.a()); - EXPECT_EQ(5678, message2.bb()); -} - -TEST(GeneratedMessageTest, MutualRecursion) { - // Test that mutually-recursive message types work. - unittest::TestMutualRecursionA message; - unittest::TestMutualRecursionA* nested = message.mutable_bb()->mutable_a(); - unittest::TestMutualRecursionA* nested2 = nested->mutable_bb()->mutable_a(); - - // Again, if the above compiles and runs, that's all we really have to - // test, but just for run we'll check that the system didn't somehow come - // up with a pointer loop... - EXPECT_NE(&message, nested); - EXPECT_NE(&message, nested2); - EXPECT_NE(nested, nested2); -} - -TEST(GeneratedMessageTest, CamelCaseFieldNames) { - // This test is mainly checking that the following compiles, which verifies - // that the field names were coerced to lower-case. - // - // Protocol buffers standard style is to use lowercase-with-underscores for - // field names. Some old proto1 .protos unfortunately used camel-case field - // names. In proto1, these names were forced to lower-case. So, we do the - // same thing in proto2. - - unittest::TestCamelCaseFieldNames message; - - message.set_primitivefield(2); - message.set_stringfield("foo"); - message.set_enumfield(unittest::FOREIGN_FOO); - message.mutable_messagefield()->set_c(6); - - message.add_repeatedprimitivefield(8); - message.add_repeatedstringfield("qux"); - message.add_repeatedenumfield(unittest::FOREIGN_BAR); - message.add_repeatedmessagefield()->set_c(15); - - EXPECT_EQ(2, message.primitivefield()); - EXPECT_EQ("foo", message.stringfield()); - EXPECT_EQ(unittest::FOREIGN_FOO, message.enumfield()); - EXPECT_EQ(6, message.messagefield().c()); - - EXPECT_EQ(8, message.repeatedprimitivefield(0)); - EXPECT_EQ("qux", message.repeatedstringfield(0)); - EXPECT_EQ(unittest::FOREIGN_BAR, message.repeatedenumfield(0)); - EXPECT_EQ(15, message.repeatedmessagefield(0).c()); -} - -TEST(GeneratedMessageTest, TestConflictingSymbolNames) { +TEST(GENERATED_MESSAGE_TEST_NAME, TestConflictingSymbolNames) { // test_bad_identifiers.proto successfully compiled, then it works. The // following is just a token usage to insure that the code is, in fact, // being compiled and linked. protobuf_unittest::TestConflictingSymbolNames message; message.set_uint32(1); - EXPECT_EQ(3, message.ByteSize()); + EXPECT_EQ(3, message.ByteSizeLong()); message.set_friend_(5); EXPECT_EQ(5, message.friend_()); @@ -948,7 +100,7 @@ TEST(GeneratedMessageTest, TestConflictingSymbolNames) { message.GetExtension(ExtensionMessage::repeated_int32_ext, 0)); } -TEST(GeneratedMessageTest, TestConflictingEnumNames) { +TEST(GENERATED_MESSAGE_TEST_NAME, TestConflictingEnumNames) { protobuf_unittest::TestConflictingEnumNames message; message.set_conflicting_enum(protobuf_unittest::TestConflictingEnumNames_NestedConflictingEnum_and_); EXPECT_EQ(1, message.conflicting_enum()); @@ -963,1366 +115,7 @@ TEST(GeneratedMessageTest, TestConflictingEnumNames) { EXPECT_EQ(3, conflicting_enum); } -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - -TEST(GeneratedMessageTest, TestOptimizedForSize) { - // We rely on the tests in reflection_ops_unittest and wire_format_unittest - // to really test that reflection-based methods work. Here we are mostly - // just making sure that TestOptimizedForSize actually builds and seems to - // function. - - protobuf_unittest::TestOptimizedForSize message, message2; - message.set_i(1); - message.mutable_msg()->set_c(2); - message2.CopyFrom(message); - EXPECT_EQ(1, message2.i()); - EXPECT_EQ(2, message2.msg().c()); -} - -TEST(GeneratedMessageTest, TestEmbedOptimizedForSize) { - // Verifies that something optimized for speed can contain something optimized - // for size. - - protobuf_unittest::TestEmbedOptimizedForSize message, message2; - message.mutable_optional_message()->set_i(1); - message.add_repeated_message()->mutable_msg()->set_c(2); - string data; - message.SerializeToString(&data); - ASSERT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(1, message2.optional_message().i()); - EXPECT_EQ(2, message2.repeated_message(0).msg().c()); -} - -TEST(GeneratedMessageTest, TestSpaceUsed) { - unittest::TestAllTypes message1; - // sizeof provides a lower bound on SpaceUsedLong(). - EXPECT_LE(sizeof(unittest::TestAllTypes), message1.SpaceUsedLong()); - const size_t empty_message_size = message1.SpaceUsedLong(); - - // Setting primitive types shouldn't affect the space used. - message1.set_optional_int32(123); - message1.set_optional_int64(12345); - message1.set_optional_uint32(123); - message1.set_optional_uint64(12345); - EXPECT_EQ(empty_message_size, message1.SpaceUsedLong()); - - // On some STL implementations, setting the string to a small value should - // only increase SpaceUsedLong() by the size of a string object, though this - // is not true everywhere. - message1.set_optional_string("abc"); - EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsedLong()); - - // Setting a string to a value larger than the string object itself should - // increase SpaceUsedLong(), because it cannot store the value internally. - message1.set_optional_string(string(sizeof(string) + 1, 'x')); - int min_expected_increase = message1.optional_string().capacity() + - sizeof(string); - EXPECT_LE(empty_message_size + min_expected_increase, - message1.SpaceUsedLong()); - - size_t previous_size = message1.SpaceUsedLong(); - // Adding an optional message should increase the size by the size of the - // nested message type. NestedMessage is simple enough (1 int field) that it - // is equal to sizeof(NestedMessage) - message1.mutable_optional_nested_message(); - ASSERT_EQ(sizeof(unittest::TestAllTypes::NestedMessage), - message1.optional_nested_message().SpaceUsedLong()); - EXPECT_EQ(previous_size + - sizeof(unittest::TestAllTypes::NestedMessage), - message1.SpaceUsedLong()); -} - -TEST(GeneratedMessageTest, TestOneofSpaceUsed) { - unittest::TestOneof2 message1; - EXPECT_LE(sizeof(unittest::TestOneof2), message1.SpaceUsedLong()); - - const size_t empty_message_size = message1.SpaceUsedLong(); - // Setting primitive types shouldn't affect the space used. - message1.set_foo_int(123); - message1.set_bar_int(12345); - EXPECT_EQ(empty_message_size, message1.SpaceUsedLong()); - - // Setting a string in oneof to a small value should only increase - // SpaceUsedLong() by the size of a string object. - message1.set_foo_string("abc"); - EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsedLong()); - - // Setting a string in oneof to a value larger than the string object itself - // should increase SpaceUsedLong(), because it cannot store the value - // internally. - message1.set_foo_string(string(sizeof(string) + 1, 'x')); - int min_expected_increase = message1.foo_string().capacity() + - sizeof(string); - EXPECT_LE(empty_message_size + min_expected_increase, - message1.SpaceUsedLong()); - - // Setting a message in oneof should delete the other fields and increase the - // size by the size of the nested message type. NestedMessage is simple enough - // that it is equal to sizeof(NestedMessage) - message1.mutable_foo_message(); - ASSERT_EQ(sizeof(unittest::TestOneof2::NestedMessage), - message1.foo_message().SpaceUsedLong()); - EXPECT_EQ(empty_message_size + - sizeof(unittest::TestOneof2::NestedMessage), - message1.SpaceUsedLong()); -} - -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS - - -TEST(GeneratedMessageTest, FieldConstantValues) { - unittest::TestRequired message; - EXPECT_EQ(unittest::TestAllTypes_NestedMessage::kBbFieldNumber, 1); - EXPECT_EQ(unittest::TestAllTypes::kOptionalInt32FieldNumber, 1); - EXPECT_EQ(unittest::TestAllTypes::kOptionalgroupFieldNumber, 16); - EXPECT_EQ(unittest::TestAllTypes::kOptionalNestedMessageFieldNumber, 18); - EXPECT_EQ(unittest::TestAllTypes::kOptionalNestedEnumFieldNumber, 21); - EXPECT_EQ(unittest::TestAllTypes::kRepeatedInt32FieldNumber, 31); - EXPECT_EQ(unittest::TestAllTypes::kRepeatedgroupFieldNumber, 46); - EXPECT_EQ(unittest::TestAllTypes::kRepeatedNestedMessageFieldNumber, 48); - EXPECT_EQ(unittest::TestAllTypes::kRepeatedNestedEnumFieldNumber, 51); -} - -TEST(GeneratedMessageTest, ExtensionConstantValues) { - EXPECT_EQ(unittest::TestRequired::kSingleFieldNumber, 1000); - EXPECT_EQ(unittest::TestRequired::kMultiFieldNumber, 1001); - EXPECT_EQ(unittest::kOptionalInt32ExtensionFieldNumber, 1); - EXPECT_EQ(unittest::kOptionalgroupExtensionFieldNumber, 16); - EXPECT_EQ(unittest::kOptionalNestedMessageExtensionFieldNumber, 18); - EXPECT_EQ(unittest::kOptionalNestedEnumExtensionFieldNumber, 21); - EXPECT_EQ(unittest::kRepeatedInt32ExtensionFieldNumber, 31); - EXPECT_EQ(unittest::kRepeatedgroupExtensionFieldNumber, 46); - EXPECT_EQ(unittest::kRepeatedNestedMessageExtensionFieldNumber, 48); - EXPECT_EQ(unittest::kRepeatedNestedEnumExtensionFieldNumber, 51); -} - -TEST(GeneratedMessageTest, ParseFromTruncated) { - const string long_string = string(128, 'q'); - FileDescriptorProto p; - p.add_extension()->set_name(long_string); - const string msg = p.SerializeAsString(); - int successful_count = 0; - for (int i = 0; i <= msg.size(); i++) { - if (p.ParseFromArray(msg.c_str(), i)) { - ++successful_count; - } - } - // We don't really care about how often we succeeded. - // As long as we didn't crash, we're happy. - EXPECT_GE(successful_count, 1); -} - -// =================================================================== - -TEST(GeneratedEnumTest, EnumValuesAsSwitchCases) { - // Test that our nested enum values can be used as switch cases. This test - // doesn't actually do anything, the proof that it works is that it - // compiles. - int i =0; - unittest::TestAllTypes::NestedEnum a = unittest::TestAllTypes::BAR; - switch (a) { - case unittest::TestAllTypes::FOO: - i = 1; - break; - case unittest::TestAllTypes::BAR: - i = 2; - break; - case unittest::TestAllTypes::BAZ: - i = 3; - break; - case unittest::TestAllTypes::NEG: - i = -1; - break; - // no default case: We want to make sure the compiler recognizes that - // all cases are covered. (GCC warns if you do not cover all cases of - // an enum in a switch.) - } - - // Token check just for fun. - EXPECT_EQ(2, i); -} - -TEST(GeneratedEnumTest, IsValidValue) { - // Test enum IsValidValue. - EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(1)); - EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(2)); - EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(3)); - - EXPECT_FALSE(unittest::TestAllTypes::NestedEnum_IsValid(0)); - EXPECT_FALSE(unittest::TestAllTypes::NestedEnum_IsValid(4)); - - // Make sure it also works when there are dups. - EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(1)); - EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(2)); - EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(3)); - - EXPECT_FALSE(unittest::TestEnumWithDupValue_IsValid(0)); - EXPECT_FALSE(unittest::TestEnumWithDupValue_IsValid(4)); -} - -TEST(GeneratedEnumTest, MinAndMax) { - EXPECT_EQ(unittest::TestAllTypes::NEG, - unittest::TestAllTypes::NestedEnum_MIN); - EXPECT_EQ(unittest::TestAllTypes::BAZ, - unittest::TestAllTypes::NestedEnum_MAX); - EXPECT_EQ(4, unittest::TestAllTypes::NestedEnum_ARRAYSIZE); - - EXPECT_EQ(unittest::FOREIGN_FOO, unittest::ForeignEnum_MIN); - EXPECT_EQ(unittest::FOREIGN_BAZ, unittest::ForeignEnum_MAX); - EXPECT_EQ(7, unittest::ForeignEnum_ARRAYSIZE); - - EXPECT_EQ(1, unittest::TestEnumWithDupValue_MIN); - EXPECT_EQ(3, unittest::TestEnumWithDupValue_MAX); - EXPECT_EQ(4, unittest::TestEnumWithDupValue_ARRAYSIZE); - - EXPECT_EQ(unittest::SPARSE_E, unittest::TestSparseEnum_MIN); - EXPECT_EQ(unittest::SPARSE_C, unittest::TestSparseEnum_MAX); - EXPECT_EQ(12589235, unittest::TestSparseEnum_ARRAYSIZE); - - // Make sure we can take the address of _MIN, _MAX and _ARRAYSIZE. - void* null_pointer = 0; // NULL may be integer-type, not pointer-type. - EXPECT_NE(null_pointer, &unittest::TestAllTypes::NestedEnum_MIN); - EXPECT_NE(null_pointer, &unittest::TestAllTypes::NestedEnum_MAX); - EXPECT_NE(null_pointer, &unittest::TestAllTypes::NestedEnum_ARRAYSIZE); - - EXPECT_NE(null_pointer, &unittest::ForeignEnum_MIN); - EXPECT_NE(null_pointer, &unittest::ForeignEnum_MAX); - EXPECT_NE(null_pointer, &unittest::ForeignEnum_ARRAYSIZE); - - // Make sure we can use _MIN and _MAX as switch cases. - switch (unittest::SPARSE_A) { - case unittest::TestSparseEnum_MIN: - case unittest::TestSparseEnum_MAX: - break; - default: - break; - } -} - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - -TEST(GeneratedEnumTest, Name) { - // "Names" in the presence of dup values are a bit arbitrary. - EXPECT_EQ("FOO1", unittest::TestEnumWithDupValue_Name(unittest::FOO1)); - EXPECT_EQ("FOO1", unittest::TestEnumWithDupValue_Name(unittest::FOO2)); - - EXPECT_EQ("SPARSE_A", unittest::TestSparseEnum_Name(unittest::SPARSE_A)); - EXPECT_EQ("SPARSE_B", unittest::TestSparseEnum_Name(unittest::SPARSE_B)); - EXPECT_EQ("SPARSE_C", unittest::TestSparseEnum_Name(unittest::SPARSE_C)); - EXPECT_EQ("SPARSE_D", unittest::TestSparseEnum_Name(unittest::SPARSE_D)); - EXPECT_EQ("SPARSE_E", unittest::TestSparseEnum_Name(unittest::SPARSE_E)); - EXPECT_EQ("SPARSE_F", unittest::TestSparseEnum_Name(unittest::SPARSE_F)); - EXPECT_EQ("SPARSE_G", unittest::TestSparseEnum_Name(unittest::SPARSE_G)); -} - -TEST(GeneratedEnumTest, Parse) { - unittest::TestEnumWithDupValue dup_value = unittest::FOO1; - EXPECT_TRUE(unittest::TestEnumWithDupValue_Parse("FOO1", &dup_value)); - EXPECT_EQ(unittest::FOO1, dup_value); - EXPECT_TRUE(unittest::TestEnumWithDupValue_Parse("FOO2", &dup_value)); - EXPECT_EQ(unittest::FOO2, dup_value); - EXPECT_FALSE(unittest::TestEnumWithDupValue_Parse("FOO", &dup_value)); -} - -TEST(GeneratedEnumTest, GetEnumDescriptor) { - EXPECT_EQ(unittest::TestAllTypes::NestedEnum_descriptor(), - GetEnumDescriptor<unittest::TestAllTypes::NestedEnum>()); - EXPECT_EQ(unittest::ForeignEnum_descriptor(), - GetEnumDescriptor<unittest::ForeignEnum>()); - EXPECT_EQ(unittest::TestEnumWithDupValue_descriptor(), - GetEnumDescriptor<unittest::TestEnumWithDupValue>()); - EXPECT_EQ(unittest::TestSparseEnum_descriptor(), - GetEnumDescriptor<unittest::TestSparseEnum>()); -} - -enum NonProtoEnum { - kFoo = 1, -}; - -TEST(GeneratedEnumTest, IsProtoEnumTypeTrait) { - EXPECT_TRUE(is_proto_enum<unittest::TestAllTypes::NestedEnum>::value); - EXPECT_TRUE(is_proto_enum<unittest::ForeignEnum>::value); - EXPECT_TRUE(is_proto_enum<unittest::TestEnumWithDupValue>::value); - EXPECT_TRUE(is_proto_enum<unittest::TestSparseEnum>::value); - - EXPECT_FALSE(is_proto_enum<int>::value); - EXPECT_FALSE(is_proto_enum<NonProtoEnum>::value); -} - -#endif // PROTOBUF_TEST_NO_DESCRIPTORS - -// =================================================================== - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - -// Support code for testing services. -class GeneratedServiceTest : public testing::Test { - protected: - class MockTestService : public unittest::TestService { - public: - MockTestService() - : called_(false), - method_(""), - controller_(NULL), - request_(NULL), - response_(NULL), - done_(NULL) {} - - ~MockTestService() {} - - void Reset() { called_ = false; } - - // implements TestService ---------------------------------------- - - void Foo(RpcController* controller, - const unittest::FooRequest* request, - unittest::FooResponse* response, - Closure* done) { - ASSERT_FALSE(called_); - called_ = true; - method_ = "Foo"; - controller_ = controller; - request_ = request; - response_ = response; - done_ = done; - } - - void Bar(RpcController* controller, - const unittest::BarRequest* request, - unittest::BarResponse* response, - Closure* done) { - ASSERT_FALSE(called_); - called_ = true; - method_ = "Bar"; - controller_ = controller; - request_ = request; - response_ = response; - done_ = done; - } - - // --------------------------------------------------------------- - - bool called_; - string method_; - RpcController* controller_; - const Message* request_; - Message* response_; - Closure* done_; - }; - - class MockRpcChannel : public RpcChannel { - public: - MockRpcChannel() - : called_(false), - method_(NULL), - controller_(NULL), - request_(NULL), - response_(NULL), - done_(NULL), - destroyed_(NULL) {} - - ~MockRpcChannel() { - if (destroyed_ != NULL) *destroyed_ = true; - } - - void Reset() { called_ = false; } - - // implements TestService ---------------------------------------- - - void CallMethod(const MethodDescriptor* method, - RpcController* controller, - const Message* request, - Message* response, - Closure* done) { - ASSERT_FALSE(called_); - called_ = true; - method_ = method; - controller_ = controller; - request_ = request; - response_ = response; - done_ = done; - } - - // --------------------------------------------------------------- - - bool called_; - const MethodDescriptor* method_; - RpcController* controller_; - const Message* request_; - Message* response_; - Closure* done_; - bool* destroyed_; - }; - - class MockController : public RpcController { - public: - void Reset() { - ADD_FAILURE() << "Reset() not expected during this test."; - } - bool Failed() const { - ADD_FAILURE() << "Failed() not expected during this test."; - return false; - } - string ErrorText() const { - ADD_FAILURE() << "ErrorText() not expected during this test."; - return ""; - } - void StartCancel() { - ADD_FAILURE() << "StartCancel() not expected during this test."; - } - void SetFailed(const string& reason) { - ADD_FAILURE() << "SetFailed() not expected during this test."; - } - bool IsCanceled() const { - ADD_FAILURE() << "IsCanceled() not expected during this test."; - return false; - } - void NotifyOnCancel(Closure* callback) { - ADD_FAILURE() << "NotifyOnCancel() not expected during this test."; - } - }; - - GeneratedServiceTest() - : descriptor_(unittest::TestService::descriptor()), - foo_(descriptor_->FindMethodByName("Foo")), - bar_(descriptor_->FindMethodByName("Bar")), - stub_(&mock_channel_), - done_(::google::protobuf::NewPermanentCallback(&DoNothing)) {} - - virtual void SetUp() { - ASSERT_TRUE(foo_ != NULL); - ASSERT_TRUE(bar_ != NULL); - } - - const ServiceDescriptor* descriptor_; - const MethodDescriptor* foo_; - const MethodDescriptor* bar_; - - MockTestService mock_service_; - MockController mock_controller_; - - MockRpcChannel mock_channel_; - unittest::TestService::Stub stub_; - - // Just so we don't have to re-define these with every test. - unittest::FooRequest foo_request_; - unittest::FooResponse foo_response_; - unittest::BarRequest bar_request_; - unittest::BarResponse bar_response_; - google::protobuf::scoped_ptr<Closure> done_; -}; - -TEST_F(GeneratedServiceTest, GetDescriptor) { - // Test that GetDescriptor() works. - - EXPECT_EQ(descriptor_, mock_service_.GetDescriptor()); -} - -TEST_F(GeneratedServiceTest, GetChannel) { - EXPECT_EQ(&mock_channel_, stub_.channel()); -} - -TEST_F(GeneratedServiceTest, OwnsChannel) { - MockRpcChannel* channel = new MockRpcChannel; - bool destroyed = false; - channel->destroyed_ = &destroyed; - - { - unittest::TestService::Stub owning_stub(channel, - Service::STUB_OWNS_CHANNEL); - EXPECT_FALSE(destroyed); - } - - EXPECT_TRUE(destroyed); -} - -TEST_F(GeneratedServiceTest, CallMethod) { - // Test that CallMethod() works. - - // Call Foo() via CallMethod(). - mock_service_.CallMethod(foo_, &mock_controller_, - &foo_request_, &foo_response_, done_.get()); - - ASSERT_TRUE(mock_service_.called_); - - EXPECT_EQ("Foo" , mock_service_.method_ ); - EXPECT_EQ(&mock_controller_, mock_service_.controller_); - EXPECT_EQ(&foo_request_ , mock_service_.request_ ); - EXPECT_EQ(&foo_response_ , mock_service_.response_ ); - EXPECT_EQ(done_.get() , mock_service_.done_ ); - - // Try again, but call Bar() instead. - mock_service_.Reset(); - mock_service_.CallMethod(bar_, &mock_controller_, - &bar_request_, &bar_response_, done_.get()); - - ASSERT_TRUE(mock_service_.called_); - EXPECT_EQ("Bar", mock_service_.method_); -} - -TEST_F(GeneratedServiceTest, CallMethodTypeFailure) { - // Verify death if we call Foo() with Bar's message types. - -#ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet - EXPECT_DEBUG_DEATH( - mock_service_.CallMethod(foo_, &mock_controller_, - &foo_request_, &bar_response_, done_.get()), - "dynamic_cast"); - - mock_service_.Reset(); - EXPECT_DEBUG_DEATH( - mock_service_.CallMethod(foo_, &mock_controller_, - &bar_request_, &foo_response_, done_.get()), - "dynamic_cast"); -#endif // PROTOBUF_HAS_DEATH_TEST -} - -TEST_F(GeneratedServiceTest, GetPrototypes) { - // Test Get{Request,Response}Prototype() methods. - - EXPECT_EQ(&unittest::FooRequest::default_instance(), - &mock_service_.GetRequestPrototype(foo_)); - EXPECT_EQ(&unittest::BarRequest::default_instance(), - &mock_service_.GetRequestPrototype(bar_)); - - EXPECT_EQ(&unittest::FooResponse::default_instance(), - &mock_service_.GetResponsePrototype(foo_)); - EXPECT_EQ(&unittest::BarResponse::default_instance(), - &mock_service_.GetResponsePrototype(bar_)); -} - -TEST_F(GeneratedServiceTest, Stub) { - // Test that the stub class works. - - // Call Foo() via the stub. - stub_.Foo(&mock_controller_, &foo_request_, &foo_response_, done_.get()); - - ASSERT_TRUE(mock_channel_.called_); - - EXPECT_EQ(foo_ , mock_channel_.method_ ); - EXPECT_EQ(&mock_controller_, mock_channel_.controller_); - EXPECT_EQ(&foo_request_ , mock_channel_.request_ ); - EXPECT_EQ(&foo_response_ , mock_channel_.response_ ); - EXPECT_EQ(done_.get() , mock_channel_.done_ ); - - // Call Bar() via the stub. - mock_channel_.Reset(); - stub_.Bar(&mock_controller_, &bar_request_, &bar_response_, done_.get()); - - ASSERT_TRUE(mock_channel_.called_); - EXPECT_EQ(bar_, mock_channel_.method_); -} - -TEST_F(GeneratedServiceTest, NotImplemented) { - // Test that failing to implement a method of a service causes it to fail - // with a "not implemented" error message. - - // A service which doesn't implement any methods. - class UnimplementedService : public unittest::TestService { - public: - UnimplementedService() {} - }; - - UnimplementedService unimplemented_service; - - // And a controller which expects to get a "not implemented" error. - class ExpectUnimplementedController : public MockController { - public: - ExpectUnimplementedController() : called_(false) {} - - void SetFailed(const string& reason) { - EXPECT_FALSE(called_); - called_ = true; - EXPECT_EQ("Method Foo() not implemented.", reason); - } - - bool called_; - }; - - ExpectUnimplementedController controller; - - // Call Foo. - unimplemented_service.Foo(&controller, &foo_request_, &foo_response_, - done_.get()); - - EXPECT_TRUE(controller.called_); -} - -// =================================================================== - -class OneofTest : public testing::Test { - protected: - virtual void SetUp() { - } - - void ExpectEnumCasesWork(const unittest::TestOneof2 &message) { - switch (message.foo_case()) { - case unittest::TestOneof2::kFooInt: - EXPECT_TRUE(message.has_foo_int()); - break; - case unittest::TestOneof2::kFooString: - EXPECT_TRUE(message.has_foo_string()); - break; - case unittest::TestOneof2::kFooCord: - EXPECT_TRUE(message.has_foo_cord()); - break; - case unittest::TestOneof2::kFooStringPiece: - EXPECT_TRUE(message.has_foo_string_piece()); - break; - case unittest::TestOneof2::kFooBytes: - EXPECT_TRUE(message.has_foo_bytes()); - break; - case unittest::TestOneof2::kFooEnum: - EXPECT_TRUE(message.has_foo_enum()); - break; - case unittest::TestOneof2::kFooMessage: - EXPECT_TRUE(message.has_foo_message()); - break; - case unittest::TestOneof2::kFoogroup: - EXPECT_TRUE(message.has_foogroup()); - break; - case unittest::TestOneof2::kFooLazyMessage: - EXPECT_TRUE(message.has_foo_lazy_message()); - break; - case unittest::TestOneof2::FOO_NOT_SET: - break; - } - } -}; - -TEST_F(OneofTest, SettingOneFieldClearsOthers) { - unittest::TestOneof2 message; - - message.set_foo_int(123); - EXPECT_TRUE(message.has_foo_int()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); - - message.set_foo_string("foo"); - EXPECT_TRUE(message.has_foo_string()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); - - - message.set_foo_bytes("qux"); - EXPECT_TRUE(message.has_foo_bytes()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); - - message.set_foo_enum(unittest::TestOneof2::FOO); - EXPECT_TRUE(message.has_foo_enum()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); - - message.mutable_foo_message()->set_qux_int(234); - EXPECT_TRUE(message.has_foo_message()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); - - message.mutable_foogroup()->set_a(345); - EXPECT_TRUE(message.has_foogroup()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); - - - // we repeat this because we didn't test if this properly clears other fields - // at the beginning. - message.set_foo_int(123); - EXPECT_TRUE(message.has_foo_int()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); -} - -TEST_F(OneofTest, EnumCases) { - unittest::TestOneof2 message; - - message.set_foo_int(123); - ExpectEnumCasesWork(message); - message.set_foo_string("foo"); - ExpectEnumCasesWork(message); - message.set_foo_bytes("qux"); - ExpectEnumCasesWork(message); - message.set_foo_enum(unittest::TestOneof2::FOO); - ExpectEnumCasesWork(message); - message.mutable_foo_message()->set_qux_int(234); - ExpectEnumCasesWork(message); - message.mutable_foogroup()->set_a(345); - ExpectEnumCasesWork(message); -} - -TEST_F(OneofTest, PrimitiveType) { - unittest::TestOneof2 message; - // Unset field returns default value - EXPECT_EQ(message.foo_int(), 0); - - message.set_foo_int(123); - EXPECT_TRUE(message.has_foo_int()); - EXPECT_EQ(message.foo_int(), 123); - message.clear_foo_int(); - EXPECT_FALSE(message.has_foo_int()); -} - -TEST_F(OneofTest, EnumType) { - unittest::TestOneof2 message; - // Unset field returns default value - EXPECT_EQ(message.foo_enum(), 1); - - message.set_foo_enum(unittest::TestOneof2::FOO); - EXPECT_TRUE(message.has_foo_enum()); - EXPECT_EQ(message.foo_enum(), unittest::TestOneof2::FOO); - message.clear_foo_enum(); - EXPECT_FALSE(message.has_foo_enum()); -} - -TEST_F(OneofTest, SetString) { - // Check that setting a string field in various ways works - unittest::TestOneof2 message; - - // Unset field returns default value - EXPECT_EQ(message.foo_string(), ""); - - message.set_foo_string("foo"); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "foo"); - message.clear_foo_string(); - EXPECT_FALSE(message.has_foo_string()); - - message.set_foo_string(string("bar")); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "bar"); - message.clear_foo_string(); - EXPECT_FALSE(message.has_foo_string()); - - - message.set_foo_string("qux", 3); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "qux"); - message.clear_foo_string(); - EXPECT_FALSE(message.has_foo_string()); - - message.mutable_foo_string()->assign("quux"); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "quux"); - message.clear_foo_string(); - EXPECT_FALSE(message.has_foo_string()); - - message.set_foo_string("corge"); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "corge"); - message.clear_foo_string(); - EXPECT_FALSE(message.has_foo_string()); -} - -TEST_F(OneofTest, ReleaseString) { - // Check that release_foo() starts out NULL, and gives us a value - // that we can delete after it's been set. - unittest::TestOneof2 message; - - EXPECT_EQ(NULL, message.release_foo_string()); - EXPECT_FALSE(message.has_foo_string()); - - message.set_foo_string("blah"); - EXPECT_TRUE(message.has_foo_string()); - google::protobuf::scoped_ptr<string> str(message.release_foo_string()); - EXPECT_FALSE(message.has_foo_string()); - ASSERT_TRUE(str != NULL); - EXPECT_EQ("blah", *str); - - EXPECT_EQ(NULL, message.release_foo_string()); - EXPECT_FALSE(message.has_foo_string()); -} - -TEST_F(OneofTest, SetAllocatedString) { - // Check that set_allocated_foo() works for strings. - unittest::TestOneof2 message; - - EXPECT_FALSE(message.has_foo_string()); - const string kHello("hello"); - message.set_foo_string(kHello); - EXPECT_TRUE(message.has_foo_string()); - - message.set_allocated_foo_string(NULL); - EXPECT_FALSE(message.has_foo_string()); - EXPECT_EQ("", message.foo_string()); - - message.set_allocated_foo_string(new string(kHello)); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(kHello, message.foo_string()); -} - - -TEST_F(OneofTest, SetMessage) { - // Check that setting a message field works - unittest::TestOneof2 message; - - // Unset field returns default instance - EXPECT_EQ(&message.foo_message(), - &unittest::TestOneof2_NestedMessage::default_instance()); - EXPECT_EQ(message.foo_message().qux_int(), 0); - - message.mutable_foo_message()->set_qux_int(234); - EXPECT_TRUE(message.has_foo_message()); - EXPECT_EQ(message.foo_message().qux_int(), 234); - message.clear_foo_message(); - EXPECT_FALSE(message.has_foo_message()); -} - -TEST_F(OneofTest, ReleaseMessage) { - // Check that release_foo() starts out NULL, and gives us a value - // that we can delete after it's been set. - unittest::TestOneof2 message; - - EXPECT_EQ(NULL, message.release_foo_message()); - EXPECT_FALSE(message.has_foo_message()); - - message.mutable_foo_message()->set_qux_int(1); - EXPECT_TRUE(message.has_foo_message()); - google::protobuf::scoped_ptr<unittest::TestOneof2_NestedMessage> mes( - message.release_foo_message()); - EXPECT_FALSE(message.has_foo_message()); - ASSERT_TRUE(mes != NULL); - EXPECT_EQ(1, mes->qux_int()); - - EXPECT_EQ(NULL, message.release_foo_message()); - EXPECT_FALSE(message.has_foo_message()); -} - -TEST_F(OneofTest, SetAllocatedMessage) { - // Check that set_allocated_foo() works for messages. - unittest::TestOneof2 message; - - EXPECT_FALSE(message.has_foo_message()); - - message.mutable_foo_message()->set_qux_int(1); - EXPECT_TRUE(message.has_foo_message()); - - message.set_allocated_foo_message(NULL); - EXPECT_FALSE(message.has_foo_message()); - EXPECT_EQ(&message.foo_message(), - &unittest::TestOneof2_NestedMessage::default_instance()); - - message.mutable_foo_message()->set_qux_int(1); - unittest::TestOneof2_NestedMessage* mes = message.release_foo_message(); - ASSERT_TRUE(mes != NULL); - EXPECT_FALSE(message.has_foo_message()); - - message.set_allocated_foo_message(mes); - EXPECT_TRUE(message.has_foo_message()); - EXPECT_EQ(1, message.foo_message().qux_int()); -} - - -TEST_F(OneofTest, Clear) { - unittest::TestOneof2 message; - - message.set_foo_int(1); - EXPECT_TRUE(message.has_foo_int()); - message.clear_foo_int(); - EXPECT_FALSE(message.has_foo_int()); -} - -TEST_F(OneofTest, Defaults) { - unittest::TestOneof2 message; - - EXPECT_FALSE(message.has_foo_int()); - EXPECT_EQ(message.foo_int(), 0); - - EXPECT_FALSE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), ""); - - - EXPECT_FALSE(message.has_foo_bytes()); - EXPECT_EQ(message.foo_bytes(), ""); - - EXPECT_FALSE(message.has_foo_enum()); - EXPECT_EQ(message.foo_enum(), 1); - - EXPECT_FALSE(message.has_foo_message()); - EXPECT_EQ(message.foo_message().qux_int(), 0); - - EXPECT_FALSE(message.has_foogroup()); - EXPECT_EQ(message.foogroup().a(), 0); - - - EXPECT_FALSE(message.has_bar_int()); - EXPECT_EQ(message.bar_int(), 5); - - EXPECT_FALSE(message.has_bar_string()); - EXPECT_EQ(message.bar_string(), "STRING"); - - - EXPECT_FALSE(message.has_bar_bytes()); - EXPECT_EQ(message.bar_bytes(), "BYTES"); - - EXPECT_FALSE(message.has_bar_enum()); - EXPECT_EQ(message.bar_enum(), 2); -} - -TEST_F(OneofTest, SwapWithEmpty) { - unittest::TestOneof2 message1, message2; - message1.set_foo_string("FOO"); - EXPECT_TRUE(message1.has_foo_string()); - message1.Swap(&message2); - EXPECT_FALSE(message1.has_foo_string()); - EXPECT_TRUE(message2.has_foo_string()); - EXPECT_EQ(message2.foo_string(), "FOO"); -} - -TEST_F(OneofTest, SwapWithSelf) { - unittest::TestOneof2 message; - message.set_foo_string("FOO"); - EXPECT_TRUE(message.has_foo_string()); - message.Swap(&message); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "FOO"); -} - -TEST_F(OneofTest, SwapBothHasFields) { - unittest::TestOneof2 message1, message2; - - message1.set_foo_string("FOO"); - EXPECT_TRUE(message1.has_foo_string()); - message2.mutable_foo_message()->set_qux_int(1); - EXPECT_TRUE(message2.has_foo_message()); - - message1.Swap(&message2); - EXPECT_FALSE(message1.has_foo_string()); - EXPECT_FALSE(message2.has_foo_message()); - EXPECT_TRUE(message1.has_foo_message()); - EXPECT_EQ(message1.foo_message().qux_int(), 1); - EXPECT_TRUE(message2.has_foo_string()); - EXPECT_EQ(message2.foo_string(), "FOO"); -} - -TEST_F(OneofTest, CopyConstructor) { - unittest::TestOneof2 message1; - message1.set_foo_bytes("FOO"); - - unittest::TestOneof2 message2(message1); - EXPECT_TRUE(message2.has_foo_bytes()); - EXPECT_EQ(message2.foo_bytes(), "FOO"); -} - -TEST_F(OneofTest, CopyFrom) { - unittest::TestOneof2 message1, message2; - message1.set_foo_enum(unittest::TestOneof2::BAR); - EXPECT_TRUE(message1.has_foo_enum()); - - message2.CopyFrom(message1); - EXPECT_TRUE(message2.has_foo_enum()); - EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::BAR); - - // Copying from self should be a no-op. - message2.CopyFrom(message2); - EXPECT_TRUE(message2.has_foo_enum()); - EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::BAR); -} - -TEST_F(OneofTest, CopyAssignmentOperator) { - unittest::TestOneof2 message1; - message1.mutable_foo_message()->set_qux_int(123); - EXPECT_TRUE(message1.has_foo_message()); - - unittest::TestOneof2 message2; - message2 = message1; - EXPECT_EQ(message2.foo_message().qux_int(), 123); - - // Make sure that self-assignment does something sane. - message2 = message2; - EXPECT_EQ(message2.foo_message().qux_int(), 123); -} - -TEST_F(OneofTest, UpcastCopyFrom) { - // Test the CopyFrom method that takes in the generic const Message& - // parameter. - unittest::TestOneof2 message1, message2; - message1.mutable_foogroup()->set_a(123); - EXPECT_TRUE(message1.has_foogroup()); - - const Message* source = implicit_cast<const Message*>(&message1); - message2.CopyFrom(*source); - - EXPECT_TRUE(message2.has_foogroup()); - EXPECT_EQ(message2.foogroup().a(), 123); -} - -// Test the generated SerializeWithCachedSizesToArray(), -// This indirectly tests MergePartialFromCodedStream() -// We have to test each field type separately because we cannot set them at the -// same time -TEST_F(OneofTest, SerializationToArray) { - // Primitive type - { - unittest::TestOneof2 message1, message2; - string data; - message1.set_foo_int(123); - int size = message1.ByteSize(); - data.resize(size); - uint8* start = reinterpret_cast<uint8*>(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_int(), 123); - } - - // String - { - unittest::TestOneof2 message1, message2; - string data; - message1.set_foo_string("foo"); - int size = message1.ByteSize(); - data.resize(size); - uint8* start = reinterpret_cast<uint8*>(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_string(), "foo"); - } - - - // Bytes - { - unittest::TestOneof2 message1, message2; - string data; - message1.set_foo_bytes("qux"); - int size = message1.ByteSize(); - data.resize(size); - uint8* start = reinterpret_cast<uint8*>(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_bytes(), "qux"); - } - - // Enum - { - unittest::TestOneof2 message1, message2; - string data; - message1.set_foo_enum(unittest::TestOneof2::FOO); - int size = message1.ByteSize(); - data.resize(size); - uint8* start = reinterpret_cast<uint8*>(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::FOO); - } - - // Message - { - unittest::TestOneof2 message1, message2; - string data; - message1.mutable_foo_message()->set_qux_int(234); - int size = message1.ByteSize(); - data.resize(size); - uint8* start = reinterpret_cast<uint8*>(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_message().qux_int(), 234); - } - - // Group - { - unittest::TestOneof2 message1, message2; - string data; - message1.mutable_foogroup()->set_a(345); - int size = message1.ByteSize(); - data.resize(size); - uint8* start = reinterpret_cast<uint8*>(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foogroup().a(), 345); - } - -} - -// Test the generated SerializeWithCachedSizes() by forcing the buffer to write -// one byte at a time. -// This indirectly tests MergePartialFromCodedStream() -// We have to test each field type separately because we cannot set them at the -// same time -TEST_F(OneofTest, SerializationToStream) { - // Primitive type - { - unittest::TestOneof2 message1, message2; - string data; - message1.set_foo_int(123); - int size = message1.ByteSize(); - data.resize(size); - - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - message1.SerializeWithCachedSizes(&output_stream); - EXPECT_FALSE(output_stream.HadError()); - EXPECT_EQ(size, output_stream.ByteCount()); - } - - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_int(), 123); - } - - // String - { - unittest::TestOneof2 message1, message2; - string data; - message1.set_foo_string("foo"); - int size = message1.ByteSize(); - data.resize(size); - - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - message1.SerializeWithCachedSizes(&output_stream); - EXPECT_FALSE(output_stream.HadError()); - EXPECT_EQ(size, output_stream.ByteCount()); - } - - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_string(), "foo"); - } - - - // Bytes - { - unittest::TestOneof2 message1, message2; - string data; - message1.set_foo_bytes("qux"); - int size = message1.ByteSize(); - data.resize(size); - - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - message1.SerializeWithCachedSizes(&output_stream); - EXPECT_FALSE(output_stream.HadError()); - EXPECT_EQ(size, output_stream.ByteCount()); - } - - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_bytes(), "qux"); - } - - // Enum - { - unittest::TestOneof2 message1, message2; - string data; - message1.set_foo_enum(unittest::TestOneof2::FOO); - int size = message1.ByteSize(); - data.resize(size); - - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - message1.SerializeWithCachedSizes(&output_stream); - EXPECT_FALSE(output_stream.HadError()); - EXPECT_EQ(size, output_stream.ByteCount()); - } - - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::FOO); - } - - // Message - { - unittest::TestOneof2 message1, message2; - string data; - message1.mutable_foo_message()->set_qux_int(234); - int size = message1.ByteSize(); - data.resize(size); - - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - message1.SerializeWithCachedSizes(&output_stream); - EXPECT_FALSE(output_stream.HadError()); - EXPECT_EQ(size, output_stream.ByteCount()); - } - - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_message().qux_int(), 234); - } - - // Group - { - unittest::TestOneof2 message1, message2; - string data; - message1.mutable_foogroup()->set_a(345); - int size = message1.ByteSize(); - data.resize(size); - - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - message1.SerializeWithCachedSizes(&output_stream); - EXPECT_FALSE(output_stream.HadError()); - EXPECT_EQ(size, output_stream.ByteCount()); - } - - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foogroup().a(), 345); - } - -} - -TEST_F(OneofTest, MergeFrom) { - unittest::TestOneof2 message1, message2; - - message1.set_foo_int(123); - message2.MergeFrom(message1); - TestUtil::ExpectAtMostOneFieldSetInOneof(message2); - EXPECT_TRUE(message2.has_foo_int()); - EXPECT_EQ(message2.foo_int(), 123); - - message1.set_foo_string("foo"); - message2.MergeFrom(message1); - TestUtil::ExpectAtMostOneFieldSetInOneof(message2); - EXPECT_TRUE(message2.has_foo_string()); - EXPECT_EQ(message2.foo_string(), "foo"); - - - message1.set_foo_bytes("qux"); - message2.MergeFrom(message1); - TestUtil::ExpectAtMostOneFieldSetInOneof(message2); - EXPECT_TRUE(message2.has_foo_bytes()); - EXPECT_EQ(message2.foo_bytes(), "qux"); - - message1.set_foo_enum(unittest::TestOneof2::FOO); - message2.MergeFrom(message1); - TestUtil::ExpectAtMostOneFieldSetInOneof(message2); - EXPECT_TRUE(message2.has_foo_enum()); - EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::FOO); - - message1.mutable_foo_message()->set_qux_int(234); - message2.MergeFrom(message1); - TestUtil::ExpectAtMostOneFieldSetInOneof(message2); - EXPECT_TRUE(message2.has_foo_message()); - EXPECT_EQ(message2.foo_message().qux_int(), 234); - - message1.mutable_foogroup()->set_a(345); - message2.MergeFrom(message1); - TestUtil::ExpectAtMostOneFieldSetInOneof(message2); - EXPECT_TRUE(message2.has_foogroup()); - EXPECT_EQ(message2.foogroup().a(), 345); - -} - -TEST(HelpersTest, TestSCC) { - protobuf_unittest::TestMutualRecursionA a; - SCCAnalyzer scc_analyzer((Options())); - const SCC* scc = scc_analyzer.GetSCC(a.GetDescriptor()); - std::vector<string> names; - for (int i = 0; i < scc->descriptors.size(); i++) { - names.push_back(scc->descriptors[i]->full_name()); - } - ASSERT_EQ(names.size(), 4); - std::sort(names.begin(), names.end()); - EXPECT_EQ(names[0], "protobuf_unittest.TestMutualRecursionA"); - EXPECT_EQ(names[1], "protobuf_unittest.TestMutualRecursionA.SubGroup"); - EXPECT_EQ(names[2], "protobuf_unittest.TestMutualRecursionA.SubMessage"); - EXPECT_EQ(names[3], "protobuf_unittest.TestMutualRecursionB"); - - MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); - EXPECT_EQ(result.is_recursive, true); - EXPECT_EQ(result.contains_required, false); - EXPECT_EQ(result.contains_cord, true); // TestAllTypes - EXPECT_EQ(result.contains_extension, false); // TestAllTypes -} - -TEST(HelpersTest, TestSCCAnalysis) { - { - protobuf_unittest::TestRecursiveMessage msg; - SCCAnalyzer scc_analyzer((Options())); - const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor()); - MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); - EXPECT_EQ(result.is_recursive, true); - EXPECT_EQ(result.contains_required, false); - EXPECT_EQ(result.contains_cord, false); - EXPECT_EQ(result.contains_extension, false); - } - { - protobuf_unittest::TestAllExtensions msg; - SCCAnalyzer scc_analyzer((Options())); - const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor()); - MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); - EXPECT_EQ(result.is_recursive, false); - EXPECT_EQ(result.contains_required, false); - EXPECT_EQ(result.contains_cord, false); - EXPECT_EQ(result.contains_extension, true); - } - { - protobuf_unittest::TestRequired msg; - SCCAnalyzer scc_analyzer((Options())); - const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor()); - MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); - EXPECT_EQ(result.is_recursive, false); - EXPECT_EQ(result.contains_required, true); - EXPECT_EQ(result.contains_cord, false); - EXPECT_EQ(result.contains_extension, false); - } -} - -} // namespace cpp_unittest -} // namespace cpp -} // namespace compiler - -namespace no_generic_services_test { - // Verify that no class called "TestService" was defined in - // unittest_no_generic_services.pb.h by defining a different type by the same - // name. If such a service was generated, this will not compile. - struct TestService { - int i; - }; -} - -namespace compiler { -namespace cpp { -namespace cpp_unittest { - -TEST_F(GeneratedServiceTest, NoGenericServices) { - // Verify that non-services in unittest_no_generic_services.proto were - // generated. - no_generic_services_test::TestMessage message; - message.set_a(1); - message.SetExtension(no_generic_services_test::test_extension, 123); - no_generic_services_test::TestEnum e = no_generic_services_test::FOO; - EXPECT_EQ(e, 1); - - // Verify that a ServiceDescriptor is generated for the service even if the - // class itself is not. - const FileDescriptor* file = - no_generic_services_test::TestMessage::descriptor()->file(); - - ASSERT_EQ(1, file->service_count()); - EXPECT_EQ("TestService", file->service(0)->name()); - ASSERT_EQ(1, file->service(0)->method_count()); - EXPECT_EQ("Foo", file->service(0)->method(0)->name()); -} - -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS - -// =================================================================== - -// This test must run last. It verifies that descriptors were or were not -// initialized depending on whether PROTOBUF_TEST_NO_DESCRIPTORS was defined. -// When this is defined, we skip all tests which are expected to trigger -// descriptor initialization. This verifies that everything else still works -// if descriptors are not initialized. -TEST(DescriptorInitializationTest, Initialized) { -#ifdef PROTOBUF_TEST_NO_DESCRIPTORS - bool should_have_descriptors = false; -#else - bool should_have_descriptors = true; -#endif - - EXPECT_EQ(should_have_descriptors, - DescriptorPool::generated_pool()->InternalIsFileLoaded( - "google/protobuf/unittest.proto")); -} - } // namespace cpp_unittest - } // namespace cpp } // namespace compiler } // namespace protobuf diff --git a/src/google/protobuf/compiler/cpp/cpp_unittest.inc b/src/google/protobuf/compiler/cpp/cpp_unittest.inc new file mode 100644 index 00000000..ff6354f8 --- /dev/null +++ b/src/google/protobuf/compiler/cpp/cpp_unittest.inc @@ -0,0 +1,2281 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. +// +// To test the code generator, we actually use it to generate code for +// google/protobuf/unittest.proto, then test that. This means that we +// are actually testing the parser and other parts of the system at the same +// time, and that problems in the generator may show up as compile-time errors +// rather than unittest failures, which may be surprising. However, testing +// the output of the C++ generator directly would be very hard. We can't very +// well just check it against golden files since those files would have to be +// updated for any small change; such a test would be very brittle and probably +// not very helpful. What we really want to test is that the code compiles +// correctly and produces the interfaces we expect, which is why this test +// is written this way. + +#include <google/protobuf/compiler/cpp/cpp_unittest.h> + +#include <memory> +#include <vector> + +#include <google/protobuf/unittest_no_arena.pb.h> +#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER) +// We exclude this large proto from cmake build because it's too large for +// visual studio to compile (report internal errors). +#include <google/protobuf/unittest_enormous_descriptor.pb.h> +#endif +#include <google/protobuf/compiler/cpp/cpp_helpers.h> +#include <google/protobuf/compiler/cpp/cpp_test_bad_identifiers.pb.h> +#include <google/protobuf/compiler/importer.h> +#include <google/protobuf/unittest_no_generic_services.pb.h> +#include <google/protobuf/io/coded_stream.h> +#include <google/protobuf/io/zero_copy_stream_impl.h> +#include <google/protobuf/descriptor.pb.h> +#include <google/protobuf/arena.h> +#include <google/protobuf/descriptor.h> +#include <google/protobuf/dynamic_message.h> + +#include <google/protobuf/stubs/callback.h> +#include <google/protobuf/stubs/common.h> +#include <google/protobuf/stubs/logging.h> +#include <google/protobuf/stubs/substitute.h> +#include <google/protobuf/testing/googletest.h> +#include <gtest/gtest.h> +#include <google/protobuf/stubs/stl_util.h> + +namespace google { +namespace protobuf { +namespace compiler { +namespace cpp { + +// Can't use an anonymous namespace here due to brokenness of Tru64 compiler. +namespace cpp_unittest { + + +class MockErrorCollector : public MultiFileErrorCollector { + public: + MockErrorCollector() {} + ~MockErrorCollector() {} + + string text_; + + // implements ErrorCollector --------------------------------------- + void AddError(const string& filename, int line, int column, + const string& message) { + strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", + filename, line, column, message); + } +}; + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + +// Test that generated code has proper descriptors: +// Parse a descriptor directly (using google::protobuf::compiler::Importer) and +// compare it to the one that was produced by generated code. +TEST(GENERATED_DESCRIPTOR_TEST_NAME, IdenticalDescriptors) { + const FileDescriptor* generated_descriptor = + UNITTEST::TestAllTypes::descriptor()->file(); + + // Set up the Importer. + MockErrorCollector error_collector; + DiskSourceTree source_tree; + source_tree.MapPath("", TestSourceDir()); + Importer importer(&source_tree, &error_collector); + + // Import (parse) unittest.proto. + const FileDescriptor* parsed_descriptor = + importer.Import(UNITTEST_PROTO_PATH); + EXPECT_EQ("", error_collector.text_); + ASSERT_TRUE(parsed_descriptor != NULL); + + // Test that descriptors are generated correctly by converting them to + // FileDescriptorProtos and comparing. + FileDescriptorProto generated_descriptor_proto, parsed_descriptor_proto; + generated_descriptor->CopyTo(&generated_descriptor_proto); + parsed_descriptor->CopyTo(&parsed_descriptor_proto); + + EXPECT_EQ(parsed_descriptor_proto.DebugString(), + generated_descriptor_proto.DebugString()); +} + +#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER) +// Test that generated code has proper descriptors: +// Touch a descriptor generated from an enormous message to validate special +// handling for descriptors exceeding the C++ standard's recommended minimum +// limit for string literal size +TEST(GENERATED_DESCRIPTOR_TEST_NAME, EnormousDescriptor) { + const Descriptor* generated_descriptor = + TestEnormousDescriptor::descriptor(); + + EXPECT_TRUE(generated_descriptor != NULL); +} +#endif + +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS + +// =================================================================== + +TEST(GENERATED_MESSAGE_TEST_NAME, Defaults) { + // Check that all default values are set correctly in the initial message. + UNITTEST::TestAllTypes message; + + TestUtil::ExpectClear(message); + + // Messages should return pointers to default instances until first use. + // (This is not checked by ExpectClear() since it is not actually true after + // the fields have been set and then cleared.) + EXPECT_EQ(&UNITTEST::TestAllTypes::OptionalGroup::default_instance(), + &message.optionalgroup()); + EXPECT_EQ(&UNITTEST::TestAllTypes::NestedMessage::default_instance(), + &message.optional_nested_message()); + EXPECT_EQ(&UNITTEST::ForeignMessage::default_instance(), + &message.optional_foreign_message()); + EXPECT_EQ(&UNITTEST_IMPORT::ImportMessage::default_instance(), + &message.optional_import_message()); +} + +#ifndef PROTOBUF_USE_DLLS +TEST(GENERATED_MESSAGE_TEST_NAME, Int32StringConversion) { + EXPECT_EQ("971", Int32ToString(971)); + EXPECT_EQ("(~0x7fffffff)", Int32ToString(kint32min)); + EXPECT_EQ("2147483647", Int32ToString(kint32max)); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, Int64StringConversion) { + EXPECT_EQ("GOOGLE_LONGLONG(971)", Int64ToString(971)); + EXPECT_EQ("GOOGLE_LONGLONG(-2147483648)", Int64ToString(kint32min)); + EXPECT_EQ("GOOGLE_LONGLONG(~0x7fffffffffffffff)", Int64ToString(kint64min)); + EXPECT_EQ("GOOGLE_LONGLONG(9223372036854775807)", Int64ToString(kint64max)); +} +#endif // !PROTOBUF_USE_DLLS + +TEST(GENERATED_MESSAGE_TEST_NAME, FloatingPointDefaults) { + const UNITTEST::TestExtremeDefaultValues& extreme_default = + UNITTEST::TestExtremeDefaultValues::default_instance(); + + EXPECT_EQ(0.0f, extreme_default.zero_float()); + EXPECT_EQ(1.0f, extreme_default.one_float()); + EXPECT_EQ(1.5f, extreme_default.small_float()); + EXPECT_EQ(-1.0f, extreme_default.negative_one_float()); + EXPECT_EQ(-1.5f, extreme_default.negative_float()); + EXPECT_EQ(2.0e8f, extreme_default.large_float()); + EXPECT_EQ(-8e-28f, extreme_default.small_negative_float()); + EXPECT_EQ(std::numeric_limits<double>::infinity(), + extreme_default.inf_double()); + EXPECT_EQ(-std::numeric_limits<double>::infinity(), + extreme_default.neg_inf_double()); + EXPECT_TRUE(extreme_default.nan_double() != extreme_default.nan_double()); + EXPECT_EQ(std::numeric_limits<float>::infinity(), + extreme_default.inf_float()); + EXPECT_EQ(-std::numeric_limits<float>::infinity(), + extreme_default.neg_inf_float()); + EXPECT_TRUE(extreme_default.nan_float() != extreme_default.nan_float()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, Trigraph) { + const UNITTEST::TestExtremeDefaultValues& extreme_default = + UNITTEST::TestExtremeDefaultValues::default_instance(); + + EXPECT_EQ("? ? ?? ?? ??? ?\?/ ?\?-", extreme_default.cpp_trigraph()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, ExtremeSmallIntegerDefault) { + const UNITTEST::TestExtremeDefaultValues& extreme_default = + UNITTEST::TestExtremeDefaultValues::default_instance(); + EXPECT_EQ(~0x7fffffff, kint32min); + EXPECT_EQ(GOOGLE_LONGLONG(~0x7fffffffffffffff), kint64min); + EXPECT_EQ(kint32min, extreme_default.really_small_int32()); + EXPECT_EQ(kint64min, extreme_default.really_small_int64()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, Accessors) { + // Set every field to a unique value then go back and check all those + // values. + UNITTEST::TestAllTypes message; + + TestUtil::SetAllFields(&message); + TestUtil::ExpectAllFieldsSet(message); + + TestUtil::ModifyRepeatedFields(&message); + TestUtil::ExpectRepeatedFieldsModified(message); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, MutableStringDefault) { + // mutable_foo() for a string should return a string initialized to its + // default value. + UNITTEST::TestAllTypes message; + + EXPECT_EQ("hello", *message.mutable_default_string()); + + // Note that the first time we call mutable_foo(), we get a newly-allocated + // string, but if we clear it and call it again, we get the same object again. + // We should verify that it has its default value in both cases. + message.set_default_string("blah"); + message.Clear(); + + EXPECT_EQ("hello", *message.mutable_default_string()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, StringDefaults) { + UNITTEST::TestExtremeDefaultValues message; + // Check if '\000' can be used in default string value. + EXPECT_EQ(string("hel\000lo", 6), message.string_with_zero()); + EXPECT_EQ(string("wor\000ld", 6), message.bytes_with_zero()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, ReleaseString) { + // Check that release_foo() starts out NULL, and gives us a value + // that we can delete after it's been set. + UNITTEST::TestAllTypes message; + + EXPECT_EQ(NULL, message.release_default_string()); + EXPECT_FALSE(message.has_default_string()); + EXPECT_EQ("hello", message.default_string()); + + message.set_default_string("blah"); + EXPECT_TRUE(message.has_default_string()); + std::unique_ptr<string> str(message.release_default_string()); + EXPECT_FALSE(message.has_default_string()); + ASSERT_TRUE(str != NULL); + EXPECT_EQ("blah", *str); + + EXPECT_EQ(NULL, message.release_default_string()); + EXPECT_FALSE(message.has_default_string()); + EXPECT_EQ("hello", message.default_string()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, ReleaseMessage) { + // Check that release_foo() starts out NULL, and gives us a value + // that we can delete after it's been set. + UNITTEST::TestAllTypes message; + + EXPECT_EQ(NULL, message.release_optional_nested_message()); + EXPECT_FALSE(message.has_optional_nested_message()); + + message.mutable_optional_nested_message()->set_bb(1); + std::unique_ptr<UNITTEST::TestAllTypes::NestedMessage> nest( + message.release_optional_nested_message()); + EXPECT_FALSE(message.has_optional_nested_message()); + ASSERT_TRUE(nest != NULL); + EXPECT_EQ(1, nest->bb()); + + EXPECT_EQ(NULL, message.release_optional_nested_message()); + EXPECT_FALSE(message.has_optional_nested_message()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, SetAllocatedString) { + // Check that set_allocated_foo() works for strings. + UNITTEST::TestAllTypes message; + + EXPECT_FALSE(message.has_optional_string()); + const string kHello("hello"); + message.set_optional_string(kHello); + EXPECT_TRUE(message.has_optional_string()); + + message.set_allocated_optional_string(NULL); + EXPECT_FALSE(message.has_optional_string()); + EXPECT_EQ("", message.optional_string()); + + message.set_allocated_optional_string(new string(kHello)); + EXPECT_TRUE(message.has_optional_string()); + EXPECT_EQ(kHello, message.optional_string()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, SetAllocatedMessage) { + // Check that set_allocated_foo() can be called in all cases. + UNITTEST::TestAllTypes message; + + EXPECT_FALSE(message.has_optional_nested_message()); + + message.mutable_optional_nested_message()->set_bb(1); + EXPECT_TRUE(message.has_optional_nested_message()); + + message.set_allocated_optional_nested_message(NULL); + EXPECT_FALSE(message.has_optional_nested_message()); + EXPECT_EQ(&UNITTEST::TestAllTypes::NestedMessage::default_instance(), + &message.optional_nested_message()); + + message.mutable_optional_nested_message()->set_bb(1); + UNITTEST::TestAllTypes::NestedMessage* nest = + message.release_optional_nested_message(); + ASSERT_TRUE(nest != NULL); + EXPECT_FALSE(message.has_optional_nested_message()); + + message.set_allocated_optional_nested_message(nest); + EXPECT_TRUE(message.has_optional_nested_message()); + EXPECT_EQ(1, message.optional_nested_message().bb()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, Clear) { + // Set every field to a unique value, clear the message, then check that + // it is cleared. + UNITTEST::TestAllTypes message; + + TestUtil::SetAllFields(&message); + message.Clear(); + TestUtil::ExpectClear(message); + + // Unlike with the defaults test, we do NOT expect that requesting embedded + // messages will return a pointer to the default instance. Instead, they + // should return the objects that were created when mutable_blah() was + // called. + EXPECT_NE(&UNITTEST::TestAllTypes::OptionalGroup::default_instance(), + &message.optionalgroup()); + EXPECT_NE(&UNITTEST::TestAllTypes::NestedMessage::default_instance(), + &message.optional_nested_message()); + EXPECT_NE(&UNITTEST::ForeignMessage::default_instance(), + &message.optional_foreign_message()); + EXPECT_NE(&UNITTEST_IMPORT::ImportMessage::default_instance(), + &message.optional_import_message()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, EmbeddedNullsInBytesCharStar) { + UNITTEST::TestAllTypes message; + + const char* value = "\0lalala\0\0"; + message.set_optional_bytes(value, 9); + ASSERT_EQ(9, message.optional_bytes().size()); + EXPECT_EQ(0, memcmp(value, message.optional_bytes().data(), 9)); + + message.add_repeated_bytes(value, 9); + ASSERT_EQ(9, message.repeated_bytes(0).size()); + EXPECT_EQ(0, memcmp(value, message.repeated_bytes(0).data(), 9)); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, ClearOneField) { + // Set every field to a unique value, then clear one value and insure that + // only that one value is cleared. + UNITTEST::TestAllTypes message; + + TestUtil::SetAllFields(&message); + int64 original_value = message.optional_int64(); + + // Clear the field and make sure it shows up as cleared. + message.clear_optional_int64(); + EXPECT_FALSE(message.has_optional_int64()); + EXPECT_EQ(0, message.optional_int64()); + + // Other adjacent fields should not be cleared. + EXPECT_TRUE(message.has_optional_int32()); + EXPECT_TRUE(message.has_optional_uint32()); + + // Make sure if we set it again, then all fields are set. + message.set_optional_int64(original_value); + TestUtil::ExpectAllFieldsSet(message); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, StringCharStarLength) { + // Verify that we can use a char*,length to set one of the string fields. + UNITTEST::TestAllTypes message; + message.set_optional_string("abcdef", 3); + EXPECT_EQ("abc", message.optional_string()); + + // Verify that we can use a char*,length to add to a repeated string field. + message.add_repeated_string("abcdef", 3); + EXPECT_EQ(1, message.repeated_string_size()); + EXPECT_EQ("abc", message.repeated_string(0)); + + // Verify that we can use a char*,length to set a repeated string field. + message.set_repeated_string(0, "wxyz", 2); + EXPECT_EQ("wx", message.repeated_string(0)); +} + +#if LANG_CXX11 +TEST(GENERATED_MESSAGE_TEST_NAME, StringMove) { + // Verify that we trigger the move behavior on a scalar setter. + protobuf_unittest_no_arena::TestAllTypes message; + { + string tmp(32, 'a'); + + const char* old_data = tmp.data(); + message.set_optional_string(std::move(tmp)); + const char* new_data = message.optional_string().data(); + + EXPECT_EQ(old_data, new_data); + EXPECT_EQ(string(32, 'a'), message.optional_string()); + + string tmp2(32, 'b'); + old_data = tmp2.data(); + message.set_optional_string(std::move(tmp2)); + new_data = message.optional_string().data(); + + EXPECT_EQ(old_data, new_data); + EXPECT_EQ(string(32, 'b'), message.optional_string()); + } + + // Verify that we trigger the move behavior on a oneof setter. + { + string tmp(32, 'a'); + + const char* old_data = tmp.data(); + message.set_oneof_string(std::move(tmp)); + const char* new_data = message.oneof_string().data(); + + EXPECT_EQ(old_data, new_data); + EXPECT_EQ(string(32, 'a'), message.oneof_string()); + + string tmp2(32, 'b'); + old_data = tmp2.data(); + message.set_oneof_string(std::move(tmp2)); + new_data = message.oneof_string().data(); + + EXPECT_EQ(old_data, new_data); + EXPECT_EQ(string(32, 'b'), message.oneof_string()); + } + + // Verify that we trigger the move behavior on a repeated setter. + { + string tmp(32, 'a'); + + const char* old_data = tmp.data(); + message.add_repeated_string(std::move(tmp)); + const char* new_data = message.repeated_string(0).data(); + + EXPECT_EQ(old_data, new_data); + EXPECT_EQ(string(32, 'a'), message.repeated_string(0)); + + string tmp2(32, 'b'); + old_data = tmp2.data(); + message.set_repeated_string(0, std::move(tmp2)); + new_data = message.repeated_string(0).data(); + + EXPECT_EQ(old_data, new_data); + EXPECT_EQ(string(32, 'b'), message.repeated_string(0)); + } +} +#endif + + +TEST(GENERATED_MESSAGE_TEST_NAME, CopyFrom) { + UNITTEST::TestAllTypes message1, message2; + + TestUtil::SetAllFields(&message1); + message2.CopyFrom(message1); + TestUtil::ExpectAllFieldsSet(message2); + + // Copying from self should be a no-op. + message2.CopyFrom(message2); + TestUtil::ExpectAllFieldsSet(message2); +} + + +TEST(GENERATED_MESSAGE_TEST_NAME, SwapWithEmpty) { + UNITTEST::TestAllTypes message1, message2; + TestUtil::SetAllFields(&message1); + + TestUtil::ExpectAllFieldsSet(message1); + TestUtil::ExpectClear(message2); + message1.Swap(&message2); + TestUtil::ExpectAllFieldsSet(message2); + TestUtil::ExpectClear(message1); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, SwapWithSelf) { + UNITTEST::TestAllTypes message; + TestUtil::SetAllFields(&message); + TestUtil::ExpectAllFieldsSet(message); + message.Swap(&message); + TestUtil::ExpectAllFieldsSet(message); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, SwapWithOther) { + UNITTEST::TestAllTypes message1, message2; + + message1.set_optional_int32(123); + message1.set_optional_string("abc"); + message1.mutable_optional_nested_message()->set_bb(1); + message1.set_optional_nested_enum(UNITTEST::TestAllTypes::FOO); + message1.add_repeated_int32(1); + message1.add_repeated_int32(2); + message1.add_repeated_string("a"); + message1.add_repeated_string("b"); + message1.add_repeated_nested_message()->set_bb(7); + message1.add_repeated_nested_message()->set_bb(8); + message1.add_repeated_nested_enum(UNITTEST::TestAllTypes::FOO); + message1.add_repeated_nested_enum(UNITTEST::TestAllTypes::BAR); + + message2.set_optional_int32(456); + message2.set_optional_string("def"); + message2.mutable_optional_nested_message()->set_bb(2); + message2.set_optional_nested_enum(UNITTEST::TestAllTypes::BAR); + message2.add_repeated_int32(3); + message2.add_repeated_string("c"); + message2.add_repeated_nested_message()->set_bb(9); + message2.add_repeated_nested_enum(UNITTEST::TestAllTypes::BAZ); + + message1.Swap(&message2); + + EXPECT_EQ(456, message1.optional_int32()); + EXPECT_EQ("def", message1.optional_string()); + EXPECT_EQ(2, message1.optional_nested_message().bb()); + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message1.optional_nested_enum()); + ASSERT_EQ(1, message1.repeated_int32_size()); + EXPECT_EQ(3, message1.repeated_int32(0)); + ASSERT_EQ(1, message1.repeated_string_size()); + EXPECT_EQ("c", message1.repeated_string(0)); + ASSERT_EQ(1, message1.repeated_nested_message_size()); + EXPECT_EQ(9, message1.repeated_nested_message(0).bb()); + ASSERT_EQ(1, message1.repeated_nested_enum_size()); + EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, message1.repeated_nested_enum(0)); + + EXPECT_EQ(123, message2.optional_int32()); + EXPECT_EQ("abc", message2.optional_string()); + EXPECT_EQ(1, message2.optional_nested_message().bb()); + EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message2.optional_nested_enum()); + ASSERT_EQ(2, message2.repeated_int32_size()); + EXPECT_EQ(1, message2.repeated_int32(0)); + EXPECT_EQ(2, message2.repeated_int32(1)); + ASSERT_EQ(2, message2.repeated_string_size()); + EXPECT_EQ("a", message2.repeated_string(0)); + EXPECT_EQ("b", message2.repeated_string(1)); + ASSERT_EQ(2, message2.repeated_nested_message_size()); + EXPECT_EQ(7, message2.repeated_nested_message(0).bb()); + EXPECT_EQ(8, message2.repeated_nested_message(1).bb()); + ASSERT_EQ(2, message2.repeated_nested_enum_size()); + EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message2.repeated_nested_enum(0)); + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message2.repeated_nested_enum(1)); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, ADLSwap) { + UNITTEST::TestAllTypes message1, message2; + TestUtil::SetAllFields(&message1); + + // Note the address of one of the repeated fields, to verify it was swapped + // rather than copied. + const int32* addr = &message1.repeated_int32().Get(0); + + using std::swap; + swap(message1, message2); + + TestUtil::ExpectAllFieldsSet(message2); + TestUtil::ExpectClear(message1); + + EXPECT_EQ(addr, &message2.repeated_int32().Get(0)); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, CopyConstructor) { + // All set. + { + UNITTEST::TestAllTypes message1; + TestUtil::SetAllFields(&message1); + + UNITTEST::TestAllTypes message2(message1); + TestUtil::ExpectAllFieldsSet(message2); + } + + // None set. + { + UNITTEST::TestAllTypes message1; + UNITTEST::TestAllTypes message2(message1); + + EXPECT_FALSE(message1.has_optional_string()); + EXPECT_FALSE(message2.has_optional_string()); + EXPECT_EQ(message1.optional_string(), message2.optional_string()); + + EXPECT_FALSE(message1.has_optional_bytes()); + EXPECT_FALSE(message2.has_optional_bytes()); + EXPECT_EQ(message1.optional_bytes(), message2.optional_bytes()); + + EXPECT_FALSE(message1.has_optional_nested_message()); + EXPECT_FALSE(message2.has_optional_nested_message()); + EXPECT_EQ(&message1.optional_nested_message(), + &message2.optional_nested_message()); + + EXPECT_FALSE(message1.has_optional_foreign_message()); + EXPECT_FALSE(message2.has_optional_foreign_message()); + EXPECT_EQ(&message1.optional_foreign_message(), + &message2.optional_foreign_message()); + + EXPECT_FALSE(message1.has_optional_import_message()); + EXPECT_FALSE(message2.has_optional_import_message()); + EXPECT_EQ(&message1.optional_import_message(), + &message2.optional_import_message()); + + EXPECT_FALSE(message1.has_optional_public_import_message()); + EXPECT_FALSE(message2.has_optional_public_import_message()); + EXPECT_EQ(&message1.optional_public_import_message(), + &message2.optional_public_import_message()); + + EXPECT_FALSE(message1.has_optional_lazy_message()); + EXPECT_FALSE(message2.has_optional_lazy_message()); + EXPECT_EQ(&message1.optional_lazy_message(), + &message2.optional_lazy_message()); + } +} + +TEST(GENERATED_MESSAGE_TEST_NAME, CopyConstructorWithArenas) { + Arena arena; + UNITTEST::TestAllTypes* message1 = + Arena::CreateMessage<UNITTEST::TestAllTypes>(&arena); + TestUtil::SetAllFields(message1); + + UNITTEST::TestAllTypes message2_stack(*message1); + TestUtil::ExpectAllFieldsSet(message2_stack); + + std::unique_ptr<UNITTEST::TestAllTypes> message2_heap( + new UNITTEST::TestAllTypes(*message1)); + TestUtil::ExpectAllFieldsSet(*message2_heap); + + arena.Reset(); + + // Verify that the copies are still intact. + TestUtil::ExpectAllFieldsSet(message2_stack); + TestUtil::ExpectAllFieldsSet(*message2_heap); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, CopyAssignmentOperator) { + UNITTEST::TestAllTypes message1; + TestUtil::SetAllFields(&message1); + + UNITTEST::TestAllTypes message2; + message2 = message1; + TestUtil::ExpectAllFieldsSet(message2); + + // Make sure that self-assignment does something sane. + message2.operator=(message2); + TestUtil::ExpectAllFieldsSet(message2); +} + +#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \ + !defined(GOOGLE_PROTOBUF_NO_RTTI) +TEST(GENERATED_MESSAGE_TEST_NAME, UpcastCopyFrom) { + // Test the CopyFrom method that takes in the generic const Message& + // parameter. + UNITTEST::TestAllTypes message1, message2; + + TestUtil::SetAllFields(&message1); + + const Message* source = implicit_cast<const Message*>(&message1); + message2.CopyFrom(*source); + + TestUtil::ExpectAllFieldsSet(message2); +} +#endif + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + +TEST(GENERATED_MESSAGE_TEST_NAME, DynamicMessageCopyFrom) { + // Test copying from a DynamicMessage, which must fall back to using + // reflection. + UNITTEST::TestAllTypes message2; + + // Construct a new version of the dynamic message via the factory. + DynamicMessageFactory factory; + std::unique_ptr<Message> message1; + message1.reset(factory.GetPrototype( + UNITTEST::TestAllTypes::descriptor())->New()); + + TestUtil::ReflectionTester reflection_tester( + UNITTEST::TestAllTypes::descriptor()); + reflection_tester.SetAllFieldsViaReflection(message1.get()); + + message2.CopyFrom(*message1); + + TestUtil::ExpectAllFieldsSet(message2); +} + +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS + +TEST(GENERATED_MESSAGE_TEST_NAME, NonEmptyMergeFrom) { + // Test merging with a non-empty message. Code is a modified form + // of that found in google/protobuf/reflection_ops_unittest.cc. + UNITTEST::TestAllTypes message1, message2; + + TestUtil::SetAllFields(&message1); + + // This field will test merging into an empty spot. + message2.set_optional_int32(message1.optional_int32()); + message1.clear_optional_int32(); + + // This tests overwriting. + message2.set_optional_string(message1.optional_string()); + message1.set_optional_string("something else"); + + // This tests concatenating. + message2.add_repeated_int32(message1.repeated_int32(1)); + int32 i = message1.repeated_int32(0); + message1.clear_repeated_int32(); + message1.add_repeated_int32(i); + + message1.MergeFrom(message2); + + TestUtil::ExpectAllFieldsSet(message1); +} + + +// Test the generated SerializeWithCachedSizesToArray(), +TEST(GENERATED_MESSAGE_TEST_NAME, SerializationToArray) { + UNITTEST::TestAllTypes message1, message2; + string data; + TestUtil::SetAllFields(&message1); + int size = message1.ByteSizeLong(); + data.resize(size); + uint8* start = reinterpret_cast<uint8*>(string_as_array(&data)); + uint8* end = message1.SerializeWithCachedSizesToArray(start); + EXPECT_EQ(size, end - start); + EXPECT_TRUE(message2.ParseFromString(data)); + TestUtil::ExpectAllFieldsSet(message2); + +} + +TEST(GENERATED_MESSAGE_TEST_NAME, PackedFieldsSerializationToArray) { + UNITTEST::TestPackedTypes packed_message1, packed_message2; + string packed_data; + TestUtil::SetPackedFields(&packed_message1); + int packed_size = packed_message1.ByteSizeLong(); + packed_data.resize(packed_size); + uint8* start = reinterpret_cast<uint8*>(string_as_array(&packed_data)); + uint8* end = packed_message1.SerializeWithCachedSizesToArray(start); + EXPECT_EQ(packed_size, end - start); + EXPECT_TRUE(packed_message2.ParseFromString(packed_data)); + TestUtil::ExpectPackedFieldsSet(packed_message2); +} + +// Test the generated SerializeWithCachedSizes() by forcing the buffer to write +// one byte at a time. +TEST(GENERATED_MESSAGE_TEST_NAME, SerializationToStream) { + UNITTEST::TestAllTypes message1, message2; + TestUtil::SetAllFields(&message1); + int size = message1.ByteSizeLong(); + string data; + data.resize(size); + { + // Allow the output stream to buffer only one byte at a time. + io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + io::CodedOutputStream output_stream(&array_stream); + message1.SerializeWithCachedSizes(&output_stream); + EXPECT_FALSE(output_stream.HadError()); + EXPECT_EQ(size, output_stream.ByteCount()); + } + EXPECT_TRUE(message2.ParseFromString(data)); + TestUtil::ExpectAllFieldsSet(message2); + +} + +TEST(GENERATED_MESSAGE_TEST_NAME, PackedFieldsSerializationToStream) { + UNITTEST::TestPackedTypes message1, message2; + TestUtil::SetPackedFields(&message1); + int size = message1.ByteSizeLong(); + string data; + data.resize(size); + { + // Allow the output stream to buffer only one byte at a time. + io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + io::CodedOutputStream output_stream(&array_stream); + message1.SerializeWithCachedSizes(&output_stream); + EXPECT_FALSE(output_stream.HadError()); + EXPECT_EQ(size, output_stream.ByteCount()); + } + EXPECT_TRUE(message2.ParseFromString(data)); + TestUtil::ExpectPackedFieldsSet(message2); +} + + +TEST(GENERATED_MESSAGE_TEST_NAME, Required) { + // Test that IsInitialized() returns false if required fields are missing. + UNITTEST::TestRequired message; + + EXPECT_FALSE(message.IsInitialized()); + message.set_a(1); + EXPECT_FALSE(message.IsInitialized()); + message.set_b(2); + EXPECT_FALSE(message.IsInitialized()); + message.set_c(3); + EXPECT_TRUE(message.IsInitialized()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, RequiredForeign) { + // Test that IsInitialized() returns false if required fields in nested + // messages are missing. + UNITTEST::TestRequiredForeign message; + + EXPECT_TRUE(message.IsInitialized()); + + message.mutable_optional_message(); + EXPECT_FALSE(message.IsInitialized()); + + message.mutable_optional_message()->set_a(1); + message.mutable_optional_message()->set_b(2); + message.mutable_optional_message()->set_c(3); + EXPECT_TRUE(message.IsInitialized()); + + message.add_repeated_message(); + EXPECT_FALSE(message.IsInitialized()); + + message.mutable_repeated_message(0)->set_a(1); + message.mutable_repeated_message(0)->set_b(2); + message.mutable_repeated_message(0)->set_c(3); + EXPECT_TRUE(message.IsInitialized()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, ForeignNested) { + // Test that TestAllTypes::NestedMessage can be embedded directly into + // another message. + UNITTEST::TestForeignNested message; + + // If this compiles and runs without crashing, it must work. We have + // nothing more to test. + UNITTEST::TestAllTypes::NestedMessage* nested = + message.mutable_foreign_nested(); + nested->set_bb(1); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, ReallyLargeTagNumber) { + // Test that really large tag numbers don't break anything. + UNITTEST::TestReallyLargeTagNumber message1, message2; + string data; + + // For the most part, if this compiles and runs then we're probably good. + // (The most likely cause for failure would be if something were attempting + // to allocate a lookup table of some sort using tag numbers as the index.) + // We'll try serializing just for fun. + message1.set_a(1234); + message1.set_bb(5678); + message1.SerializeToString(&data); + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(1234, message2.a()); + EXPECT_EQ(5678, message2.bb()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, MutualRecursion) { + // Test that mutually-recursive message types work. + UNITTEST::TestMutualRecursionA message; + UNITTEST::TestMutualRecursionA* nested = message.mutable_bb()->mutable_a(); + UNITTEST::TestMutualRecursionA* nested2 = nested->mutable_bb()->mutable_a(); + + // Again, if the above compiles and runs, that's all we really have to + // test, but just for run we'll check that the system didn't somehow come + // up with a pointer loop... + EXPECT_NE(&message, nested); + EXPECT_NE(&message, nested2); + EXPECT_NE(nested, nested2); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, CamelCaseFieldNames) { + // This test is mainly checking that the following compiles, which verifies + // that the field names were coerced to lower-case. + // + // Protocol buffers standard style is to use lowercase-with-underscores for + // field names. Some old proto1 .protos unfortunately used camel-case field + // names. In proto1, these names were forced to lower-case. So, we do the + // same thing in proto2. + + UNITTEST::TestCamelCaseFieldNames message; + + message.set_primitivefield(2); + message.set_stringfield("foo"); + message.set_enumfield(UNITTEST::FOREIGN_FOO); + message.mutable_messagefield()->set_c(6); + + message.add_repeatedprimitivefield(8); + message.add_repeatedstringfield("qux"); + message.add_repeatedenumfield(UNITTEST::FOREIGN_BAR); + message.add_repeatedmessagefield()->set_c(15); + + EXPECT_EQ(2, message.primitivefield()); + EXPECT_EQ("foo", message.stringfield()); + EXPECT_EQ(UNITTEST::FOREIGN_FOO, message.enumfield()); + EXPECT_EQ(6, message.messagefield().c()); + + EXPECT_EQ(8, message.repeatedprimitivefield(0)); + EXPECT_EQ("qux", message.repeatedstringfield(0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.repeatedenumfield(0)); + EXPECT_EQ(15, message.repeatedmessagefield(0).c()); +} + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + +TEST(GENERATED_MESSAGE_TEST_NAME, TestOptimizedForSize) { + // We rely on the tests in reflection_ops_unittest and wire_format_unittest + // to really test that reflection-based methods work. Here we are mostly + // just making sure that TestOptimizedForSize actually builds and seems to + // function. + + UNITTEST::TestOptimizedForSize message, message2; + message.set_i(1); + message.mutable_msg()->set_c(2); + message2.CopyFrom(message); + EXPECT_EQ(1, message2.i()); + EXPECT_EQ(2, message2.msg().c()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, TestEmbedOptimizedForSize) { + // Verifies that something optimized for speed can contain something optimized + // for size. + + UNITTEST::TestEmbedOptimizedForSize message, message2; + message.mutable_optional_message()->set_i(1); + message.add_repeated_message()->mutable_msg()->set_c(2); + string data; + message.SerializeToString(&data); + ASSERT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(1, message2.optional_message().i()); + EXPECT_EQ(2, message2.repeated_message(0).msg().c()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, TestSpaceUsed) { + UNITTEST::TestAllTypes message1; + // sizeof provides a lower bound on SpaceUsedLong(). + EXPECT_LE(sizeof(UNITTEST::TestAllTypes), message1.SpaceUsedLong()); + const size_t empty_message_size = message1.SpaceUsedLong(); + + // Setting primitive types shouldn't affect the space used. + message1.set_optional_int32(123); + message1.set_optional_int64(12345); + message1.set_optional_uint32(123); + message1.set_optional_uint64(12345); + EXPECT_EQ(empty_message_size, message1.SpaceUsedLong()); + + // On some STL implementations, setting the string to a small value should + // only increase SpaceUsedLong() by the size of a string object, though this + // is not true everywhere. + message1.set_optional_string("abc"); + EXPECT_LE(empty_message_size + message1.optional_string().size(), + message1.SpaceUsedLong()); + + // Setting a string to a value larger than the string object itself should + // increase SpaceUsedLong(), because it cannot store the value internally. + message1.set_optional_string(string(sizeof(string) + 1, 'x')); + int min_expected_increase = message1.optional_string().capacity(); + EXPECT_LE(empty_message_size + min_expected_increase, + message1.SpaceUsedLong()); + + size_t previous_size = message1.SpaceUsedLong(); + // Adding an optional message should increase the size by the size of the + // nested message type. NestedMessage is simple enough (1 int field) that it + // is equal to sizeof(NestedMessage) + message1.mutable_optional_nested_message(); + ASSERT_EQ(sizeof(UNITTEST::TestAllTypes::NestedMessage), + message1.optional_nested_message().SpaceUsedLong()); + EXPECT_EQ(previous_size + + sizeof(UNITTEST::TestAllTypes::NestedMessage), + message1.SpaceUsedLong()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, TestOneofSpaceUsed) { + UNITTEST::TestOneof2 message1; + EXPECT_LE(sizeof(UNITTEST::TestOneof2), message1.SpaceUsedLong()); + + const size_t empty_message_size = message1.SpaceUsedLong(); + // Setting primitive types shouldn't affect the space used. + message1.set_foo_int(123); + message1.set_bar_int(12345); + EXPECT_EQ(empty_message_size, message1.SpaceUsedLong()); + + // Setting a string in oneof to a small value should only increase + // SpaceUsedLong() by the size of a string object. + message1.set_foo_string("abc"); + EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsedLong()); + + // Setting a string in oneof to a value larger than the string object itself + // should increase SpaceUsedLong(), because it cannot store the value + // internally. + message1.set_foo_string(string(sizeof(string) + 1, 'x')); + int min_expected_increase = message1.foo_string().capacity() + + sizeof(string); + EXPECT_LE(empty_message_size + min_expected_increase, + message1.SpaceUsedLong()); + + // Setting a message in oneof should delete the other fields and increase the + // size by the size of the nested message type. NestedMessage is simple enough + // that it is equal to sizeof(NestedMessage) + message1.mutable_foo_message(); + ASSERT_EQ(sizeof(UNITTEST::TestOneof2::NestedMessage), + message1.foo_message().SpaceUsedLong()); + EXPECT_EQ(empty_message_size + + sizeof(UNITTEST::TestOneof2::NestedMessage), + message1.SpaceUsedLong()); +} + +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS + + +TEST(GENERATED_MESSAGE_TEST_NAME, FieldConstantValues) { + UNITTEST::TestRequired message; + EXPECT_EQ(UNITTEST::TestAllTypes_NestedMessage::kBbFieldNumber, 1); + EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalInt32FieldNumber, 1); + EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalgroupFieldNumber, 16); + EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalNestedMessageFieldNumber, 18); + EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalNestedEnumFieldNumber, 21); + EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedInt32FieldNumber, 31); + EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedgroupFieldNumber, 46); + EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedNestedMessageFieldNumber, 48); + EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedNestedEnumFieldNumber, 51); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, ExtensionConstantValues) { + EXPECT_EQ(UNITTEST::TestRequired::kSingleFieldNumber, 1000); + EXPECT_EQ(UNITTEST::TestRequired::kMultiFieldNumber, 1001); + EXPECT_EQ(UNITTEST::kOptionalInt32ExtensionFieldNumber, 1); + EXPECT_EQ(UNITTEST::kOptionalgroupExtensionFieldNumber, 16); + EXPECT_EQ(UNITTEST::kOptionalNestedMessageExtensionFieldNumber, 18); + EXPECT_EQ(UNITTEST::kOptionalNestedEnumExtensionFieldNumber, 21); + EXPECT_EQ(UNITTEST::kRepeatedInt32ExtensionFieldNumber, 31); + EXPECT_EQ(UNITTEST::kRepeatedgroupExtensionFieldNumber, 46); + EXPECT_EQ(UNITTEST::kRepeatedNestedMessageExtensionFieldNumber, 48); + EXPECT_EQ(UNITTEST::kRepeatedNestedEnumExtensionFieldNumber, 51); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, ParseFromTruncated) { + const string long_string = string(128, 'q'); + FileDescriptorProto p; + p.add_extension()->set_name(long_string); + const string msg = p.SerializeAsString(); + int successful_count = 0; + for (int i = 0; i <= msg.size(); i++) { + if (p.ParseFromArray(msg.c_str(), i)) { + ++successful_count; + } + } + // We don't really care about how often we succeeded. + // As long as we didn't crash, we're happy. + EXPECT_GE(successful_count, 1); +} + +// =================================================================== + +TEST(GENERATED_ENUM_TEST_NAME, EnumValuesAsSwitchCases) { + // Test that our nested enum values can be used as switch cases. This test + // doesn't actually do anything, the proof that it works is that it + // compiles. + int i =0; + UNITTEST::TestAllTypes::NestedEnum a = UNITTEST::TestAllTypes::BAR; + switch (a) { + case UNITTEST::TestAllTypes::FOO: + i = 1; + break; + case UNITTEST::TestAllTypes::BAR: + i = 2; + break; + case UNITTEST::TestAllTypes::BAZ: + i = 3; + break; + case UNITTEST::TestAllTypes::NEG: + i = -1; + break; + // no default case: We want to make sure the compiler recognizes that + // all cases are covered. (GCC warns if you do not cover all cases of + // an enum in a switch.) + } + + // Token check just for fun. + EXPECT_EQ(2, i); +} + +TEST(GENERATED_ENUM_TEST_NAME, IsValidValue) { + // Test enum IsValidValue. + EXPECT_TRUE(UNITTEST::TestAllTypes::NestedEnum_IsValid(1)); + EXPECT_TRUE(UNITTEST::TestAllTypes::NestedEnum_IsValid(2)); + EXPECT_TRUE(UNITTEST::TestAllTypes::NestedEnum_IsValid(3)); + + EXPECT_FALSE(UNITTEST::TestAllTypes::NestedEnum_IsValid(0)); + EXPECT_FALSE(UNITTEST::TestAllTypes::NestedEnum_IsValid(4)); + + // Make sure it also works when there are dups. + EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_IsValid(1)); + EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_IsValid(2)); + EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_IsValid(3)); + + EXPECT_FALSE(UNITTEST::TestEnumWithDupValue_IsValid(0)); + EXPECT_FALSE(UNITTEST::TestEnumWithDupValue_IsValid(4)); +} + +TEST(GENERATED_ENUM_TEST_NAME, MinAndMax) { + EXPECT_EQ(UNITTEST::TestAllTypes::NEG, + UNITTEST::TestAllTypes::NestedEnum_MIN); + EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, + UNITTEST::TestAllTypes::NestedEnum_MAX); + EXPECT_EQ(4, UNITTEST::TestAllTypes::NestedEnum_ARRAYSIZE); + + EXPECT_EQ(UNITTEST::FOREIGN_FOO, UNITTEST::ForeignEnum_MIN); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, UNITTEST::ForeignEnum_MAX); + EXPECT_EQ(7, UNITTEST::ForeignEnum_ARRAYSIZE); + + EXPECT_EQ(1, UNITTEST::TestEnumWithDupValue_MIN); + EXPECT_EQ(3, UNITTEST::TestEnumWithDupValue_MAX); + EXPECT_EQ(4, UNITTEST::TestEnumWithDupValue_ARRAYSIZE); + + EXPECT_EQ(UNITTEST::SPARSE_E, UNITTEST::TestSparseEnum_MIN); + EXPECT_EQ(UNITTEST::SPARSE_C, UNITTEST::TestSparseEnum_MAX); + EXPECT_EQ(12589235, UNITTEST::TestSparseEnum_ARRAYSIZE); + + // Make sure we can take the address of _MIN, _MAX and _ARRAYSIZE. + void* null_pointer = 0; // NULL may be integer-type, not pointer-type. + EXPECT_NE(null_pointer, &UNITTEST::TestAllTypes::NestedEnum_MIN); + EXPECT_NE(null_pointer, &UNITTEST::TestAllTypes::NestedEnum_MAX); + EXPECT_NE(null_pointer, &UNITTEST::TestAllTypes::NestedEnum_ARRAYSIZE); + + EXPECT_NE(null_pointer, &UNITTEST::ForeignEnum_MIN); + EXPECT_NE(null_pointer, &UNITTEST::ForeignEnum_MAX); + EXPECT_NE(null_pointer, &UNITTEST::ForeignEnum_ARRAYSIZE); + + // Make sure we can use _MIN and _MAX as switch cases. + switch (UNITTEST::SPARSE_A) { + case UNITTEST::TestSparseEnum_MIN: + case UNITTEST::TestSparseEnum_MAX: + break; + default: + break; + } +} + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + +TEST(GENERATED_ENUM_TEST_NAME, Name) { + // "Names" in the presence of dup values are a bit arbitrary. + EXPECT_EQ("FOO1", UNITTEST::TestEnumWithDupValue_Name(UNITTEST::FOO1)); + EXPECT_EQ("FOO1", UNITTEST::TestEnumWithDupValue_Name(UNITTEST::FOO2)); + + EXPECT_EQ("SPARSE_A", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_A)); + EXPECT_EQ("SPARSE_B", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_B)); + EXPECT_EQ("SPARSE_C", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_C)); + EXPECT_EQ("SPARSE_D", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_D)); + EXPECT_EQ("SPARSE_E", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_E)); + EXPECT_EQ("SPARSE_F", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_F)); + EXPECT_EQ("SPARSE_G", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_G)); +} + +TEST(GENERATED_ENUM_TEST_NAME, Parse) { + UNITTEST::TestEnumWithDupValue dup_value = UNITTEST::FOO1; + EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_Parse("FOO1", &dup_value)); + EXPECT_EQ(UNITTEST::FOO1, dup_value); + EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_Parse("FOO2", &dup_value)); + EXPECT_EQ(UNITTEST::FOO2, dup_value); + EXPECT_FALSE(UNITTEST::TestEnumWithDupValue_Parse("FOO", &dup_value)); +} + +TEST(GENERATED_ENUM_TEST_NAME, GetEnumDescriptor) { + EXPECT_EQ(UNITTEST::TestAllTypes::NestedEnum_descriptor(), + GetEnumDescriptor<UNITTEST::TestAllTypes::NestedEnum>()); + EXPECT_EQ(UNITTEST::ForeignEnum_descriptor(), + GetEnumDescriptor<UNITTEST::ForeignEnum>()); + EXPECT_EQ(UNITTEST::TestEnumWithDupValue_descriptor(), + GetEnumDescriptor<UNITTEST::TestEnumWithDupValue>()); + EXPECT_EQ(UNITTEST::TestSparseEnum_descriptor(), + GetEnumDescriptor<UNITTEST::TestSparseEnum>()); +} + +enum NonProtoEnum { + kFoo = 1, +}; + +TEST(GENERATED_ENUM_TEST_NAME, IsProtoEnumTypeTrait) { + EXPECT_TRUE(is_proto_enum<UNITTEST::TestAllTypes::NestedEnum>::value); + EXPECT_TRUE(is_proto_enum<UNITTEST::ForeignEnum>::value); + EXPECT_TRUE(is_proto_enum<UNITTEST::TestEnumWithDupValue>::value); + EXPECT_TRUE(is_proto_enum<UNITTEST::TestSparseEnum>::value); + + EXPECT_FALSE(is_proto_enum<int>::value); + EXPECT_FALSE(is_proto_enum<NonProtoEnum>::value); +} + +#endif // PROTOBUF_TEST_NO_DESCRIPTORS + +// =================================================================== + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + +// Support code for testing services. +class GENERATED_SERVICE_TEST_NAME : public testing::Test { + protected: + class MockTestService : public UNITTEST::TestService { + public: + MockTestService() + : called_(false), + method_(""), + controller_(NULL), + request_(NULL), + response_(NULL), + done_(NULL) {} + + ~MockTestService() {} + + void Reset() { called_ = false; } + + // implements TestService ---------------------------------------- + + void Foo(RpcController* controller, + const UNITTEST::FooRequest* request, + UNITTEST::FooResponse* response, + Closure* done) { + ASSERT_FALSE(called_); + called_ = true; + method_ = "Foo"; + controller_ = controller; + request_ = request; + response_ = response; + done_ = done; + } + + void Bar(RpcController* controller, + const UNITTEST::BarRequest* request, + UNITTEST::BarResponse* response, + Closure* done) { + ASSERT_FALSE(called_); + called_ = true; + method_ = "Bar"; + controller_ = controller; + request_ = request; + response_ = response; + done_ = done; + } + + // --------------------------------------------------------------- + + bool called_; + string method_; + RpcController* controller_; + const Message* request_; + Message* response_; + Closure* done_; + }; + + class MockRpcChannel : public RpcChannel { + public: + MockRpcChannel() + : called_(false), + method_(NULL), + controller_(NULL), + request_(NULL), + response_(NULL), + done_(NULL), + destroyed_(NULL) {} + + ~MockRpcChannel() { + if (destroyed_ != NULL) *destroyed_ = true; + } + + void Reset() { called_ = false; } + + // implements TestService ---------------------------------------- + + void CallMethod(const MethodDescriptor* method, + RpcController* controller, + const Message* request, + Message* response, + Closure* done) { + ASSERT_FALSE(called_); + called_ = true; + method_ = method; + controller_ = controller; + request_ = request; + response_ = response; + done_ = done; + } + + // --------------------------------------------------------------- + + bool called_; + const MethodDescriptor* method_; + RpcController* controller_; + const Message* request_; + Message* response_; + Closure* done_; + bool* destroyed_; + }; + + class MockController : public RpcController { + public: + void Reset() { + ADD_FAILURE() << "Reset() not expected during this test."; + } + bool Failed() const { + ADD_FAILURE() << "Failed() not expected during this test."; + return false; + } + string ErrorText() const { + ADD_FAILURE() << "ErrorText() not expected during this test."; + return ""; + } + void StartCancel() { + ADD_FAILURE() << "StartCancel() not expected during this test."; + } + void SetFailed(const string& reason) { + ADD_FAILURE() << "SetFailed() not expected during this test."; + } + bool IsCanceled() const { + ADD_FAILURE() << "IsCanceled() not expected during this test."; + return false; + } + void NotifyOnCancel(Closure* callback) { + ADD_FAILURE() << "NotifyOnCancel() not expected during this test."; + } + }; + + GENERATED_SERVICE_TEST_NAME() + : descriptor_(UNITTEST::TestService::descriptor()), + foo_(descriptor_->FindMethodByName("Foo")), + bar_(descriptor_->FindMethodByName("Bar")), + stub_(&mock_channel_), + done_(::google::protobuf::NewPermanentCallback(&DoNothing)) {} + + virtual void SetUp() { + ASSERT_TRUE(foo_ != NULL); + ASSERT_TRUE(bar_ != NULL); + } + + const ServiceDescriptor* descriptor_; + const MethodDescriptor* foo_; + const MethodDescriptor* bar_; + + MockTestService mock_service_; + MockController mock_controller_; + + MockRpcChannel mock_channel_; + UNITTEST::TestService::Stub stub_; + + // Just so we don't have to re-define these with every test. + UNITTEST::FooRequest foo_request_; + UNITTEST::FooResponse foo_response_; + UNITTEST::BarRequest bar_request_; + UNITTEST::BarResponse bar_response_; + std::unique_ptr<Closure> done_; +}; + +TEST_F(GENERATED_SERVICE_TEST_NAME, GetDescriptor) { + // Test that GetDescriptor() works. + + EXPECT_EQ(descriptor_, mock_service_.GetDescriptor()); +} + +TEST_F(GENERATED_SERVICE_TEST_NAME, GetChannel) { + EXPECT_EQ(&mock_channel_, stub_.channel()); +} + +TEST_F(GENERATED_SERVICE_TEST_NAME, OwnsChannel) { + MockRpcChannel* channel = new MockRpcChannel; + bool destroyed = false; + channel->destroyed_ = &destroyed; + + { + UNITTEST::TestService::Stub owning_stub(channel, + Service::STUB_OWNS_CHANNEL); + EXPECT_FALSE(destroyed); + } + + EXPECT_TRUE(destroyed); +} + +TEST_F(GENERATED_SERVICE_TEST_NAME, CallMethod) { + // Test that CallMethod() works. + + // Call Foo() via CallMethod(). + mock_service_.CallMethod(foo_, &mock_controller_, + &foo_request_, &foo_response_, done_.get()); + + ASSERT_TRUE(mock_service_.called_); + + EXPECT_EQ("Foo" , mock_service_.method_ ); + EXPECT_EQ(&mock_controller_, mock_service_.controller_); + EXPECT_EQ(&foo_request_ , mock_service_.request_ ); + EXPECT_EQ(&foo_response_ , mock_service_.response_ ); + EXPECT_EQ(done_.get() , mock_service_.done_ ); + + // Try again, but call Bar() instead. + mock_service_.Reset(); + mock_service_.CallMethod(bar_, &mock_controller_, + &bar_request_, &bar_response_, done_.get()); + + ASSERT_TRUE(mock_service_.called_); + EXPECT_EQ("Bar", mock_service_.method_); +} + +TEST_F(GENERATED_SERVICE_TEST_NAME, CallMethodTypeFailure) { + // Verify death if we call Foo() with Bar's message types. + +#ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet + EXPECT_DEBUG_DEATH( + mock_service_.CallMethod(foo_, &mock_controller_, + &foo_request_, &bar_response_, done_.get()), + "dynamic_cast"); + + mock_service_.Reset(); + EXPECT_DEBUG_DEATH( + mock_service_.CallMethod(foo_, &mock_controller_, + &bar_request_, &foo_response_, done_.get()), + "dynamic_cast"); +#endif // PROTOBUF_HAS_DEATH_TEST +} + +TEST_F(GENERATED_SERVICE_TEST_NAME, GetPrototypes) { + // Test Get{Request,Response}Prototype() methods. + + EXPECT_EQ(&UNITTEST::FooRequest::default_instance(), + &mock_service_.GetRequestPrototype(foo_)); + EXPECT_EQ(&UNITTEST::BarRequest::default_instance(), + &mock_service_.GetRequestPrototype(bar_)); + + EXPECT_EQ(&UNITTEST::FooResponse::default_instance(), + &mock_service_.GetResponsePrototype(foo_)); + EXPECT_EQ(&UNITTEST::BarResponse::default_instance(), + &mock_service_.GetResponsePrototype(bar_)); +} + +TEST_F(GENERATED_SERVICE_TEST_NAME, Stub) { + // Test that the stub class works. + + // Call Foo() via the stub. + stub_.Foo(&mock_controller_, &foo_request_, &foo_response_, done_.get()); + + ASSERT_TRUE(mock_channel_.called_); + + EXPECT_EQ(foo_ , mock_channel_.method_ ); + EXPECT_EQ(&mock_controller_, mock_channel_.controller_); + EXPECT_EQ(&foo_request_ , mock_channel_.request_ ); + EXPECT_EQ(&foo_response_ , mock_channel_.response_ ); + EXPECT_EQ(done_.get() , mock_channel_.done_ ); + + // Call Bar() via the stub. + mock_channel_.Reset(); + stub_.Bar(&mock_controller_, &bar_request_, &bar_response_, done_.get()); + + ASSERT_TRUE(mock_channel_.called_); + EXPECT_EQ(bar_, mock_channel_.method_); +} + +TEST_F(GENERATED_SERVICE_TEST_NAME, NotImplemented) { + // Test that failing to implement a method of a service causes it to fail + // with a "not implemented" error message. + + // A service which doesn't implement any methods. + class UnimplementedService : public UNITTEST::TestService { + public: + UnimplementedService() {} + }; + + UnimplementedService unimplemented_service; + + // And a controller which expects to get a "not implemented" error. + class ExpectUnimplementedController : public MockController { + public: + ExpectUnimplementedController() : called_(false) {} + + void SetFailed(const string& reason) { + EXPECT_FALSE(called_); + called_ = true; + EXPECT_EQ("Method Foo() not implemented.", reason); + } + + bool called_; + }; + + ExpectUnimplementedController controller; + + // Call Foo. + unimplemented_service.Foo(&controller, &foo_request_, &foo_response_, + done_.get()); + + EXPECT_TRUE(controller.called_); +} + +// =================================================================== + +class OneofTest : public testing::Test { + protected: + virtual void SetUp() { + } + + void ExpectEnumCasesWork(const UNITTEST::TestOneof2 &message) { + switch (message.foo_case()) { + case UNITTEST::TestOneof2::kFooInt: + EXPECT_TRUE(message.has_foo_int()); + break; + case UNITTEST::TestOneof2::kFooString: + EXPECT_TRUE(message.has_foo_string()); + break; + case UNITTEST::TestOneof2::kFooCord: + EXPECT_TRUE(message.has_foo_cord()); + break; + case UNITTEST::TestOneof2::kFooStringPiece: + EXPECT_TRUE(message.has_foo_string_piece()); + break; + case UNITTEST::TestOneof2::kFooBytes: + EXPECT_TRUE(message.has_foo_bytes()); + break; + case UNITTEST::TestOneof2::kFooEnum: + EXPECT_TRUE(message.has_foo_enum()); + break; + case UNITTEST::TestOneof2::kFooMessage: + EXPECT_TRUE(message.has_foo_message()); + break; + case UNITTEST::TestOneof2::kFoogroup: + EXPECT_TRUE(message.has_foogroup()); + break; + case UNITTEST::TestOneof2::kFooLazyMessage: + EXPECT_TRUE(message.has_foo_lazy_message()); + break; + case UNITTEST::TestOneof2::FOO_NOT_SET: + break; + } + } +}; + +TEST_F(OneofTest, SettingOneFieldClearsOthers) { + UNITTEST::TestOneof2 message; + + message.set_foo_int(123); + EXPECT_TRUE(message.has_foo_int()); + TestUtil::ExpectAtMostOneFieldSetInOneof(message); + + message.set_foo_string("foo"); + EXPECT_TRUE(message.has_foo_string()); + TestUtil::ExpectAtMostOneFieldSetInOneof(message); + + + message.set_foo_bytes("qux"); + EXPECT_TRUE(message.has_foo_bytes()); + TestUtil::ExpectAtMostOneFieldSetInOneof(message); + + message.set_foo_enum(UNITTEST::TestOneof2::FOO); + EXPECT_TRUE(message.has_foo_enum()); + TestUtil::ExpectAtMostOneFieldSetInOneof(message); + + message.mutable_foo_message()->set_qux_int(234); + EXPECT_TRUE(message.has_foo_message()); + TestUtil::ExpectAtMostOneFieldSetInOneof(message); + + message.mutable_foogroup()->set_a(345); + EXPECT_TRUE(message.has_foogroup()); + TestUtil::ExpectAtMostOneFieldSetInOneof(message); + + + // we repeat this because we didn't test if this properly clears other fields + // at the beginning. + message.set_foo_int(123); + EXPECT_TRUE(message.has_foo_int()); + TestUtil::ExpectAtMostOneFieldSetInOneof(message); +} + +TEST_F(OneofTest, EnumCases) { + UNITTEST::TestOneof2 message; + + message.set_foo_int(123); + ExpectEnumCasesWork(message); + message.set_foo_string("foo"); + ExpectEnumCasesWork(message); + message.set_foo_bytes("qux"); + ExpectEnumCasesWork(message); + message.set_foo_enum(UNITTEST::TestOneof2::FOO); + ExpectEnumCasesWork(message); + message.mutable_foo_message()->set_qux_int(234); + ExpectEnumCasesWork(message); + message.mutable_foogroup()->set_a(345); + ExpectEnumCasesWork(message); +} + +TEST_F(OneofTest, PrimitiveType) { + UNITTEST::TestOneof2 message; + // Unset field returns default value + EXPECT_EQ(message.foo_int(), 0); + + message.set_foo_int(123); + EXPECT_TRUE(message.has_foo_int()); + EXPECT_EQ(message.foo_int(), 123); + message.clear_foo_int(); + EXPECT_FALSE(message.has_foo_int()); +} + +TEST_F(OneofTest, EnumType) { + UNITTEST::TestOneof2 message; + // Unset field returns default value + EXPECT_EQ(message.foo_enum(), 1); + + message.set_foo_enum(UNITTEST::TestOneof2::FOO); + EXPECT_TRUE(message.has_foo_enum()); + EXPECT_EQ(message.foo_enum(), UNITTEST::TestOneof2::FOO); + message.clear_foo_enum(); + EXPECT_FALSE(message.has_foo_enum()); +} + +TEST_F(OneofTest, SetString) { + // Check that setting a string field in various ways works + UNITTEST::TestOneof2 message; + + // Unset field returns default value + EXPECT_EQ(message.foo_string(), ""); + + message.set_foo_string("foo"); + EXPECT_TRUE(message.has_foo_string()); + EXPECT_EQ(message.foo_string(), "foo"); + message.clear_foo_string(); + EXPECT_FALSE(message.has_foo_string()); + + message.set_foo_string(string("bar")); + EXPECT_TRUE(message.has_foo_string()); + EXPECT_EQ(message.foo_string(), "bar"); + message.clear_foo_string(); + EXPECT_FALSE(message.has_foo_string()); + + + message.set_foo_string("qux", 3); + EXPECT_TRUE(message.has_foo_string()); + EXPECT_EQ(message.foo_string(), "qux"); + message.clear_foo_string(); + EXPECT_FALSE(message.has_foo_string()); + + message.mutable_foo_string()->assign("quux"); + EXPECT_TRUE(message.has_foo_string()); + EXPECT_EQ(message.foo_string(), "quux"); + message.clear_foo_string(); + EXPECT_FALSE(message.has_foo_string()); + + message.set_foo_string("corge"); + EXPECT_TRUE(message.has_foo_string()); + EXPECT_EQ(message.foo_string(), "corge"); + message.clear_foo_string(); + EXPECT_FALSE(message.has_foo_string()); +} + +TEST_F(OneofTest, ReleaseString) { + // Check that release_foo() starts out NULL, and gives us a value + // that we can delete after it's been set. + UNITTEST::TestOneof2 message; + + EXPECT_EQ(NULL, message.release_foo_string()); + EXPECT_FALSE(message.has_foo_string()); + + message.set_foo_string("blah"); + EXPECT_TRUE(message.has_foo_string()); + std::unique_ptr<string> str(message.release_foo_string()); + EXPECT_FALSE(message.has_foo_string()); + ASSERT_TRUE(str != NULL); + EXPECT_EQ("blah", *str); + + EXPECT_EQ(NULL, message.release_foo_string()); + EXPECT_FALSE(message.has_foo_string()); +} + +TEST_F(OneofTest, SetAllocatedString) { + // Check that set_allocated_foo() works for strings. + UNITTEST::TestOneof2 message; + + EXPECT_FALSE(message.has_foo_string()); + const string kHello("hello"); + message.set_foo_string(kHello); + EXPECT_TRUE(message.has_foo_string()); + + message.set_allocated_foo_string(NULL); + EXPECT_FALSE(message.has_foo_string()); + EXPECT_EQ("", message.foo_string()); + + message.set_allocated_foo_string(new string(kHello)); + EXPECT_TRUE(message.has_foo_string()); + EXPECT_EQ(kHello, message.foo_string()); +} + + +TEST_F(OneofTest, SetMessage) { + // Check that setting a message field works + UNITTEST::TestOneof2 message; + + // Unset field returns default instance + EXPECT_EQ(&message.foo_message(), + &UNITTEST::TestOneof2_NestedMessage::default_instance()); + EXPECT_EQ(message.foo_message().qux_int(), 0); + + message.mutable_foo_message()->set_qux_int(234); + EXPECT_TRUE(message.has_foo_message()); + EXPECT_EQ(message.foo_message().qux_int(), 234); + message.clear_foo_message(); + EXPECT_FALSE(message.has_foo_message()); +} + +TEST_F(OneofTest, ReleaseMessage) { + // Check that release_foo() starts out NULL, and gives us a value + // that we can delete after it's been set. + UNITTEST::TestOneof2 message; + + EXPECT_EQ(NULL, message.release_foo_message()); + EXPECT_FALSE(message.has_foo_message()); + + message.mutable_foo_message()->set_qux_int(1); + EXPECT_TRUE(message.has_foo_message()); + std::unique_ptr<UNITTEST::TestOneof2_NestedMessage> mes( + message.release_foo_message()); + EXPECT_FALSE(message.has_foo_message()); + ASSERT_TRUE(mes != NULL); + EXPECT_EQ(1, mes->qux_int()); + + EXPECT_EQ(NULL, message.release_foo_message()); + EXPECT_FALSE(message.has_foo_message()); +} + +TEST_F(OneofTest, SetAllocatedMessage) { + // Check that set_allocated_foo() works for messages. + UNITTEST::TestOneof2 message; + + EXPECT_FALSE(message.has_foo_message()); + + message.mutable_foo_message()->set_qux_int(1); + EXPECT_TRUE(message.has_foo_message()); + + message.set_allocated_foo_message(NULL); + EXPECT_FALSE(message.has_foo_message()); + EXPECT_EQ(&message.foo_message(), + &UNITTEST::TestOneof2_NestedMessage::default_instance()); + + message.mutable_foo_message()->set_qux_int(1); + UNITTEST::TestOneof2_NestedMessage* mes = message.release_foo_message(); + ASSERT_TRUE(mes != NULL); + EXPECT_FALSE(message.has_foo_message()); + + message.set_allocated_foo_message(mes); + EXPECT_TRUE(message.has_foo_message()); + EXPECT_EQ(1, message.foo_message().qux_int()); +} + + +TEST_F(OneofTest, Clear) { + UNITTEST::TestOneof2 message; + + message.set_foo_int(1); + EXPECT_TRUE(message.has_foo_int()); + message.clear_foo_int(); + EXPECT_FALSE(message.has_foo_int()); +} + +TEST_F(OneofTest, Defaults) { + UNITTEST::TestOneof2 message; + + EXPECT_FALSE(message.has_foo_int()); + EXPECT_EQ(message.foo_int(), 0); + + EXPECT_FALSE(message.has_foo_string()); + EXPECT_EQ(message.foo_string(), ""); + + + EXPECT_FALSE(message.has_foo_bytes()); + EXPECT_EQ(message.foo_bytes(), ""); + + EXPECT_FALSE(message.has_foo_enum()); + EXPECT_EQ(message.foo_enum(), 1); + + EXPECT_FALSE(message.has_foo_message()); + EXPECT_EQ(message.foo_message().qux_int(), 0); + + EXPECT_FALSE(message.has_foogroup()); + EXPECT_EQ(message.foogroup().a(), 0); + + + EXPECT_FALSE(message.has_bar_int()); + EXPECT_EQ(message.bar_int(), 5); + + EXPECT_FALSE(message.has_bar_string()); + EXPECT_EQ(message.bar_string(), "STRING"); + + + EXPECT_FALSE(message.has_bar_bytes()); + EXPECT_EQ(message.bar_bytes(), "BYTES"); + + EXPECT_FALSE(message.has_bar_enum()); + EXPECT_EQ(message.bar_enum(), 2); +} + +TEST_F(OneofTest, SwapWithEmpty) { + UNITTEST::TestOneof2 message1, message2; + message1.set_foo_string("FOO"); + EXPECT_TRUE(message1.has_foo_string()); + message1.Swap(&message2); + EXPECT_FALSE(message1.has_foo_string()); + EXPECT_TRUE(message2.has_foo_string()); + EXPECT_EQ(message2.foo_string(), "FOO"); +} + +TEST_F(OneofTest, SwapWithSelf) { + UNITTEST::TestOneof2 message; + message.set_foo_string("FOO"); + EXPECT_TRUE(message.has_foo_string()); + message.Swap(&message); + EXPECT_TRUE(message.has_foo_string()); + EXPECT_EQ(message.foo_string(), "FOO"); +} + +TEST_F(OneofTest, SwapBothHasFields) { + UNITTEST::TestOneof2 message1, message2; + + message1.set_foo_string("FOO"); + EXPECT_TRUE(message1.has_foo_string()); + message2.mutable_foo_message()->set_qux_int(1); + EXPECT_TRUE(message2.has_foo_message()); + + message1.Swap(&message2); + EXPECT_FALSE(message1.has_foo_string()); + EXPECT_FALSE(message2.has_foo_message()); + EXPECT_TRUE(message1.has_foo_message()); + EXPECT_EQ(message1.foo_message().qux_int(), 1); + EXPECT_TRUE(message2.has_foo_string()); + EXPECT_EQ(message2.foo_string(), "FOO"); +} + +TEST_F(OneofTest, CopyConstructor) { + UNITTEST::TestOneof2 message1; + message1.set_foo_bytes("FOO"); + + UNITTEST::TestOneof2 message2(message1); + EXPECT_TRUE(message2.has_foo_bytes()); + EXPECT_EQ(message2.foo_bytes(), "FOO"); +} + +TEST_F(OneofTest, CopyFrom) { + UNITTEST::TestOneof2 message1, message2; + message1.set_foo_enum(UNITTEST::TestOneof2::BAR); + EXPECT_TRUE(message1.has_foo_enum()); + + message2.CopyFrom(message1); + EXPECT_TRUE(message2.has_foo_enum()); + EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::BAR); + + // Copying from self should be a no-op. + message2.CopyFrom(message2); + EXPECT_TRUE(message2.has_foo_enum()); + EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::BAR); +} + +TEST_F(OneofTest, CopyAssignmentOperator) { + UNITTEST::TestOneof2 message1; + message1.mutable_foo_message()->set_qux_int(123); + EXPECT_TRUE(message1.has_foo_message()); + + UNITTEST::TestOneof2 message2; + message2 = message1; + EXPECT_EQ(message2.foo_message().qux_int(), 123); + + // Make sure that self-assignment does something sane. + message2 = message2; + EXPECT_EQ(message2.foo_message().qux_int(), 123); +} + +TEST_F(OneofTest, UpcastCopyFrom) { + // Test the CopyFrom method that takes in the generic const Message& + // parameter. + UNITTEST::TestOneof2 message1, message2; + message1.mutable_foogroup()->set_a(123); + EXPECT_TRUE(message1.has_foogroup()); + + const Message* source = implicit_cast<const Message*>(&message1); + message2.CopyFrom(*source); + + EXPECT_TRUE(message2.has_foogroup()); + EXPECT_EQ(message2.foogroup().a(), 123); +} + +// Test the generated SerializeWithCachedSizesToArray(), +// This indirectly tests MergePartialFromCodedStream() +// We have to test each field type separately because we cannot set them at the +// same time +TEST_F(OneofTest, SerializationToArray) { + // Primitive type + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.set_foo_int(123); + int size = message1.ByteSizeLong(); + data.resize(size); + uint8* start = reinterpret_cast<uint8*>(string_as_array(&data)); + uint8* end = message1.SerializeWithCachedSizesToArray(start); + EXPECT_EQ(size, end - start); + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(message2.foo_int(), 123); + } + + // String + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.set_foo_string("foo"); + int size = message1.ByteSizeLong(); + data.resize(size); + uint8* start = reinterpret_cast<uint8*>(string_as_array(&data)); + uint8* end = message1.SerializeWithCachedSizesToArray(start); + EXPECT_EQ(size, end - start); + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(message2.foo_string(), "foo"); + } + + + // Bytes + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.set_foo_bytes("qux"); + int size = message1.ByteSizeLong(); + data.resize(size); + uint8* start = reinterpret_cast<uint8*>(string_as_array(&data)); + uint8* end = message1.SerializeWithCachedSizesToArray(start); + EXPECT_EQ(size, end - start); + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(message2.foo_bytes(), "qux"); + } + + // Enum + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.set_foo_enum(UNITTEST::TestOneof2::FOO); + int size = message1.ByteSizeLong(); + data.resize(size); + uint8* start = reinterpret_cast<uint8*>(string_as_array(&data)); + uint8* end = message1.SerializeWithCachedSizesToArray(start); + EXPECT_EQ(size, end - start); + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::FOO); + } + + // Message + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.mutable_foo_message()->set_qux_int(234); + int size = message1.ByteSizeLong(); + data.resize(size); + uint8* start = reinterpret_cast<uint8*>(string_as_array(&data)); + uint8* end = message1.SerializeWithCachedSizesToArray(start); + EXPECT_EQ(size, end - start); + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(message2.foo_message().qux_int(), 234); + } + + // Group + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.mutable_foogroup()->set_a(345); + int size = message1.ByteSizeLong(); + data.resize(size); + uint8* start = reinterpret_cast<uint8*>(string_as_array(&data)); + uint8* end = message1.SerializeWithCachedSizesToArray(start); + EXPECT_EQ(size, end - start); + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(message2.foogroup().a(), 345); + } + +} + +// Test the generated SerializeWithCachedSizes() by forcing the buffer to write +// one byte at a time. +// This indirectly tests MergePartialFromCodedStream() +// We have to test each field type separately because we cannot set them at the +// same time +TEST_F(OneofTest, SerializationToStream) { + // Primitive type + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.set_foo_int(123); + int size = message1.ByteSizeLong(); + data.resize(size); + + { + // Allow the output stream to buffer only one byte at a time. + io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + io::CodedOutputStream output_stream(&array_stream); + message1.SerializeWithCachedSizes(&output_stream); + EXPECT_FALSE(output_stream.HadError()); + EXPECT_EQ(size, output_stream.ByteCount()); + } + + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(message2.foo_int(), 123); + } + + // String + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.set_foo_string("foo"); + int size = message1.ByteSizeLong(); + data.resize(size); + + { + // Allow the output stream to buffer only one byte at a time. + io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + io::CodedOutputStream output_stream(&array_stream); + message1.SerializeWithCachedSizes(&output_stream); + EXPECT_FALSE(output_stream.HadError()); + EXPECT_EQ(size, output_stream.ByteCount()); + } + + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(message2.foo_string(), "foo"); + } + + + // Bytes + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.set_foo_bytes("qux"); + int size = message1.ByteSizeLong(); + data.resize(size); + + { + // Allow the output stream to buffer only one byte at a time. + io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + io::CodedOutputStream output_stream(&array_stream); + message1.SerializeWithCachedSizes(&output_stream); + EXPECT_FALSE(output_stream.HadError()); + EXPECT_EQ(size, output_stream.ByteCount()); + } + + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(message2.foo_bytes(), "qux"); + } + + // Enum + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.set_foo_enum(UNITTEST::TestOneof2::FOO); + int size = message1.ByteSizeLong(); + data.resize(size); + + { + // Allow the output stream to buffer only one byte at a time. + io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + io::CodedOutputStream output_stream(&array_stream); + message1.SerializeWithCachedSizes(&output_stream); + EXPECT_FALSE(output_stream.HadError()); + EXPECT_EQ(size, output_stream.ByteCount()); + } + + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::FOO); + } + + // Message + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.mutable_foo_message()->set_qux_int(234); + int size = message1.ByteSizeLong(); + data.resize(size); + + { + // Allow the output stream to buffer only one byte at a time. + io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + io::CodedOutputStream output_stream(&array_stream); + message1.SerializeWithCachedSizes(&output_stream); + EXPECT_FALSE(output_stream.HadError()); + EXPECT_EQ(size, output_stream.ByteCount()); + } + + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(message2.foo_message().qux_int(), 234); + } + + // Group + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.mutable_foogroup()->set_a(345); + int size = message1.ByteSizeLong(); + data.resize(size); + + { + // Allow the output stream to buffer only one byte at a time. + io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + io::CodedOutputStream output_stream(&array_stream); + message1.SerializeWithCachedSizes(&output_stream); + EXPECT_FALSE(output_stream.HadError()); + EXPECT_EQ(size, output_stream.ByteCount()); + } + + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(message2.foogroup().a(), 345); + } + +} + +TEST_F(OneofTest, MergeFrom) { + UNITTEST::TestOneof2 message1, message2; + + message1.set_foo_int(123); + message2.MergeFrom(message1); + TestUtil::ExpectAtMostOneFieldSetInOneof(message2); + EXPECT_TRUE(message2.has_foo_int()); + EXPECT_EQ(message2.foo_int(), 123); + + message1.set_foo_string("foo"); + message2.MergeFrom(message1); + TestUtil::ExpectAtMostOneFieldSetInOneof(message2); + EXPECT_TRUE(message2.has_foo_string()); + EXPECT_EQ(message2.foo_string(), "foo"); + + + message1.set_foo_bytes("qux"); + message2.MergeFrom(message1); + TestUtil::ExpectAtMostOneFieldSetInOneof(message2); + EXPECT_TRUE(message2.has_foo_bytes()); + EXPECT_EQ(message2.foo_bytes(), "qux"); + + message1.set_foo_enum(UNITTEST::TestOneof2::FOO); + message2.MergeFrom(message1); + TestUtil::ExpectAtMostOneFieldSetInOneof(message2); + EXPECT_TRUE(message2.has_foo_enum()); + EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::FOO); + + message1.mutable_foo_message()->set_qux_int(234); + message2.MergeFrom(message1); + TestUtil::ExpectAtMostOneFieldSetInOneof(message2); + EXPECT_TRUE(message2.has_foo_message()); + EXPECT_EQ(message2.foo_message().qux_int(), 234); + + message1.mutable_foogroup()->set_a(345); + message2.MergeFrom(message1); + TestUtil::ExpectAtMostOneFieldSetInOneof(message2); + EXPECT_TRUE(message2.has_foogroup()); + EXPECT_EQ(message2.foogroup().a(), 345); + +} + +TEST(HELPERS_TEST_NAME, TestSCC) { + UNITTEST::TestMutualRecursionA a; + SCCAnalyzer scc_analyzer((Options())); + const SCC* scc = scc_analyzer.GetSCC(a.GetDescriptor()); + std::vector<string> names; + for (int i = 0; i < scc->descriptors.size(); i++) { + names.push_back(scc->descriptors[i]->full_name()); + } + string package = a.GetDescriptor()->file()->package(); + ASSERT_EQ(names.size(), 4); + std::sort(names.begin(), names.end()); + EXPECT_EQ(names[0], package + ".TestMutualRecursionA"); + EXPECT_EQ(names[1], package + ".TestMutualRecursionA.SubGroup"); + EXPECT_EQ(names[2], package + ".TestMutualRecursionA.SubMessage"); + EXPECT_EQ(names[3], package + ".TestMutualRecursionB"); + + MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); + EXPECT_EQ(result.is_recursive, true); + EXPECT_EQ(result.contains_required, false); + EXPECT_EQ(result.contains_cord, true); // TestAllTypes + EXPECT_EQ(result.contains_extension, false); // TestAllTypes +} + +TEST(HELPERS_TEST_NAME, TestSCCAnalysis) { + { + UNITTEST::TestRecursiveMessage msg; + SCCAnalyzer scc_analyzer((Options())); + const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor()); + MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); + EXPECT_EQ(result.is_recursive, true); + EXPECT_EQ(result.contains_required, false); + EXPECT_EQ(result.contains_cord, false); + EXPECT_EQ(result.contains_extension, false); + } + { + UNITTEST::TestAllExtensions msg; + SCCAnalyzer scc_analyzer((Options())); + const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor()); + MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); + EXPECT_EQ(result.is_recursive, false); + EXPECT_EQ(result.contains_required, false); + EXPECT_EQ(result.contains_cord, false); + EXPECT_EQ(result.contains_extension, true); + } + { + UNITTEST::TestRequired msg; + SCCAnalyzer scc_analyzer((Options())); + const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor()); + MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); + EXPECT_EQ(result.is_recursive, false); + EXPECT_EQ(result.contains_required, true); + EXPECT_EQ(result.contains_cord, false); + EXPECT_EQ(result.contains_extension, false); + } +} + +} // namespace cpp_unittest +} // namespace cpp +} // namespace compiler + +namespace no_generic_services_test { + // Verify that no class called "TestService" was defined in + // unittest_no_generic_services.pb.h by defining a different type by the same + // name. If such a service was generated, this will not compile. + struct TestService { + int i; + }; +} + +namespace compiler { +namespace cpp { +namespace cpp_unittest { + +TEST_F(GENERATED_SERVICE_TEST_NAME, NoGenericServices) { + // Verify that non-services in unittest_no_generic_services.proto were + // generated. + no_generic_services_test::TestMessage message; + message.set_a(1); + message.SetExtension(no_generic_services_test::test_extension, 123); + no_generic_services_test::TestEnum e = no_generic_services_test::FOO; + EXPECT_EQ(e, 1); + + // Verify that a ServiceDescriptor is generated for the service even if the + // class itself is not. + const FileDescriptor* file = + no_generic_services_test::TestMessage::descriptor()->file(); + + ASSERT_EQ(1, file->service_count()); + EXPECT_EQ("TestService", file->service(0)->name()); + ASSERT_EQ(1, file->service(0)->method_count()); + EXPECT_EQ("Foo", file->service(0)->method(0)->name()); +} + +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS + +// =================================================================== + +// This test must run last. It verifies that descriptors were or were not +// initialized depending on whether PROTOBUF_TEST_NO_DESCRIPTORS was defined. +// When this is defined, we skip all tests which are expected to trigger +// descriptor initialization. This verifies that everything else still works +// if descriptors are not initialized. +TEST(DESCRIPTOR_INIT_TEST_NAME, Initialized) { +#ifdef PROTOBUF_TEST_NO_DESCRIPTORS + bool should_have_descriptors = false; +#else + bool should_have_descriptors = true; +#endif + + EXPECT_EQ(should_have_descriptors, + DescriptorPool::generated_pool()->InternalIsFileLoaded( + UNITTEST_PROTO_PATH)); +} + +} // namespace cpp_unittest + +} // namespace cpp +} // namespace compiler +} // namespace protobuf +} // namespace google diff --git a/src/google/protobuf/compiler/cpp/metadata_test.cc b/src/google/protobuf/compiler/cpp/metadata_test.cc index 456784c6..2ad4edd2 100644 --- a/src/google/protobuf/compiler/cpp/metadata_test.cc +++ b/src/google/protobuf/compiler/cpp/metadata_test.cc @@ -29,9 +29,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/compiler/cpp/cpp_helpers.h> #include <google/protobuf/compiler/cpp/cpp_generator.h> diff --git a/src/google/protobuf/compiler/csharp/csharp_doc_comment.cc b/src/google/protobuf/compiler/csharp/csharp_doc_comment.cc index 636a76a0..a21dc0a4 100644 --- a/src/google/protobuf/compiler/csharp/csharp_doc_comment.cc +++ b/src/google/protobuf/compiler/csharp/csharp_doc_comment.cc @@ -56,7 +56,7 @@ void WriteDocCommentBodyImpl(io::Printer* printer, SourceLocation location) { // node of a summary element, not part of an attribute. comments = StringReplace(comments, "&", "&", true); comments = StringReplace(comments, "<", "<", true); - vector<string> lines = Split(comments, "\n", false /* skip_empty */); + std::vector<string> lines = Split(comments, "\n", false /* skip_empty */); // TODO: We really should work out which part to put in the summary and which to put in the remarks... // but that needs to be part of a bigger effort to understand the markdown better anyway. printer->Print("/// <summary>\n"); diff --git a/src/google/protobuf/compiler/csharp/csharp_enum.cc b/src/google/protobuf/compiler/csharp/csharp_enum.cc index 9759e3ef..32c71990 100644 --- a/src/google/protobuf/compiler/csharp/csharp_enum.cc +++ b/src/google/protobuf/compiler/csharp/csharp_enum.cc @@ -43,8 +43,6 @@ #include <google/protobuf/compiler/csharp/csharp_helpers.h> #include <google/protobuf/compiler/csharp/csharp_options.h> -using google::protobuf::internal::scoped_ptr; - namespace google { namespace protobuf { namespace compiler { diff --git a/src/google/protobuf/compiler/csharp/csharp_field_base.cc b/src/google/protobuf/compiler/csharp/csharp_field_base.cc index ecf29ece..7e737e47 100644 --- a/src/google/protobuf/compiler/csharp/csharp_field_base.cc +++ b/src/google/protobuf/compiler/csharp/csharp_field_base.cc @@ -46,8 +46,6 @@ #include <google/protobuf/compiler/csharp/csharp_helpers.h> #include <google/protobuf/compiler/csharp/csharp_names.h> -using google::protobuf::internal::scoped_ptr; - namespace google { namespace protobuf { namespace compiler { diff --git a/src/google/protobuf/compiler/csharp/csharp_generator.cc b/src/google/protobuf/compiler/csharp/csharp_generator.cc index c13ed65b..0c93fc29 100644 --- a/src/google/protobuf/compiler/csharp/csharp_generator.cc +++ b/src/google/protobuf/compiler/csharp/csharp_generator.cc @@ -44,8 +44,6 @@ #include <google/protobuf/compiler/csharp/csharp_options.h> #include <google/protobuf/compiler/csharp/csharp_reflection_class.h> -using google::protobuf::internal::scoped_ptr; - namespace google { namespace protobuf { namespace compiler { @@ -64,7 +62,7 @@ bool Generator::Generate( GeneratorContext* generator_context, string* error) const { - vector<pair<string, string> > options; + std::vector<std::pair<string, string> > options; ParseGeneratorParameter(parameter, &options); // We only support proto3 - but we make an exception for descriptor.proto. @@ -100,7 +98,7 @@ bool Generator::Generate( *error = filename_error; return false; } - scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( generator_context->Open(filename)); io::Printer printer(output.get(), '$'); diff --git a/src/google/protobuf/compiler/csharp/csharp_helpers.cc b/src/google/protobuf/compiler/csharp/csharp_helpers.cc index 5bca1ffa..04b61074 100644 --- a/src/google/protobuf/compiler/csharp/csharp_helpers.cc +++ b/src/google/protobuf/compiler/csharp/csharp_helpers.cc @@ -169,7 +169,7 @@ std::string UnderscoresToCamelCase(const std::string& input, } } // Add a trailing "_" if the name should be altered. - if (input[input.size() - 1] == '#') { + if (input.size() > 0 && input[input.size() - 1] == '#') { result += '_'; } return result; diff --git a/src/google/protobuf/compiler/csharp/csharp_map_field.cc b/src/google/protobuf/compiler/csharp/csharp_map_field.cc index e6eac6ed..d58514ce 100644 --- a/src/google/protobuf/compiler/csharp/csharp_map_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_map_field.cc @@ -63,9 +63,9 @@ void MapFieldGenerator::GenerateMembers(io::Printer* printer) { descriptor_->message_type()->FindFieldByName("value"); variables_["key_type_name"] = type_name(key_descriptor); variables_["value_type_name"] = type_name(value_descriptor); - scoped_ptr<FieldGeneratorBase> key_generator( + std::unique_ptr<FieldGeneratorBase> key_generator( CreateFieldGenerator(key_descriptor, 1, this->options())); - scoped_ptr<FieldGeneratorBase> value_generator( + std::unique_ptr<FieldGeneratorBase> value_generator( CreateFieldGenerator(value_descriptor, 2, this->options())); printer->Print( diff --git a/src/google/protobuf/compiler/csharp/csharp_message.cc b/src/google/protobuf/compiler/csharp/csharp_message.cc index 17b4a071..8a4307f1 100644 --- a/src/google/protobuf/compiler/csharp/csharp_message.cc +++ b/src/google/protobuf/compiler/csharp/csharp_message.cc @@ -49,8 +49,6 @@ #include <google/protobuf/compiler/csharp/csharp_message.h> #include <google/protobuf/compiler/csharp/csharp_names.h> -using google::protobuf::internal::scoped_ptr; - namespace google { namespace protobuf { namespace compiler { @@ -184,7 +182,7 @@ void MessageGenerator::Generate(io::Printer* printer) { "field_name", fieldDescriptor->name(), "field_constant_name", GetFieldConstantName(fieldDescriptor), "index", SimpleItoa(fieldDescriptor->number())); - scoped_ptr<FieldGeneratorBase> generator( + std::unique_ptr<FieldGeneratorBase> generator( CreateFieldGeneratorInternal(fieldDescriptor)); generator->GenerateMembers(printer); printer->Print("\n"); @@ -293,7 +291,7 @@ void MessageGenerator::GenerateCloningCode(io::Printer* printer) { // Clone non-oneof fields first for (int i = 0; i < descriptor_->field_count(); i++) { if (!descriptor_->field(i)->containing_oneof()) { - scoped_ptr<FieldGeneratorBase> generator( + std::unique_ptr<FieldGeneratorBase> generator( CreateFieldGeneratorInternal(descriptor_->field(i))); generator->GenerateCloningCode(printer); } @@ -307,7 +305,7 @@ void MessageGenerator::GenerateCloningCode(io::Printer* printer) { printer->Indent(); for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - scoped_ptr<FieldGeneratorBase> generator(CreateFieldGeneratorInternal(field)); + std::unique_ptr<FieldGeneratorBase> generator(CreateFieldGeneratorInternal(field)); vars["field_property_name"] = GetPropertyName(field); printer->Print( vars, @@ -361,7 +359,7 @@ void MessageGenerator::GenerateFrameworkMethods(io::Printer* printer) { " }\n"); printer->Indent(); for (int i = 0; i < descriptor_->field_count(); i++) { - scoped_ptr<FieldGeneratorBase> generator( + std::unique_ptr<FieldGeneratorBase> generator( CreateFieldGeneratorInternal(descriptor_->field(i))); generator->WriteEquals(printer); } @@ -382,7 +380,7 @@ void MessageGenerator::GenerateFrameworkMethods(io::Printer* printer) { " int hash = 1;\n"); printer->Indent(); for (int i = 0; i < descriptor_->field_count(); i++) { - scoped_ptr<FieldGeneratorBase> generator( + std::unique_ptr<FieldGeneratorBase> generator( CreateFieldGeneratorInternal(descriptor_->field(i))); generator->WriteHash(printer); } @@ -413,7 +411,7 @@ void MessageGenerator::GenerateMessageSerializationMethods(io::Printer* printer) // Serialize all the fields for (int i = 0; i < fields_by_number().size(); i++) { - scoped_ptr<FieldGeneratorBase> generator( + std::unique_ptr<FieldGeneratorBase> generator( CreateFieldGeneratorInternal(fields_by_number()[i])); generator->GenerateSerializationCode(printer); } @@ -435,7 +433,7 @@ void MessageGenerator::GenerateMessageSerializationMethods(io::Printer* printer) printer->Indent(); printer->Print("int size = 0;\n"); for (int i = 0; i < descriptor_->field_count(); i++) { - scoped_ptr<FieldGeneratorBase> generator( + std::unique_ptr<FieldGeneratorBase> generator( CreateFieldGeneratorInternal(descriptor_->field(i))); generator->GenerateSerializedSizeCode(printer); } @@ -469,7 +467,7 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) { // Merge non-oneof fields for (int i = 0; i < descriptor_->field_count(); i++) { if (!descriptor_->field(i)->containing_oneof()) { - scoped_ptr<FieldGeneratorBase> generator( + std::unique_ptr<FieldGeneratorBase> generator( CreateFieldGeneratorInternal(descriptor_->field(i))); generator->GenerateMergingCode(printer); } @@ -487,7 +485,7 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) { vars, "case $property_name$OneofCase.$field_property_name$:\n"); printer->Indent(); - scoped_ptr<FieldGeneratorBase> generator(CreateFieldGeneratorInternal(field)); + std::unique_ptr<FieldGeneratorBase> generator(CreateFieldGeneratorInternal(field)); generator->GenerateMergingCode(printer); printer->Print("break;\n"); printer->Outdent(); @@ -546,7 +544,7 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) { printer->Print("case $tag$: {\n", "tag", SimpleItoa(tag)); printer->Indent(); - scoped_ptr<FieldGeneratorBase> generator( + std::unique_ptr<FieldGeneratorBase> generator( CreateFieldGeneratorInternal(field)); generator->GenerateParsingCode(printer); printer->Print("break;\n"); diff --git a/src/google/protobuf/compiler/csharp/csharp_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_message_field.cc index 59b7edfb..cf1b4dbf 100644 --- a/src/google/protobuf/compiler/csharp/csharp_message_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_message_field.cc @@ -133,7 +133,7 @@ void MessageFieldGenerator::WriteToString(io::Printer* printer) { void MessageFieldGenerator::GenerateCloningCode(io::Printer* printer) { printer->Print(variables_, - "$property_name$ = other.$has_property_check$ ? other.$property_name$.Clone() : null;\n"); + "$name$_ = other.$has_property_check$ ? other.$name$_.Clone() : null;\n"); } void MessageFieldGenerator::GenerateFreezingCode(io::Printer* printer) { diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc index 8fa0b050..90af569c 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc @@ -66,11 +66,11 @@ void RepeatedMessageFieldGenerator::GenerateMembers(io::Printer* printer) { // "create single field generator for this repeated field" // function, but it doesn't seem worth it for just this. if (IsWrapperType(descriptor_)) { - scoped_ptr<FieldGeneratorBase> single_generator( + std::unique_ptr<FieldGeneratorBase> single_generator( new WrapperFieldGenerator(descriptor_, fieldOrdinal_, this->options())); single_generator->GenerateCodecCode(printer); } else { - scoped_ptr<FieldGeneratorBase> single_generator( + std::unique_ptr<FieldGeneratorBase> single_generator( new MessageFieldGenerator(descriptor_, fieldOrdinal_, this->options())); single_generator->GenerateCodecCode(printer); } diff --git a/src/google/protobuf/compiler/importer.cc b/src/google/protobuf/compiler/importer.cc index a5341e0d..c3831e72 100644 --- a/src/google/protobuf/compiler/importer.cc +++ b/src/google/protobuf/compiler/importer.cc @@ -32,7 +32,6 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. - #ifdef _MSC_VER #include <direct.h> #else @@ -45,9 +44,6 @@ #include <algorithm> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/compiler/importer.h> @@ -55,6 +51,8 @@ #include <google/protobuf/io/tokenizer.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/stubs/strutil.h> + + #include <google/protobuf/stubs/io_win32.h> #ifdef _WIN32 @@ -131,7 +129,7 @@ SourceTreeDescriptorDatabase::~SourceTreeDescriptorDatabase() {} bool SourceTreeDescriptorDatabase::FindFileByName( const string& filename, FileDescriptorProto* output) { - google::protobuf::scoped_ptr<io::ZeroCopyInputStream> input(source_tree_->Open(filename)); + std::unique_ptr<io::ZeroCopyInputStream> input(source_tree_->Open(filename)); if (input == NULL) { if (error_collector_ != NULL) { error_collector_->AddError(filename, -1, 0, @@ -420,7 +418,7 @@ DiskSourceTree::DiskFileToVirtualFile( // Verify that we can open the file. Note that this also has the side-effect // of verifying that we are not canonicalizing away any non-existent // directories. - google::protobuf::scoped_ptr<io::ZeroCopyInputStream> stream(OpenDiskFile(disk_file)); + std::unique_ptr<io::ZeroCopyInputStream> stream(OpenDiskFile(disk_file)); if (stream == NULL) { return CANNOT_OPEN; } @@ -430,7 +428,7 @@ DiskSourceTree::DiskFileToVirtualFile( bool DiskSourceTree::VirtualFileToDiskFile(const string& virtual_file, string* disk_file) { - google::protobuf::scoped_ptr<io::ZeroCopyInputStream> stream( + std::unique_ptr<io::ZeroCopyInputStream> stream( OpenVirtualFile(virtual_file, disk_file)); return stream != NULL; } diff --git a/src/google/protobuf/compiler/importer_unittest.cc b/src/google/protobuf/compiler/importer_unittest.cc index a96ac853..73bef3f4 100644 --- a/src/google/protobuf/compiler/importer_unittest.cc +++ b/src/google/protobuf/compiler/importer_unittest.cc @@ -36,9 +36,6 @@ #include <google/protobuf/stubs/hash.h> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> @@ -268,7 +265,7 @@ class DiskSourceTreeTest : public testing::Test { void ExpectFileContents(const string& filename, const char* expected_contents) { - google::protobuf::scoped_ptr<io::ZeroCopyInputStream> input(source_tree_.Open(filename)); + std::unique_ptr<io::ZeroCopyInputStream> input(source_tree_.Open(filename)); ASSERT_FALSE(input == NULL); @@ -285,7 +282,7 @@ class DiskSourceTreeTest : public testing::Test { void ExpectCannotOpenFile(const string& filename, const string& error_message) { - google::protobuf::scoped_ptr<io::ZeroCopyInputStream> input(source_tree_.Open(filename)); + std::unique_ptr<io::ZeroCopyInputStream> input(source_tree_.Open(filename)); EXPECT_TRUE(input == NULL); EXPECT_EQ(error_message, source_tree_.GetLastErrorMessage()); } diff --git a/src/google/protobuf/compiler/java/java_context.cc b/src/google/protobuf/compiler/java/java_context.cc index 0771d5e1..2528c2d1 100644 --- a/src/google/protobuf/compiler/java/java_context.cc +++ b/src/google/protobuf/compiler/java/java_context.cc @@ -69,14 +69,14 @@ bool IsConflicting(const FieldDescriptor* field1, const string& name1, // field1 is repeated, and field2 is not. if (name1 + "Count" == name2) { *info = "both repeated field \"" + field1->name() + "\" and singular " + - "field \"" + field2->name() + "\" generates the method \"" + - "get" + name1 + "Count()\""; + "field \"" + field2->name() + "\" generate the method \"" + + "get" + name1 + "Count()\""; return true; } if (name1 + "List" == name2) { *info = "both repeated field \"" + field1->name() + "\" and singular " + - "field \"" + field2->name() + "\" generates the method \"" + - "get" + name1 + "List()\""; + "field \"" + field2->name() + "\" generate the method \"" + + "get" + name1 + "List()\""; return true; } // Well, there are obviously many more conflicting cases, but it probably diff --git a/src/google/protobuf/compiler/java/java_context.h b/src/google/protobuf/compiler/java/java_context.h index 9a74c430..9de7415a 100644 --- a/src/google/protobuf/compiler/java/java_context.h +++ b/src/google/protobuf/compiler/java/java_context.h @@ -33,9 +33,6 @@ #include <map> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <vector> #include <google/protobuf/stubs/common.h> @@ -97,7 +94,7 @@ class Context { void InitializeFieldGeneratorInfoForFields( const std::vector<const FieldDescriptor*>& fields); - google::protobuf::scoped_ptr<ClassNameResolver> name_resolver_; + std::unique_ptr<ClassNameResolver> name_resolver_; std::map<const FieldDescriptor*, FieldGeneratorInfo> field_generator_info_map_; std::map<const OneofDescriptor*, OneofGeneratorInfo> diff --git a/src/google/protobuf/compiler/java/java_enum.cc b/src/google/protobuf/compiler/java/java_enum.cc index d125ebe5..bef69f1a 100644 --- a/src/google/protobuf/compiler/java/java_enum.cc +++ b/src/google/protobuf/compiler/java/java_enum.cc @@ -36,12 +36,12 @@ #include <string> #include <google/protobuf/compiler/java/java_context.h> -#include <google/protobuf/compiler/java/java_enum.h> #include <google/protobuf/compiler/java/java_doc_comment.h> +#include <google/protobuf/compiler/java/java_enum.h> #include <google/protobuf/compiler/java/java_helpers.h> #include <google/protobuf/compiler/java/java_name_resolver.h> -#include <google/protobuf/io/printer.h> #include <google/protobuf/descriptor.pb.h> +#include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> namespace google { diff --git a/src/google/protobuf/compiler/java/java_enum_field.cc b/src/google/protobuf/compiler/java/java_enum_field.cc index 642cdd36..ef64d88b 100644 --- a/src/google/protobuf/compiler/java/java_enum_field.cc +++ b/src/google/protobuf/compiler/java/java_enum_field.cc @@ -305,11 +305,15 @@ GenerateBuildingCode(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { printer->Print(variables_, "if ($get_has_field_bit_from_local$) {\n" + " result.$name$_ = $name$_;\n" " $set_has_field_bit_to_local$;\n" + "} else {\n" + " result.$name$_ = $default_number$;\n" "}\n"); + } else { + printer->Print(variables_, + "result.$name$_ = $name$_;\n"); } - printer->Print(variables_, - "result.$name$_ = $name$_;\n"); } void ImmutableEnumFieldGenerator:: @@ -674,8 +678,7 @@ GenerateMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); } - if (descriptor_->is_packed() && - context_->HasGeneratedMethods(descriptor_->containing_type())) { + if (descriptor_->is_packed()) { printer->Print(variables_, "private int $name$MemoizedSerializedSize;\n"); } diff --git a/src/google/protobuf/compiler/java/java_enum_field_lite.cc b/src/google/protobuf/compiler/java/java_enum_field_lite.cc index a4de1e23..f1fe71b0 100644 --- a/src/google/protobuf/compiler/java/java_enum_field_lite.cc +++ b/src/google/protobuf/compiler/java/java_enum_field_lite.cc @@ -165,6 +165,7 @@ GenerateMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return $get_has_field_bit_message$;\n" "}\n"); @@ -173,6 +174,7 @@ GenerateMembers(io::Printer* printer) const { if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" " return $name$_;\n" "}\n"); @@ -180,6 +182,7 @@ GenerateMembers(io::Printer* printer) const { } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " $type$ result = $type$.forNumber($name$_);\n" " return result == null ? $unknown$ : result;\n" @@ -217,6 +220,7 @@ GenerateBuilderMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return instance.has$capitalized_name$();\n" "}\n"); @@ -225,6 +229,7 @@ GenerateBuilderMembers(io::Printer* printer) const { if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" " return instance.get$capitalized_name$Value();\n" "}\n"); @@ -241,6 +246,7 @@ GenerateBuilderMembers(io::Printer* printer) const { } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " return instance.get$capitalized_name$();\n" "}\n"); @@ -378,6 +384,7 @@ GenerateMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return $has_oneof_case_message$;\n" "}\n"); @@ -386,6 +393,7 @@ GenerateMembers(io::Printer* printer) const { if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" " if ($has_oneof_case_message$) {\n" " return (java.lang.Integer) $oneof_name$_;\n" @@ -396,6 +404,7 @@ GenerateMembers(io::Printer* printer) const { } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " if ($has_oneof_case_message$) {\n" " $type$ result = $type$.forNumber((java.lang.Integer) $oneof_name$_);\n" @@ -439,6 +448,7 @@ GenerateBuilderMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return instance.has$capitalized_name$();\n" "}\n"); @@ -447,6 +457,7 @@ GenerateBuilderMembers(io::Printer* printer) const { if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" " return instance.get$capitalized_name$Value();\n" "}\n"); @@ -463,6 +474,7 @@ GenerateBuilderMembers(io::Printer* printer) const { } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " return instance.get$capitalized_name$();\n" "}\n"); @@ -611,6 +623,7 @@ GenerateMembers(io::Printer* printer) const { " java.lang.Integer, $type$> $name$_converter_ =\n" " new com.google.protobuf.Internal.ListAdapter.Converter<\n" " java.lang.Integer, $type$>() {\n" + " @java.lang.Override\n" " public $type$ convert(java.lang.Integer from) {\n" " $type$ result = $type$.forNumber(from);\n" " return result == null ? $unknown$ : result;\n" @@ -619,6 +632,7 @@ GenerateMembers(io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List<$type$> " "${$get$capitalized_name$List$}$() {\n" " return new com.google.protobuf.Internal.ListAdapter<\n" @@ -627,12 +641,14 @@ GenerateMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" " return $name$_.size();\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" " return $name$_converter_.convert($name$_.getInt(index));\n" "}\n"); @@ -640,6 +656,7 @@ GenerateMembers(io::Printer* printer) const { if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List<java.lang.Integer>\n" "${$get$capitalized_name$ValueList$}$() {\n" " return $name$_;\n" @@ -647,6 +664,7 @@ GenerateMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n" " return $name$_.getInt(index);\n" "}\n"); @@ -732,6 +750,7 @@ void RepeatedImmutableEnumFieldLiteGenerator:: GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List<$type$> " "${$get$capitalized_name$List$}$() {\n" " return instance.get$capitalized_name$List();\n" @@ -739,12 +758,14 @@ GenerateBuilderMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" " return instance.get$capitalized_name$Count();\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" " return instance.get$capitalized_name$(index);\n" "}\n"); @@ -787,6 +808,7 @@ GenerateBuilderMembers(io::Printer* printer) const { if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List<java.lang.Integer>\n" "${$get$capitalized_name$ValueList$}$() {\n" " return java.util.Collections.unmodifiableList(\n" @@ -795,6 +817,7 @@ GenerateBuilderMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n" " return instance.get$capitalized_name$Value(index);\n" "}\n"); diff --git a/src/google/protobuf/compiler/java/java_enum_lite.cc b/src/google/protobuf/compiler/java/java_enum_lite.cc index ab3b3323..806008ee 100644 --- a/src/google/protobuf/compiler/java/java_enum_lite.cc +++ b/src/google/protobuf/compiler/java/java_enum_lite.cc @@ -36,12 +36,12 @@ #include <string> #include <google/protobuf/compiler/java/java_context.h> -#include <google/protobuf/compiler/java/java_enum_lite.h> #include <google/protobuf/compiler/java/java_doc_comment.h> +#include <google/protobuf/compiler/java/java_enum_lite.h> #include <google/protobuf/compiler/java/java_helpers.h> #include <google/protobuf/compiler/java/java_name_resolver.h> -#include <google/protobuf/io/printer.h> #include <google/protobuf/descriptor.pb.h> +#include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> namespace google { @@ -135,6 +135,7 @@ void EnumLiteGenerator::Generate(io::Printer* printer) { printer->Print( "\n" + "@java.lang.Override\n" "public final int getNumber() {\n"); if (SupportUnknownEnumValue(descriptor_->file())) { printer->Print( @@ -182,6 +183,7 @@ void EnumLiteGenerator::Generate(io::Printer* printer) { "private static final com.google.protobuf.Internal.EnumLiteMap<\n" " $classname$> internalValueMap =\n" " new com.google.protobuf.Internal.EnumLiteMap<$classname$>() {\n" + " @java.lang.Override\n" " public $classname$ findValueByNumber(int number) {\n" " return $classname$.forNumber(number);\n" " }\n" diff --git a/src/google/protobuf/compiler/java/java_extension.cc b/src/google/protobuf/compiler/java/java_extension.cc index 9b9be55b..3eb1370d 100644 --- a/src/google/protobuf/compiler/java/java_extension.cc +++ b/src/google/protobuf/compiler/java/java_extension.cc @@ -141,6 +141,7 @@ void ImmutableExtensionGenerator::Generate(io::Printer* printer) { " $singular_type$.class,\n" " $prototype$);\n"); } + printer->Annotate("name", descriptor_); } int ImmutableExtensionGenerator::GenerateNonNestedInitializationCode( diff --git a/src/google/protobuf/compiler/java/java_extension_lite.cc b/src/google/protobuf/compiler/java/java_extension_lite.cc index c48c92e9..70ce8e7d 100644 --- a/src/google/protobuf/compiler/java/java_extension_lite.cc +++ b/src/google/protobuf/compiler/java/java_extension_lite.cc @@ -96,6 +96,7 @@ void ImmutableExtensionLiteGenerator::Generate(io::Printer* printer) { " com.google.protobuf.WireFormat.FieldType.$type_constant$,\n" " $singular_type$.class);\n"); } + printer->Annotate("name", descriptor_); } int ImmutableExtensionLiteGenerator::GenerateNonNestedInitializationCode( diff --git a/src/google/protobuf/compiler/java/java_field.cc b/src/google/protobuf/compiler/java/java_field.cc index 1ab18629..93de0229 100644 --- a/src/google/protobuf/compiler/java/java_field.cc +++ b/src/google/protobuf/compiler/java/java_field.cc @@ -35,9 +35,6 @@ #include <google/protobuf/compiler/java/java_field.h> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> @@ -214,8 +211,7 @@ template <> FieldGeneratorMap<ImmutableFieldGenerator>::FieldGeneratorMap( const Descriptor* descriptor, Context* context) : descriptor_(descriptor), - field_generators_(new google::protobuf::scoped_ptr< - ImmutableFieldGenerator>[descriptor->field_count()]) { + field_generators_(descriptor->field_count()) { // Construct all the FieldGenerators and assign them bit indices for their // bit fields. @@ -237,8 +233,7 @@ template <> FieldGeneratorMap<ImmutableFieldLiteGenerator>::FieldGeneratorMap( const Descriptor* descriptor, Context* context) : descriptor_(descriptor), - field_generators_(new google::protobuf::scoped_ptr< - ImmutableFieldLiteGenerator>[descriptor->field_count()]) { + field_generators_(descriptor->field_count()) { // Construct all the FieldGenerators and assign them bit indices for their // bit fields. int messageBitIndex = 0; diff --git a/src/google/protobuf/compiler/java/java_field.h b/src/google/protobuf/compiler/java/java_field.h index cc1d83d9..7275c099 100644 --- a/src/google/protobuf/compiler/java/java_field.h +++ b/src/google/protobuf/compiler/java/java_field.h @@ -37,9 +37,6 @@ #include <map> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <string> #include <google/protobuf/stubs/common.h> @@ -141,7 +138,7 @@ class FieldGeneratorMap { const Descriptor* descriptor_; Context* context_; ClassNameResolver* name_resolver_; - google::protobuf::scoped_array<google::protobuf::scoped_ptr<FieldGeneratorType> > field_generators_; + std::vector<std::unique_ptr<FieldGeneratorType>> field_generators_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap); }; @@ -163,6 +160,14 @@ template<> FieldGeneratorMap<ImmutableFieldGenerator>::~FieldGeneratorMap(); +template <> +FieldGeneratorMap<ImmutableFieldLiteGenerator>::FieldGeneratorMap( + const Descriptor* descriptor, Context* context); + +template <> +FieldGeneratorMap<ImmutableFieldLiteGenerator>::~FieldGeneratorMap(); + + // Field information used in FieldGeneartors. struct FieldGeneratorInfo { string name; diff --git a/src/google/protobuf/compiler/java/java_file.cc b/src/google/protobuf/compiler/java/java_file.cc index 21133a15..5583b779 100644 --- a/src/google/protobuf/compiler/java/java_file.cc +++ b/src/google/protobuf/compiler/java/java_file.cc @@ -35,9 +35,6 @@ #include <google/protobuf/compiler/java/java_file.h> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <set> #include <google/protobuf/compiler/java/java_context.h> @@ -51,9 +48,9 @@ #include <google/protobuf/compiler/java/java_service.h> #include <google/protobuf/compiler/java/java_shared_code_generator.h> #include <google/protobuf/compiler/code_generator.h> +#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/io/zero_copy_stream.h> -#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/dynamic_message.h> #include <google/protobuf/stubs/strutil.h> @@ -136,7 +133,7 @@ void CollectExtensions(const FileDescriptorProto& file_proto, "descriptor.proto is not in the transitive dependencies. " "This normally should not happen. Please report a bug."; DynamicMessageFactory factory; - google::protobuf::scoped_ptr<Message> dynamic_file_proto( + std::unique_ptr<Message> dynamic_file_proto( factory.GetPrototype(file_proto_desc)->New()); GOOGLE_CHECK(dynamic_file_proto.get() != NULL); GOOGLE_CHECK(dynamic_file_proto->ParseFromString(file_data)); @@ -189,10 +186,8 @@ FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options, bool immutable_api) : file_(file), java_package_(FileJavaPackage(file, immutable_api)), - message_generators_( - new google::protobuf::scoped_ptr<MessageGenerator>[file->message_type_count()]), - extension_generators_( - new google::protobuf::scoped_ptr<ExtensionGenerator>[file->extension_count()]), + message_generators_(file->message_type_count()), + extension_generators_(file->extension_count()), context_(new Context(file, options)), name_resolver_(context_->GetNameResolver()), options_(options), @@ -228,6 +223,16 @@ bool FileGenerator::Validate(string* error) { "option to specify a different outer class name for the .proto file."); return false; } + // Print a warning if optimize_for = LITE_RUNTIME is used. + if (file_->options().optimize_for() == FileOptions::LITE_RUNTIME) { + GOOGLE_LOG(WARNING) + << "The optimize_for = LITE_RUNTIME option is no longer supported by " + << "protobuf Java code generator and may generate broken code. It " + << "will be ignored by protoc in the future and protoc will always " + << "generate full runtime code for Java. To use Java Lite runtime, " + << "users should use the Java Lite plugin instead. See:\n" + << " https://github.com/google/protobuf/blob/master/java/lite.md"; + } return true; } @@ -309,7 +314,7 @@ void FileGenerator::Generate(io::Printer* printer) { } if (HasGenericServices(file_, context_->EnforceLite())) { for (int i = 0; i < file_->service_count(); i++) { - google::protobuf::scoped_ptr<ServiceGenerator> generator( + std::unique_ptr<ServiceGenerator> generator( generator_factory_->NewServiceGenerator(file_->service(i))); generator->Generate(printer); } @@ -435,7 +440,7 @@ void FileGenerator::GenerateDescriptorInitializationCodeForImmutable( " com.google.protobuf.ExtensionRegistry.newInstance();\n"); FieldDescriptorSet::iterator it; for (it = extensions.begin(); it != extensions.end(); it++) { - google::protobuf::scoped_ptr<ExtensionGenerator> generator( + std::unique_ptr<ExtensionGenerator> generator( generator_factory_->NewExtensionGenerator(*it)); bytecode_estimate += generator->GenerateRegistrationCode(printer); MaybeRestartJavaMethod( @@ -588,7 +593,7 @@ static void GenerateSibling(const string& package_dir, io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector( &annotations); - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename)); + std::unique_ptr<io::ZeroCopyOutputStream> output(context->Open(filename)); io::Printer printer(output.get(), '$', annotate_code ? &annotation_collector : NULL); @@ -607,7 +612,7 @@ static void GenerateSibling(const string& package_dir, (generator->*pfn)(&printer); if (annotate_code) { - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output( + std::unique_ptr<io::ZeroCopyOutputStream> info_output( context->Open(info_full_path)); annotations.SerializeToZeroCopyStream(info_output.get()); annotation_list->push_back(info_full_path); @@ -650,7 +655,7 @@ void FileGenerator::GenerateSiblings(const string& package_dir, } if (HasGenericServices(file_, context_->EnforceLite())) { for (int i = 0; i < file_->service_count(); i++) { - google::protobuf::scoped_ptr<ServiceGenerator> generator( + std::unique_ptr<ServiceGenerator> generator( generator_factory_->NewServiceGenerator(file_->service(i))); GenerateSibling<ServiceGenerator>( package_dir, java_package_, file_->service(i), context, file_list, diff --git a/src/google/protobuf/compiler/java/java_file.h b/src/google/protobuf/compiler/java/java_file.h index e95aef09..78833a45 100644 --- a/src/google/protobuf/compiler/java/java_file.h +++ b/src/google/protobuf/compiler/java/java_file.h @@ -36,9 +36,6 @@ #define GOOGLE_PROTOBUF_COMPILER_JAVA_FILE_H__ #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <string> #include <vector> #include <google/protobuf/stubs/common.h> @@ -101,10 +98,10 @@ class FileGenerator { string java_package_; string classname_; - google::protobuf::scoped_array<google::protobuf::scoped_ptr<MessageGenerator> > message_generators_; - google::protobuf::scoped_array<google::protobuf::scoped_ptr<ExtensionGenerator> > extension_generators_; - google::protobuf::scoped_ptr<GeneratorFactory> generator_factory_; - google::protobuf::scoped_ptr<Context> context_; + std::vector<std::unique_ptr<MessageGenerator>> message_generators_; + std::vector<std::unique_ptr<ExtensionGenerator>> extension_generators_; + std::unique_ptr<GeneratorFactory> generator_factory_; + std::unique_ptr<Context> context_; ClassNameResolver* name_resolver_; const Options options_; bool immutable_api_; diff --git a/src/google/protobuf/compiler/java/java_generator.cc b/src/google/protobuf/compiler/java/java_generator.cc index 84a3b90d..a5b2e784 100644 --- a/src/google/protobuf/compiler/java/java_generator.cc +++ b/src/google/protobuf/compiler/java/java_generator.cc @@ -35,9 +35,6 @@ #include <google/protobuf/compiler/java/java_generator.h> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/compiler/java/java_file.h> #include <google/protobuf/compiler/java/java_generator_factory.h> @@ -45,9 +42,9 @@ #include <google/protobuf/compiler/java/java_name_resolver.h> #include <google/protobuf/compiler/java/java_options.h> #include <google/protobuf/compiler/java/java_shared_code_generator.h> +#include <google/protobuf/descriptor.pb.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> @@ -144,7 +141,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file, } // Generate main java file. - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( context->Open(java_filename)); GeneratedCodeInfo annotations; io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector( @@ -160,7 +157,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file, &all_annotations); if (file_options.annotate_code) { - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output( + std::unique_ptr<io::ZeroCopyOutputStream> info_output( context->Open(info_full_path)); annotations.SerializeToZeroCopyStream(info_output.get()); } @@ -175,7 +172,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file, if (!file_options.output_list_file.empty()) { // Generate output list. This is just a simple text file placed in a // deterministic location which lists the .java files being generated. - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> srclist_raw_output( + std::unique_ptr<io::ZeroCopyOutputStream> srclist_raw_output( context->Open(file_options.output_list_file)); io::Printer srclist_printer(srclist_raw_output.get(), '$'); for (int i = 0; i < all_files.size(); i++) { @@ -186,7 +183,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file, if (!file_options.annotation_list_file.empty()) { // Generate output list. This is just a simple text file placed in a // deterministic location which lists the .java files being generated. - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> annotation_list_raw_output( + std::unique_ptr<io::ZeroCopyOutputStream> annotation_list_raw_output( context->Open(file_options.annotation_list_file)); io::Printer annotation_list_printer(annotation_list_raw_output.get(), '$'); for (int i = 0; i < all_annotations.size(); i++) { diff --git a/src/google/protobuf/compiler/java/java_helpers.cc b/src/google/protobuf/compiler/java/java_helpers.cc index dbb86b87..957076cb 100644 --- a/src/google/protobuf/compiler/java/java_helpers.cc +++ b/src/google/protobuf/compiler/java/java_helpers.cc @@ -75,6 +75,8 @@ const char* kForbiddenWordList[] = { "class", }; +const int kDefaultLookUpStartFieldNumber = 40; + bool IsForbidden(const string& field_name) { for (int i = 0; i < GOOGLE_ARRAYSIZE(kForbiddenWordList); ++i) { if (field_name == kForbiddenWordList[i]) { @@ -103,6 +105,20 @@ string FieldName(const FieldDescriptor* field) { } +// Judge whether should use table or use look up. +// Copied from com.google.protobuf.SchemaUtil.shouldUseTableSwitch +bool ShouldUseTable(int lo, int hi, int number_of_fields) { + if (hi < kDefaultLookUpStartFieldNumber) { + return true; + } + int64 table_space_cost = (static_cast<int64>(hi) - lo + 1); // words + int64 table_time_cost = 3; // comparisons + int64 lookup_space_cost = 3 + 2 * static_cast<int64>(number_of_fields); + int64 lookup_time_cost = 3 + number_of_fields; + return table_space_cost + 3 * table_time_cost <= + lookup_space_cost + 3 * lookup_time_cost; +} + } // namespace void PrintGeneratedAnnotation(io::Printer* printer, char delimiter, @@ -915,6 +931,23 @@ void EscapeUtf16ToString(uint16 code, string* output) { output->append(StringPrintf("\\u%04x", code)); } } + +std::pair<int, int> GetTableDrivenNumberOfEntriesAndLookUpStartFieldNumber( + const FieldDescriptor** fields, int count) { + GOOGLE_CHECK_GT(count, 0); + int table_driven_number_of_entries = count; + int look_up_start_field_number = 0; + for (int i = 0; i < count; i++) { + const int field_number = fields[i]->number(); + if (ShouldUseTable(fields[0]->number(), field_number, i + 1)) { + table_driven_number_of_entries = + field_number - fields[0]->number() + 1 + count - i - 1; + look_up_start_field_number = field_number + 1; + } + } + return std::make_pair( + table_driven_number_of_entries, look_up_start_field_number); +} } // namespace java } // namespace compiler } // namespace protobuf diff --git a/src/google/protobuf/compiler/java/java_helpers.h b/src/google/protobuf/compiler/java/java_helpers.h index 00d683db..dd9b65b8 100644 --- a/src/google/protobuf/compiler/java/java_helpers.h +++ b/src/google/protobuf/compiler/java/java_helpers.h @@ -37,8 +37,8 @@ #include <string> #include <google/protobuf/compiler/java/java_context.h> -#include <google/protobuf/io/printer.h> #include <google/protobuf/descriptor.pb.h> +#include <google/protobuf/io/printer.h> #include <google/protobuf/descriptor.h> namespace google { @@ -414,6 +414,11 @@ void EscapeUtf16ToString(uint16 code, string* output); // bit 3: whether the field is a map field with proto2 enum value. // bits 4-7: unused int GetExperimentalJavaFieldType(const FieldDescriptor* field); + +// To get the total number of entries need to be built for experimental runtime +// and the first field number that are not in the table part +std::pair<int, int> GetTableDrivenNumberOfEntriesAndLookUpStartFieldNumber( + const FieldDescriptor** fields, int count); } // namespace java } // namespace compiler } // namespace protobuf diff --git a/src/google/protobuf/compiler/java/java_lazy_message_field.cc b/src/google/protobuf/compiler/java/java_lazy_message_field.cc index abf8e55c..6544bea0 100644 --- a/src/google/protobuf/compiler/java/java_lazy_message_field.cc +++ b/src/google/protobuf/compiler/java/java_lazy_message_field.cc @@ -233,12 +233,9 @@ void ImmutableLazyMessageFieldGenerator:: GenerateBuildingCode(io::Printer* printer) const { printer->Print(variables_, "if ($get_has_field_bit_from_local$) {\n" + " result.$name$_.set($name$_);\n" " $set_has_field_bit_to_local$;\n" "}\n"); - - printer->Print(variables_, - "result.$name$_.set(\n" - " $name$_);\n"); } void ImmutableLazyMessageFieldGenerator:: diff --git a/src/google/protobuf/compiler/java/java_map_field_lite.cc b/src/google/protobuf/compiler/java/java_map_field_lite.cc index f19ec271..e2e68076 100644 --- a/src/google/protobuf/compiler/java/java_map_field_lite.cc +++ b/src/google/protobuf/compiler/java/java_map_field_lite.cc @@ -301,6 +301,7 @@ GenerateMembers(io::Printer* printer) const { "}\n"); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public int ${$get$capitalized_name$Count$}$() {\n" " return internalGet$capitalized_name$().size();\n" @@ -309,6 +310,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public boolean ${$contains$capitalized_name$$}$(\n" " $key_type$ key) {\n" @@ -339,6 +341,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" "${$get$capitalized_name$Map$}$() {\n" @@ -352,6 +355,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n" " $key_type$ key,\n" @@ -367,6 +371,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n" " $key_type$ key) {\n" @@ -385,6 +390,7 @@ GenerateMembers(io::Printer* printer) const { "/**\n" " * Use {@link #get$capitalized_name$ValueMap()} instead.\n" " */\n" + "@java.lang.Override\n" "@java.lang.Deprecated\n" "public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n" "${$get$capitalized_name$Value$}$() {\n" @@ -394,6 +400,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n" "${$get$capitalized_name$ValueMap$}$() {\n" @@ -404,6 +411,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n" " $key_type$ key,\n" @@ -417,6 +425,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n" " $key_type$ key) {\n" @@ -436,6 +445,7 @@ GenerateMembers(io::Printer* printer) const { "/**\n" " * Use {@link #get$capitalized_name$Map()} instead.\n" " */\n" + "@java.lang.Override\n" "@java.lang.Deprecated\n" "public java.util.Map<$type_parameters$> " "${$get$capitalized_name$$}$() {\n" @@ -445,6 +455,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public java.util.Map<$type_parameters$> " "${$get$capitalized_name$Map$}$() {\n" @@ -455,6 +466,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_type$ ${$get$capitalized_name$OrDefault$}$(\n" " $key_type$ key,\n" @@ -468,6 +480,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n" " $key_type$ key) {\n" @@ -519,6 +532,7 @@ void ImmutableMapFieldLiteGenerator:: GenerateBuilderMembers(io::Printer* printer) const { printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public int ${$get$capitalized_name$Count$}$() {\n" " return instance.get$capitalized_name$Map().size();\n" @@ -527,6 +541,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public boolean ${$contains$capitalized_name$$}$(\n" " $key_type$ key) {\n" @@ -570,6 +585,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" "${$get$capitalized_name$Map$}$() {\n" @@ -580,6 +596,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n" " $key_type$ key,\n" @@ -595,6 +612,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n" " $key_type$ key) {\n" @@ -636,6 +654,7 @@ GenerateBuilderMembers(io::Printer* printer) const { "/**\n" " * Use {@link #get$capitalized_name$ValueMap()} instead.\n" " */\n" + "@java.lang.Override\n" "@java.lang.Deprecated\n" "public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n" "${$get$capitalized_name$Value$}$() {\n" @@ -645,6 +664,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n" "${$get$capitalized_name$ValueMap$}$() {\n" @@ -655,6 +675,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n" " $key_type$ key,\n" @@ -668,6 +689,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n" " $key_type$ key) {\n" @@ -709,6 +731,7 @@ GenerateBuilderMembers(io::Printer* printer) const { "/**\n" " * Use {@link #get$capitalized_name$Map()} instead.\n" " */\n" + "@java.lang.Override\n" "@java.lang.Deprecated\n" "public java.util.Map<$type_parameters$> " "${$get$capitalized_name$$}$() {\n" @@ -718,6 +741,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$" "public java.util.Map<$type_parameters$> " "${$get$capitalized_name$Map$}$() {\n" @@ -728,6 +752,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_type$ ${$get$capitalized_name$OrDefault$}$(\n" " $key_type$ key,\n" @@ -741,6 +766,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n" " $key_type$ key) {\n" diff --git a/src/google/protobuf/compiler/java/java_message.cc b/src/google/protobuf/compiler/java/java_message.cc index eca7cf9a..209c0b2a 100644 --- a/src/google/protobuf/compiler/java/java_message.cc +++ b/src/google/protobuf/compiler/java/java_message.cc @@ -38,9 +38,6 @@ #include <google/protobuf/stubs/hash.h> #include <map> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <vector> #include <google/protobuf/compiler/java/java_context.h> @@ -52,9 +49,9 @@ #include <google/protobuf/compiler/java/java_message_builder.h> #include <google/protobuf/compiler/java/java_message_builder_lite.h> #include <google/protobuf/compiler/java/java_name_resolver.h> +#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/printer.h> -#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/substitute.h> #include <google/protobuf/stubs/strutil.h> @@ -438,7 +435,8 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) { const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); printer->Print( "$deprecation$$field_name$($field_number$),\n", - "deprecation", field->options().deprecated() ? "@java.lang.Deprecated " : "", + "deprecation", + field->options().deprecated() ? "@java.lang.Deprecated " : "", "field_name", ToUpper(field->name()), "field_number", SimpleItoa(field->number())); } @@ -554,6 +552,7 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) { GenerateParser(printer); printer->Print( + "@java.lang.Override\n" "public $classname$ getDefaultInstanceForType() {\n" " return DEFAULT_INSTANCE;\n" "}\n" @@ -577,7 +576,7 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) { void ImmutableMessageGenerator:: GenerateMessageSerializationMethods(io::Printer* printer) { - google::protobuf::scoped_array<const FieldDescriptor * > sorted_fields( + std::unique_ptr<const FieldDescriptor * []> sorted_fields( SortFieldsByNumber(descriptor_)); std::vector<const Descriptor::ExtensionRange*> sorted_extensions; @@ -587,6 +586,7 @@ GenerateMessageSerializationMethods(io::Printer* printer) { std::sort(sorted_extensions.begin(), sorted_extensions.end(), ExtensionRangeOrdering()); printer->Print( + "@java.lang.Override\n" "public void writeTo(com.google.protobuf.CodedOutputStream output)\n" " throws java.io.IOException {\n"); printer->Indent(); @@ -647,6 +647,7 @@ GenerateMessageSerializationMethods(io::Printer* printer) { printer->Print( "}\n" "\n" + "@java.lang.Override\n" "public int getSerializedSize() {\n" " int size = memoizedSize;\n" " if (size != -1) return size;\n" @@ -788,6 +789,7 @@ void ImmutableMessageGenerator::GenerateSerializeOneExtensionRange( void ImmutableMessageGenerator::GenerateBuilder(io::Printer* printer) { // LITE_RUNTIME implements this at the GeneratedMessageLite level. printer->Print( + "@java.lang.Override\n" "public Builder newBuilderForType() { return newBuilder(); }\n"); printer->Print( @@ -797,6 +799,7 @@ void ImmutableMessageGenerator::GenerateBuilder(io::Printer* printer) { "public static Builder newBuilder($classname$ prototype) {\n" " return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);\n" "}\n" + "@java.lang.Override\n" "public Builder toBuilder() {\n" " return this == DEFAULT_INSTANCE\n" " ? new Builder() : new Builder().mergeFrom(this);\n" @@ -840,6 +843,7 @@ GenerateDescriptorMethods(io::Printer* printer) { if (!map_fields.empty()) { printer->Print( "@SuppressWarnings({\"rawtypes\"})\n" + "@java.lang.Override\n" "protected com.google.protobuf.MapField internalGetMapField(\n" " int number) {\n" " switch (number) {\n"); @@ -865,6 +869,7 @@ GenerateDescriptorMethods(io::Printer* printer) { "}\n"); } printer->Print( + "@java.lang.Override\n" "protected com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n" " internalGetFieldAccessorTable() {\n" " return $fileclass$.internal_$identifier$_fieldAccessorTable\n" @@ -888,6 +893,7 @@ void ImmutableMessageGenerator::GenerateIsInitialized( printer->Print( "private byte memoizedIsInitialized = -1;\n"); printer->Print( + "@java.lang.Override\n" "public final boolean isInitialized() {\n"); printer->Indent(); @@ -1208,7 +1214,7 @@ GenerateExtensionRegistrationCode(io::Printer* printer) { // =================================================================== void ImmutableMessageGenerator:: GenerateParsingConstructor(io::Printer* printer) { - google::protobuf::scoped_array<const FieldDescriptor * > sorted_fields( + std::unique_ptr<const FieldDescriptor * []> sorted_fields( SortFieldsByNumber(descriptor_)); printer->Print( @@ -1357,6 +1363,7 @@ void ImmutableMessageGenerator::GenerateParser(io::Printer* printer) { "classname", descriptor_->name()); printer->Indent(); printer->Print( + "@java.lang.Override\n" "public $classname$ parsePartialFrom(\n" " com.google.protobuf.CodedInputStream input,\n" " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" diff --git a/src/google/protobuf/compiler/java/java_message_builder.cc b/src/google/protobuf/compiler/java/java_message_builder.cc index f9bbfbf4..4c67e806 100644 --- a/src/google/protobuf/compiler/java/java_message_builder.cc +++ b/src/google/protobuf/compiler/java/java_message_builder.cc @@ -38,9 +38,6 @@ #include <google/protobuf/stubs/hash.h> #include <map> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <vector> #include <google/protobuf/compiler/java/java_context.h> @@ -50,9 +47,9 @@ #include <google/protobuf/compiler/java/java_generator_factory.h> #include <google/protobuf/compiler/java/java_helpers.h> #include <google/protobuf/compiler/java/java_name_resolver.h> +#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/printer.h> -#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/substitute.h> #include <google/protobuf/stubs/strutil.h> @@ -180,11 +177,13 @@ Generate(io::Printer* printer) { // to subclass a different GeneratedMessage class (e.g., in v3.0.0 release // we changed all generated code to subclass GeneratedMessageV3). printer->Print( + "@java.lang.Override\n" "public final Builder setUnknownFields(\n" " final com.google.protobuf.UnknownFieldSet unknownFields) {\n" " return super.setUnknownFields$suffix$(unknownFields);\n" "}\n" "\n" + "@java.lang.Override\n" "public final Builder mergeUnknownFields(\n" " final com.google.protobuf.UnknownFieldSet unknownFields) {\n" " return super.mergeUnknownFields(unknownFields);\n" @@ -277,6 +276,7 @@ GenerateDescriptorMethods(io::Printer* printer) { "}\n"); } printer->Print( + "@java.lang.Override\n" "protected com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n" " internalGetFieldAccessorTable() {\n" " return $fileclass$.internal_$identifier$_fieldAccessorTable\n" @@ -333,6 +333,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) { "}\n"); printer->Print( + "@java.lang.Override\n" "public Builder clear() {\n" " super.clear();\n"); @@ -361,6 +362,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) { "\n"); printer->Print( + "@java.lang.Override\n" "public com.google.protobuf.Descriptors.Descriptor\n" " getDescriptorForType() {\n" " return $fileclass$.internal_$identifier$_descriptor;\n" @@ -371,6 +373,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) { // LITE runtime implements this in GeneratedMessageLite. printer->Print( + "@java.lang.Override\n" "public $classname$ getDefaultInstanceForType() {\n" " return $classname$.getDefaultInstance();\n" "}\n" @@ -378,6 +381,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) { "classname", name_resolver_->GetImmutableClassName(descriptor_)); printer->Print( + "@java.lang.Override\n" "public $classname$ build() {\n" " $classname$ result = buildPartial();\n" " if (!result.isInitialized()) {\n" @@ -389,6 +393,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) { "classname", name_resolver_->GetImmutableClassName(descriptor_)); printer->Print( + "@java.lang.Override\n" "public $classname$ buildPartial() {\n" " $classname$ result = new $classname$(this);\n", "classname", name_resolver_->GetImmutableClassName(descriptor_)); @@ -457,27 +462,33 @@ GenerateCommonBuilderMethods(io::Printer* printer) { // to subclass a different GeneratedMessage class (e.g., in v3.0.0 release // we changed all generated code to subclass GeneratedMessageV3). printer->Print( + "@java.lang.Override\n" "public Builder clone() {\n" " return (Builder) super.clone();\n" "}\n" + "@java.lang.Override\n" "public Builder setField(\n" " com.google.protobuf.Descriptors.FieldDescriptor field,\n" " java.lang.Object value) {\n" " return (Builder) super.setField(field, value);\n" "}\n" + "@java.lang.Override\n" "public Builder clearField(\n" " com.google.protobuf.Descriptors.FieldDescriptor field) {\n" " return (Builder) super.clearField(field);\n" "}\n" + "@java.lang.Override\n" "public Builder clearOneof(\n" " com.google.protobuf.Descriptors.OneofDescriptor oneof) {\n" " return (Builder) super.clearOneof(oneof);\n" "}\n" + "@java.lang.Override\n" "public Builder setRepeatedField(\n" " com.google.protobuf.Descriptors.FieldDescriptor field,\n" " int index, java.lang.Object value) {\n" " return (Builder) super.setRepeatedField(field, index, value);\n" "}\n" + "@java.lang.Override\n" "public Builder addRepeatedField(\n" " com.google.protobuf.Descriptors.FieldDescriptor field,\n" " java.lang.Object value) {\n" @@ -486,24 +497,28 @@ GenerateCommonBuilderMethods(io::Printer* printer) { if (descriptor_->extension_range_count() > 0) { printer->Print( + "@java.lang.Override\n" "public <Type> Builder setExtension(\n" " com.google.protobuf.GeneratedMessage.GeneratedExtension<\n" " $classname$, Type> extension,\n" " Type value) {\n" " return (Builder) super.setExtension(extension, value);\n" "}\n" + "@java.lang.Override\n" "public <Type> Builder setExtension(\n" " com.google.protobuf.GeneratedMessage.GeneratedExtension<\n" " $classname$, java.util.List<Type>> extension,\n" " int index, Type value) {\n" " return (Builder) super.setExtension(extension, index, value);\n" "}\n" + "@java.lang.Override\n" "public <Type> Builder addExtension(\n" " com.google.protobuf.GeneratedMessage.GeneratedExtension<\n" " $classname$, java.util.List<Type>> extension,\n" " Type value) {\n" " return (Builder) super.addExtension(extension, value);\n" "}\n" + "@java.lang.Override\n" "public <Type> Builder clearExtension(\n" " com.google.protobuf.GeneratedMessage.GeneratedExtension<\n" " $classname$, ?> extension) {\n" @@ -516,6 +531,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) { if (context_->HasGeneratedMethods(descriptor_)) { printer->Print( + "@java.lang.Override\n" "public Builder mergeFrom(com.google.protobuf.Message other) {\n" " if (other instanceof $classname$) {\n" " return mergeFrom(($classname$)other);\n" @@ -602,6 +618,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) { void MessageBuilderGenerator:: GenerateBuilderParsingMethods(io::Printer* printer) { printer->Print( + "@java.lang.Override\n" "public Builder mergeFrom(\n" " com.google.protobuf.CodedInputStream input,\n" " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" @@ -627,6 +644,7 @@ GenerateBuilderParsingMethods(io::Printer* printer) { void MessageBuilderGenerator::GenerateIsInitialized( io::Printer* printer) { printer->Print( + "@java.lang.Override\n" "public final boolean isInitialized() {\n"); printer->Indent(); diff --git a/src/google/protobuf/compiler/java/java_message_builder_lite.cc b/src/google/protobuf/compiler/java/java_message_builder_lite.cc index 1ad58c09..f04d394e 100644 --- a/src/google/protobuf/compiler/java/java_message_builder_lite.cc +++ b/src/google/protobuf/compiler/java/java_message_builder_lite.cc @@ -38,9 +38,6 @@ #include <google/protobuf/stubs/hash.h> #include <map> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <vector> #include <google/protobuf/compiler/java/java_context.h> @@ -50,12 +47,12 @@ #include <google/protobuf/compiler/java/java_generator_factory.h> #include <google/protobuf/compiler/java/java_helpers.h> #include <google/protobuf/compiler/java/java_name_resolver.h> +#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/printer.h> -#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/wire_format.h> -#include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/substitute.h> +#include <google/protobuf/stubs/strutil.h> namespace google { namespace protobuf { @@ -109,6 +106,7 @@ Generate(io::Printer* printer) { // oneofCase() and clearOneof() printer->Print(vars, + "@java.lang.Override\n" "public $oneof_capitalized_name$Case\n" " get$oneof_capitalized_name$Case() {\n" " return instance.get$oneof_capitalized_name$Case();\n" diff --git a/src/google/protobuf/compiler/java/java_message_field.cc b/src/google/protobuf/compiler/java/java_message_field.cc index baa7f872..bda4fcc0 100644 --- a/src/google/protobuf/compiler/java/java_message_field.cc +++ b/src/google/protobuf/compiler/java/java_message_field.cc @@ -255,7 +255,7 @@ GenerateBuilderMembers(io::Printer* printer) const { bool support_field_presence = SupportFieldPresence(descriptor_->file()); printer->Print(variables_, - "private $type$ $name$_ = null;\n"); + "private $type$ $name$_;\n"); printer->Print(variables_, // If this builder is non-null, it is used and the other fields are @@ -444,15 +444,20 @@ void ImmutableMessageFieldGenerator:: GenerateBuildingCode(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { printer->Print(variables_, - "if ($get_has_field_bit_from_local$) {\n" - " $set_has_field_bit_to_local$;\n" - "}\n"); + "if ($get_has_field_bit_from_local$) {\n"); + printer->Indent(); + PrintNestedBuilderCondition(printer, + "result.$name$_ = $name$_;\n", + "result.$name$_ = $name$Builder_.build();\n"); + printer->Outdent(); + printer->Print(variables_, + " $set_has_field_bit_to_local$;\n" + "}\n"); + } else { + PrintNestedBuilderCondition(printer, + "result.$name$_ = $name$_;\n", + "result.$name$_ = $name$Builder_.build();\n"); } - - PrintNestedBuilderCondition(printer, - "result.$name$_ = $name$_;\n", - - "result.$name$_ = $name$Builder_.build();\n"); } void ImmutableMessageFieldGenerator:: diff --git a/src/google/protobuf/compiler/java/java_message_field_lite.cc b/src/google/protobuf/compiler/java/java_message_field_lite.cc index df3e80d4..9cf6f363 100644 --- a/src/google/protobuf/compiler/java/java_message_field_lite.cc +++ b/src/google/protobuf/compiler/java/java_message_field_lite.cc @@ -147,12 +147,14 @@ GenerateMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return $get_has_field_bit_message$;\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" "}\n"); @@ -160,12 +162,14 @@ GenerateMembers(io::Printer* printer) const { } else { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return $name$_ != null;\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" "}\n"); @@ -195,7 +199,11 @@ GenerateMembers(io::Printer* printer) const { // Field.Builder mergeField(Field value) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.SuppressWarnings({\"ReferenceEquality\"})\n" "private void merge$capitalized_name$($type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" " if ($name$_ != null &&\n" " $name$_ != $type$.getDefaultInstance()) {\n" " $name$_ =\n" @@ -223,6 +231,7 @@ GenerateBuilderMembers(io::Printer* printer) const { // boolean hasField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return instance.has$capitalized_name$();\n" "}\n"); @@ -231,6 +240,7 @@ GenerateBuilderMembers(io::Printer* printer) const { // Field getField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " return instance.get$capitalized_name$();\n" "}\n"); @@ -396,12 +406,14 @@ GenerateMembers(io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return $has_oneof_case_message$;\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " if ($has_oneof_case_message$) {\n" " return ($type$) $oneof_name$_;\n" @@ -434,6 +446,9 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "private void merge$capitalized_name$($type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" " if ($has_oneof_case_message$ &&\n" " $oneof_name$_ != $type$.getDefaultInstance()) {\n" " $oneof_name$_ = $type$.newBuilder(($type$) $oneof_name$_)\n" @@ -464,6 +479,7 @@ GenerateBuilderMembers(io::Printer* printer) const { // boolean hasField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return instance.has$capitalized_name$();\n" "}\n"); @@ -472,6 +488,7 @@ GenerateBuilderMembers(io::Printer* printer) const { // Field getField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " return instance.get$capitalized_name$();\n" "}\n"); @@ -624,6 +641,7 @@ GenerateMembers(io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List<$type$> " "${$get$capitalized_name$List$}$() {\n" " return $name$_;\n" // note: unmodifiable list @@ -638,12 +656,14 @@ GenerateMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" " return $name$_.size();\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" " return $name$_.get(index);\n" "}\n"); @@ -761,6 +781,7 @@ GenerateBuilderMembers(io::Printer* printer) const { // List<Field> getRepeatedFieldList() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List<$type$> " "${$get$capitalized_name$List$}$() {\n" " return java.util.Collections.unmodifiableList(\n" @@ -771,6 +792,7 @@ GenerateBuilderMembers(io::Printer* printer) const { // int getRepeatedFieldCount() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" " return instance.get$capitalized_name$Count();\n" "}"); @@ -779,6 +801,7 @@ GenerateBuilderMembers(io::Printer* printer) const { // Field getRepeatedField(int index) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" " return instance.get$capitalized_name$(index);\n" "}\n"); diff --git a/src/google/protobuf/compiler/java/java_message_lite.cc b/src/google/protobuf/compiler/java/java_message_lite.cc index 108504c7..3a512e8d 100644 --- a/src/google/protobuf/compiler/java/java_message_lite.cc +++ b/src/google/protobuf/compiler/java/java_message_lite.cc @@ -38,9 +38,6 @@ #include <google/protobuf/stubs/hash.h> #include <map> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <vector> #include <google/protobuf/compiler/java/java_context.h> @@ -52,9 +49,9 @@ #include <google/protobuf/compiler/java/java_message_builder.h> #include <google/protobuf/compiler/java/java_message_builder_lite.h> #include <google/protobuf/compiler/java/java_name_resolver.h> +#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/printer.h> -#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/substitute.h> #include <google/protobuf/stubs/strutil.h> @@ -310,6 +307,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { " default: return null;\n" " }\n" "}\n" + "@java.lang.Override\n" "public int getNumber() {\n" " return this.value;\n" "}\n", @@ -318,6 +316,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { printer->Print("};\n\n"); // oneofCase() printer->Print(vars, + "@java.lang.Override\n" "public $oneof_capitalized_name$Case\n" "get$oneof_capitalized_name$Case() {\n" " return $oneof_capitalized_name$Case.forNumber(\n" @@ -356,6 +355,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { } printer->Print( + "@java.lang.Override\n" "@java.lang.SuppressWarnings({\"unchecked\", \"fallthrough\"})\n" "protected final java.lang.Object dynamicMethod(\n" " com.google.protobuf.GeneratedMessageLite.MethodToInvoke method,\n" @@ -369,22 +369,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { printer->Indent(); printer->Indent(); - printer->Print("case IS_INITIALIZED: {\n"); - printer->Indent(); - GenerateDynamicMethodIsInitialized(printer); - printer->Outdent(); - - printer->Print("}\n"); - printer->Print( - "case MAKE_IMMUTABLE: {\n"); - - printer->Indent(); - GenerateDynamicMethodMakeImmutable(printer); - printer->Outdent(); - - printer->Print( - "}\n" "case NEW_BUILDER: {\n"); printer->Indent(); @@ -393,21 +378,38 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { if (!EnableExperimentalRuntimeForLite()) { printer->Print( + "}\n" + "case IS_INITIALIZED: {\n"); + printer->Indent(); + GenerateDynamicMethodIsInitialized(printer); + printer->Outdent(); + + printer->Print("}\n"); + + printer->Print( + "case MAKE_IMMUTABLE: {\n"); + + printer->Indent(); + GenerateDynamicMethodMakeImmutable(printer); + printer->Outdent(); + + printer->Print( "}\n" "case VISIT: {\n"); printer->Indent(); GenerateDynamicMethodVisit(printer); printer->Outdent(); - } - printer->Print( - "}\n" - "case MERGE_FROM_STREAM: {\n"); + printer->Print( + "}\n" + "case MERGE_FROM_STREAM: {\n"); + + printer->Indent(); + GenerateDynamicMethodMergeFromStream(printer); + printer->Outdent(); + } - printer->Indent(); - GenerateDynamicMethodMergeFromStream(printer); - printer->Outdent(); printer->Print( "}\n" @@ -420,14 +422,20 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { // manipulating static fields but that has exceptional cost on Android as // it will generate an extra class for every message. Instead, use the // double-check locking pattern which works just as well. - " if (PARSER == null) {" + // + // The "parser" temporary mirrors the "PARSER" field to eliminate a read + // at the final return statement. + " com.google.protobuf.Parser<$classname$> parser = PARSER;\n" + " if (parser == null) {\n" " synchronized ($classname$.class) {\n" - " if (PARSER == null) {\n" - " PARSER = new DefaultInstanceBasedParser(DEFAULT_INSTANCE);\n" + " parser = PARSER;\n" + " if (parser == null) {\n" + " parser = new DefaultInstanceBasedParser(DEFAULT_INSTANCE);\n" + " PARSER = parser;\n" " }\n" " }\n" " }\n" - " return PARSER;\n", + " return parser;\n", "classname", name_resolver_->GetImmutableClassName(descriptor_)); printer->Outdent(); @@ -475,8 +483,9 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { printer->Print( "static {\n" + " // New instances are implicitly immutable so no need to make\n" + " // immutable.\n" " DEFAULT_INSTANCE = new $classname$();\n" - " DEFAULT_INSTANCE.makeImmutable();\n" "}\n" "\n", "classname", descriptor_->name()); @@ -491,6 +500,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { "}\n", "classname", descriptor_->name()); } + printer->Print( "public static $classname$ getDefaultInstance() {\n" " return DEFAULT_INSTANCE;\n" @@ -519,6 +529,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { .Generate(printer); } + printer->Outdent(); printer->Print("}\n\n"); } @@ -528,7 +539,11 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { void ImmutableMessageLiteGenerator:: GenerateMessageSerializationMethods(io::Printer* printer) { - google::protobuf::scoped_array<const FieldDescriptor * > sorted_fields( + if (EnableExperimentalRuntimeForLite()) { + return; + } + + std::unique_ptr<const FieldDescriptor * []> sorted_fields( SortFieldsByNumber(descriptor_)); std::vector<const Descriptor::ExtensionRange*> sorted_extensions; @@ -539,6 +554,7 @@ GenerateMessageSerializationMethods(io::Printer* printer) { ExtensionRangeOrdering()); printer->Print( + "@java.lang.Override\n" "public void writeTo(com.google.protobuf.CodedOutputStream output)\n" " throws java.io.IOException {\n"); printer->Indent(); @@ -594,6 +610,7 @@ GenerateMessageSerializationMethods(io::Printer* printer) { printer->Print( "}\n" "\n" + "@java.lang.Override\n" "public int getSerializedSize() {\n" " int size = memoizedSerializedSize;\n" " if (size != -1) return size;\n" @@ -1005,7 +1022,7 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodMergeFromStream( " done = true;\n" " break;\n"); - google::protobuf::scoped_array<const FieldDescriptor* > sorted_fields( + std::unique_ptr<const FieldDescriptor* []> sorted_fields( SortFieldsByNumber(descriptor_)); for (int i = 0; i < descriptor_->field_count(); i++) { const FieldDescriptor* field = sorted_fields[i]; diff --git a/src/google/protobuf/compiler/java/java_plugin_unittest.cc b/src/google/protobuf/compiler/java/java_plugin_unittest.cc index 3e4910c8..87f687da 100644 --- a/src/google/protobuf/compiler/java/java_plugin_unittest.cc +++ b/src/google/protobuf/compiler/java/java_plugin_unittest.cc @@ -35,9 +35,6 @@ // worth. #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/compiler/java/java_generator.h> #include <google/protobuf/compiler/command_line_interface.h> @@ -76,7 +73,7 @@ class TestGenerator : public CodeGenerator { void TryInsert(const string& filename, const string& insertion_point, GeneratorContext* context) const { - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( context->OpenForInsert(filename, insertion_point)); io::Printer printer(output.get(), '$'); printer.Print("// inserted $name$\n", "name", insertion_point); diff --git a/src/google/protobuf/compiler/java/java_primitive_field.cc b/src/google/protobuf/compiler/java/java_primitive_field.cc index 074a6be8..e6ce69c7 100644 --- a/src/google/protobuf/compiler/java/java_primitive_field.cc +++ b/src/google/protobuf/compiler/java/java_primitive_field.cc @@ -264,7 +264,9 @@ GenerateFieldBuilderInitializationCode(io::Printer* printer) const { void ImmutablePrimitiveFieldGenerator:: GenerateInitializationCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $default$;\n"); + if (!IsDefaultValueJavaDefault(descriptor_)) { + printer->Print(variables_, "$name$_ = $default$;\n"); + } } void ImmutablePrimitiveFieldGenerator:: @@ -294,11 +296,21 @@ GenerateBuildingCode(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { printer->Print(variables_, "if ($get_has_field_bit_from_local$) {\n" - " $set_has_field_bit_to_local$;\n" - "}\n"); + " result.$name$_ = $name$_;\n" + " $set_has_field_bit_to_local$;\n"); + if (IsDefaultValueJavaDefault(descriptor_)) { + printer->Print(variables_, + "}\n"); + } else { + printer->Print(variables_, + "} else {\n" + " result.$name$_ = $default$;\n" + "}\n"); + } + } else { + printer->Print(variables_, + "result.$name$_ = $name$_;\n"); } - printer->Print(variables_, - "result.$name$_ = $name$_;\n"); } void ImmutablePrimitiveFieldGenerator:: @@ -633,8 +645,7 @@ GenerateMembers(io::Printer* printer) const { "}\n"); printer->Annotate("{", "}", descriptor_); - if (descriptor_->is_packed() && - context_->HasGeneratedMethods(descriptor_->containing_type())) { + if (descriptor_->is_packed()) { printer->Print(variables_, "private int $name$MemoizedSerializedSize = -1;\n"); } diff --git a/src/google/protobuf/compiler/java/java_primitive_field_lite.cc b/src/google/protobuf/compiler/java/java_primitive_field_lite.cc index f9293171..d2ebc567 100644 --- a/src/google/protobuf/compiler/java/java_primitive_field_lite.cc +++ b/src/google/protobuf/compiler/java/java_primitive_field_lite.cc @@ -222,6 +222,7 @@ GenerateMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return $get_has_field_bit_message$;\n" "}\n"); @@ -230,6 +231,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " return $name$_;\n" "}\n"); @@ -266,6 +268,7 @@ GenerateBuilderMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return instance.has$capitalized_name$();\n" "}\n"); @@ -274,6 +277,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " return instance.get$capitalized_name$();\n" "}\n"); @@ -488,6 +492,7 @@ GenerateMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return $has_oneof_case_message$;\n" "}\n"); @@ -496,6 +501,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " if ($has_oneof_case_message$) {\n" " return ($boxed_type$) $oneof_name$_;\n" @@ -528,6 +534,7 @@ GenerateBuilderMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return instance.has$capitalized_name$();\n" "}\n"); @@ -536,6 +543,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " return instance.get$capitalized_name$();\n" "}\n"); @@ -645,6 +653,7 @@ GenerateMembers(io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List<$boxed_type$>\n" " ${$get$capitalized_name$List$}$() {\n" " return $name$_;\n" // note: unmodifiable list @@ -652,12 +661,14 @@ GenerateMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" " return $name$_.size();\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" " return $repeated_get$(index);\n" "}\n"); @@ -711,6 +722,7 @@ void RepeatedImmutablePrimitiveFieldLiteGenerator:: GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List<$boxed_type$>\n" " ${$get$capitalized_name$List$}$() {\n" " return java.util.Collections.unmodifiableList(\n" @@ -719,12 +731,14 @@ GenerateBuilderMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" " return instance.get$capitalized_name$Count();\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" " return instance.get$capitalized_name$(index);\n" "}\n"); diff --git a/src/google/protobuf/compiler/java/java_shared_code_generator.cc b/src/google/protobuf/compiler/java/java_shared_code_generator.cc index 9a42aba9..0cec20b9 100644 --- a/src/google/protobuf/compiler/java/java_shared_code_generator.cc +++ b/src/google/protobuf/compiler/java/java_shared_code_generator.cc @@ -33,16 +33,13 @@ #include <google/protobuf/compiler/java/java_shared_code_generator.h> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/compiler/java/java_helpers.h> #include <google/protobuf/compiler/java/java_name_resolver.h> #include <google/protobuf/compiler/code_generator.h> +#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/io/zero_copy_stream.h> -#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/stubs/strutil.h> @@ -69,11 +66,11 @@ void SharedCodeGenerator::Generate(GeneratorContext* context, string classname = name_resolver_->GetDescriptorClassName(file_); string filename = package_dir + classname + ".java"; file_list->push_back(filename); - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename)); + std::unique_ptr<io::ZeroCopyOutputStream> output(context->Open(filename)); GeneratedCodeInfo annotations; io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector( &annotations); - google::protobuf::scoped_ptr<io::Printer> printer( + std::unique_ptr<io::Printer> printer( new io::Printer(output.get(), '$', options_.annotate_code ? &annotation_collector : NULL)); string info_relative_path = classname + ".java.pb.meta"; @@ -108,7 +105,7 @@ void SharedCodeGenerator::Generate(GeneratorContext* context, "}\n"); if (options_.annotate_code) { - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output( + std::unique_ptr<io::ZeroCopyOutputStream> info_output( context->Open(info_full_path)); annotations.SerializeToZeroCopyStream(info_output.get()); annotation_file_list->push_back(info_full_path); diff --git a/src/google/protobuf/compiler/java/java_shared_code_generator.h b/src/google/protobuf/compiler/java/java_shared_code_generator.h index 40502270..58a31f5d 100644 --- a/src/google/protobuf/compiler/java/java_shared_code_generator.h +++ b/src/google/protobuf/compiler/java/java_shared_code_generator.h @@ -36,9 +36,6 @@ #define GOOGLE_PROTOBUF_COMPILER_JAVA_SHARED_CODE_GENERATOR_H__ #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <string> #include <vector> @@ -77,7 +74,7 @@ class SharedCodeGenerator { void GenerateDescriptors(io::Printer* printer); private: - google::protobuf::scoped_ptr<ClassNameResolver> name_resolver_; + std::unique_ptr<ClassNameResolver> name_resolver_; const FileDescriptor* file_; const Options options_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SharedCodeGenerator); diff --git a/src/google/protobuf/compiler/java/java_string_field.cc b/src/google/protobuf/compiler/java/java_string_field.cc index 2b6e9381..b08febc0 100644 --- a/src/google/protobuf/compiler/java/java_string_field.cc +++ b/src/google/protobuf/compiler/java/java_string_field.cc @@ -405,11 +405,15 @@ GenerateBuildingCode(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { printer->Print(variables_, "if ($get_has_field_bit_from_local$) {\n" + " result.$name$_ = $name$_;\n" " $set_has_field_bit_to_local$;\n" + "} else {\n" + " result.$name$_ = $default$;\n" "}\n"); + } else { + printer->Print(variables_, + "result.$name$_ = $name$_;\n"); } - printer->Print(variables_, - "result.$name$_ = $name$_;\n"); } void ImmutableStringFieldGenerator:: diff --git a/src/google/protobuf/compiler/java/java_string_field_lite.cc b/src/google/protobuf/compiler/java/java_string_field_lite.cc index adda307c..a238c67d 100644 --- a/src/google/protobuf/compiler/java/java_string_field_lite.cc +++ b/src/google/protobuf/compiler/java/java_string_field_lite.cc @@ -192,6 +192,7 @@ GenerateMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return $get_has_field_bit_message$;\n" "}\n"); @@ -200,12 +201,14 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" " return $name$_;\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public com.google.protobuf.ByteString\n" " ${$get$capitalized_name$Bytes$}$() {\n" " return com.google.protobuf.ByteString.copyFromUtf8($name$_);\n" @@ -249,6 +252,7 @@ GenerateBuilderMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return instance.has$capitalized_name$();\n" "}\n"); @@ -257,6 +261,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" " return instance.get$capitalized_name$();\n" "}\n"); @@ -264,6 +269,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public com.google.protobuf.ByteString\n" " ${$get$capitalized_name$Bytes$}$() {\n" " return instance.get$capitalized_name$Bytes();\n" @@ -419,6 +425,7 @@ GenerateMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return $has_oneof_case_message$;\n" "}\n"); @@ -427,6 +434,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" " java.lang.String ref $default_init$;\n" " if ($has_oneof_case_message$) {\n" @@ -438,6 +446,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public com.google.protobuf.ByteString\n" " ${$get$capitalized_name$Bytes$}$() {\n" " java.lang.String ref $default_init$;\n" @@ -489,6 +498,7 @@ GenerateBuilderMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return instance.has$capitalized_name$();\n" "}\n"); @@ -497,6 +507,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" " return instance.get$capitalized_name$();\n" "}\n"); @@ -504,6 +515,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public com.google.protobuf.ByteString\n" " ${$get$capitalized_name$Bytes$}$() {\n" " return instance.get$capitalized_name$Bytes();\n" @@ -641,6 +653,7 @@ GenerateMembers(io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List<java.lang.String> " "${$get$capitalized_name$List$}$() {\n" " return $name$_;\n" // note: unmodifiable list @@ -648,12 +661,14 @@ GenerateMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" " return $name$_.size();\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.lang.String " "${$get$capitalized_name$$}$(int index) {\n" " return $name$_.get(index);\n" @@ -661,6 +676,7 @@ GenerateMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public com.google.protobuf.ByteString\n" " ${$get$capitalized_name$Bytes$}$(int index) {\n" " return com.google.protobuf.ByteString.copyFromUtf8(\n" @@ -725,6 +741,7 @@ void RepeatedImmutableStringFieldLiteGenerator:: GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List<java.lang.String>\n" " ${$get$capitalized_name$List$}$() {\n" " return java.util.Collections.unmodifiableList(\n" @@ -733,12 +750,14 @@ GenerateBuilderMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" " return instance.get$capitalized_name$Count();\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.lang.String " "${$get$capitalized_name$$}$(int index) {\n" " return instance.get$capitalized_name$(index);\n" @@ -746,6 +765,7 @@ GenerateBuilderMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public com.google.protobuf.ByteString\n" " ${$get$capitalized_name$Bytes$}$(int index) {\n" " return instance.get$capitalized_name$Bytes(index);\n" diff --git a/src/google/protobuf/compiler/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 10dd3648..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. - vector<const EnumValueDescriptor*> canonical_values_; - - struct Alias { - const EnumValueDescriptor* value; - const EnumValueDescriptor* canonical_value; - }; - 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 26bc7f85..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, 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 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 1be25d10..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_; - 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_; - 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_; - 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 e31d1177..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 scoped_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 347c888c..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_; - scoped_array<scoped_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 17f7386e..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; - - 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, - vector<string>* file_list, - const Params& params) { - string filename = package_dir + descriptor->name() + ".java"; - file_list->push_back(filename); - - scoped_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, - 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 217eafe2..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, - 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 7c3a0421..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 { - vector<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") { - 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") { - 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 += "/"; - - 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. - scoped_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. - scoped_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 78421887..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; - } - - scoped_array<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) { - scoped_array<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/js/embed.cc b/src/google/protobuf/compiler/js/embed.cc deleted file mode 100644 index a725b62e..00000000 --- a/src/google/protobuf/compiler/js/embed.cc +++ /dev/null @@ -1,112 +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. - -#include <cassert> -#include <cstdlib> -#include <fstream> -#include <iostream> -#include <string> - -const char output_file[] = "well_known_types_embed.cc"; - -static bool AsciiIsPrint(unsigned char c) { - return c >= 32 && c < 127; -} - -static char ToDecimalDigit(int num) { - assert(num < 10); - return '0' + num; -} - -static std::string CEscape(const std::string& str) { - std::string dest; - - for (size_t i = 0; i < str.size(); ++i) { - unsigned char ch = str[i]; - switch (ch) { - case '\n': dest += "\\n"; break; - case '\r': dest += "\\r"; break; - case '\t': dest += "\\t"; break; - case '\"': dest += "\\\""; break; - case '\\': dest += "\\\\"; break; - default: - if (AsciiIsPrint(ch)) { - dest += ch; - } else { - dest += "\\"; - dest += ToDecimalDigit(ch / 64); - dest += ToDecimalDigit((ch % 64) / 8); - dest += ToDecimalDigit(ch % 8); - } - break; - } - } - - return dest; -} - -static void AddFile(const char* name, std::basic_ostream<char>* out) { - std::ifstream in(name); - - if (!in.is_open()) { - std::cerr << "Couldn't open input file: " << name << "\n"; - std::exit(EXIT_FAILURE); - } - - // Make canonical name only include the final element. - for (const char *p = name; *p; p++) { - if (*p == '/') { - name = p + 1; - } - } - - *out << "{\"" << CEscape(name) << "\",\n"; - - for (std::string line; std::getline(in, line); ) { - *out << " \"" << CEscape(line) << "\\n\"\n"; - } - - *out << "},\n"; -} - -int main(int argc, char *argv[]) { - std::cout << "#include " - "\"google/protobuf/compiler/js/well_known_types_embed.h\"\n"; - std::cout << "struct FileToc well_known_types_js[] = {\n"; - - for (int i = 1; i < argc; i++) { - AddFile(argv[i], &std::cout); - } - - std::cout << " {NULL, NULL} // Terminate the list.\n"; - std::cout << "};\n"; - - return EXIT_SUCCESS; -} diff --git a/src/google/protobuf/compiler/js/js_generator.cc b/src/google/protobuf/compiler/js/js_generator.cc index fd2d3dfd..7109ed5b 100755 --- a/src/google/protobuf/compiler/js/js_generator.cc +++ b/src/google/protobuf/compiler/js/js_generator.cc @@ -35,9 +35,6 @@ #include <limits> #include <map> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <string> #include <utility> #include <vector> @@ -52,6 +49,7 @@ #include <google/protobuf/descriptor.h> #include <google/protobuf/stubs/strutil.h> + namespace google { namespace protobuf { namespace compiler { @@ -2062,6 +2060,7 @@ void Generator::GenerateOneofCaseDefinition( " $upcase$: $number$", "upcase", ToEnumCase(oneof->field(i)->name()), "number", JSFieldIndex(oneof->field(i))); + printer->Annotate("upcase", oneof->field(i)); } printer->Print( @@ -2768,28 +2767,33 @@ void Generator::GenerateClassField(const GeneratorOptions& options, void Generator::GenerateRepeatedPrimitiveHelperMethods( const GeneratorOptions& options, io::Printer* printer, const FieldDescriptor* field, bool untyped) const { + // clang-format off printer->Print( "/**\n" " * @param {!$optionaltype$} value\n" - " * @param {number=} opt_index\n" + " * @param {number=} opt_index$returndoc$\n" " */\n" "$class$.prototype.$addername$ = function(value, opt_index) {\n" " jspb.Message.addToRepeatedField(this, $index$", "class", GetMessagePath(options, field->containing_type()), "addername", "add" + JSGetterName(options, field, BYTES_DEFAULT, /* drop_list = */ true), - "optionaltype", JSTypeName(options, field, BYTES_DEFAULT), "index", - JSFieldIndex(field)); + "optionaltype", JSTypeName(options, field, BYTES_DEFAULT), + "index", JSFieldIndex(field), + "returndoc", JSReturnDoc(options, field)); printer->Annotate("addername", field); printer->Print( - "$oneofgroup$, $type$value$rptvalueinit$$typeclose$, opt_index);\n" + "$oneofgroup$, $type$value$rptvalueinit$$typeclose$, " + "opt_index);$returnvalue$\n" "};\n" "\n" "\n", "type", untyped ? "/** @type{string|number|boolean|!Uint8Array} */(" : "", "typeclose", untyped ? ")" : "", "oneofgroup", (field->containing_oneof() ? (", " + JSOneofArray(options, field)) : ""), - "rptvalueinit", ""); + "rptvalueinit", "", + "returnvalue", JSReturnClause(field)); + // clang-format on } void Generator::GenerateRepeatedMessageHelperMethods( @@ -3206,21 +3210,24 @@ void Generator::GenerateExtension(const GeneratorOptions& options, ? GetMessagePath(options, field->extension_scope()) : GetFilePath(options, field->file())); + const string extension_object_name = JSObjectFieldName(options, field); printer->Print( "\n" "/**\n" " * A tuple of {field number, class constructor} for the extension\n" - " * field named `$name$`.\n" + " * field named `$nameInComment$`.\n" " * @type {!jspb.ExtensionFieldInfo<$extensionType$>}\n" " */\n" "$class$.$name$ = new jspb.ExtensionFieldInfo(\n", - "name", JSObjectFieldName(options, field), + "nameInComment", extension_object_name, + "name", extension_object_name, "class", extension_scope, "extensionType", JSFieldTypeAnnotation( options, field, /* is_setter_argument = */ false, /* force_present = */ true, /* singular_if_not_packed = */ false)); + printer->Annotate("name", field); printer->Print( " $index$,\n" " {$name$: 0},\n" @@ -3230,7 +3237,7 @@ void Generator::GenerateExtension(const GeneratorOptions& options, " $toObject$),\n" " $repeated$);\n", "index", SimpleItoa(field->number()), - "name", JSObjectFieldName(options, field), + "name", extension_object_name, "ctor", (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ? SubmessageTypeRef(options, field) : string("null")), "toObject", (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ? @@ -3249,7 +3256,7 @@ void Generator::GenerateExtension(const GeneratorOptions& options, "extendName", JSExtensionsObjectName(options, field->file(), field->containing_type()), "index", SimpleItoa(field->number()), "class", extension_scope, "name", - JSObjectFieldName(options, field), "binaryReaderFn", + extension_object_name, "binaryReaderFn", JSBinaryReaderMethodName(options, field), "binaryWriterFn", JSBinaryWriterMethodName(options, field), "binaryMessageSerializeFn", (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) @@ -3272,7 +3279,7 @@ void Generator::GenerateExtension(const GeneratorOptions& options, field->containing_type()), "index", SimpleItoa(field->number()), "class", extension_scope, - "name", JSObjectFieldName(options, field)); + "name", extension_object_name); } bool GeneratorOptions::ParseFromOptions( @@ -3470,7 +3477,8 @@ void Generator::GenerateFile(const GeneratorOptions& options, GenerateExtension(options, printer, *it); } - if (options.import_style == GeneratorOptions::kImportCommonJs) { + // if provided is empty, do not export anything + if (options.import_style == GeneratorOptions::kImportCommonJs && !provided.empty()) { printer->Print("goog.object.extend(exports, $package$);\n", "package", GetFilePath(options, file)); } @@ -3500,7 +3508,7 @@ bool Generator::GenerateAll(const std::vector<const FileDescriptor*>& files, // All output should go in a single file. string filename = options.output_dir + "/" + options.library + options.GetFileNameExtension(); - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename)); + std::unique_ptr<io::ZeroCopyOutputStream> output(context->Open(filename)); GOOGLE_CHECK(output.get()); io::Printer printer(output.get(), '$'); @@ -3549,7 +3557,7 @@ bool Generator::GenerateAll(const std::vector<const FileDescriptor*>& files, } string filename = GetMessageFileName(options, desc); - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( context->Open(filename)); GOOGLE_CHECK(output.get()); io::Printer printer(output.get(), '$'); @@ -3575,7 +3583,7 @@ bool Generator::GenerateAll(const std::vector<const FileDescriptor*>& files, } string filename = GetEnumFileName(options, enumdesc); - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( context->Open(filename)); GOOGLE_CHECK(output.get()); io::Printer printer(output.get(), '$'); @@ -3598,7 +3606,7 @@ bool Generator::GenerateAll(const std::vector<const FileDescriptor*>& files, if (allowed_set.count(file) == 1) { string filename = GetExtensionFileName(options, file); - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( context->Open(filename)); GOOGLE_CHECK(output.get()); io::Printer printer(output.get(), '$'); @@ -3634,7 +3642,7 @@ bool Generator::GenerateAll(const std::vector<const FileDescriptor*>& files, string filename = options.output_dir + "/" + GetJSFilename(options, file->name()); - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename)); + std::unique_ptr<io::ZeroCopyOutputStream> output(context->Open(filename)); GOOGLE_CHECK(output.get()); GeneratedCodeInfo annotations; io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector( diff --git a/src/google/protobuf/compiler/js/well_known_types_embed.cc b/src/google/protobuf/compiler/js/well_known_types_embed.cc new file mode 100644 index 00000000..e5ee5510 --- /dev/null +++ b/src/google/protobuf/compiler/js/well_known_types_embed.cc @@ -0,0 +1,225 @@ +#include <google/protobuf/compiler/js/well_known_types_embed.h> + +struct FileToc well_known_types_js[] = { + {"any.js", + "/* This code will be inserted into generated code for\n" + " * google/protobuf/any.proto. */\n" + "\n" + "/**\n" + " * Returns the type name contained in this instance, if any.\n" + " * @return {string|undefined}\n" + " */\n" + "proto.google.protobuf.Any.prototype.getTypeName = function() {\n" + " return this.getTypeUrl().split('/').pop();\n" + "};\n" + "\n" + "\n" + "/**\n" + " * Packs the given message instance into this Any.\n" + " * @param {!Uint8Array} serialized The serialized data to pack.\n" + " * @param {string} name The type name of this message object.\n" + " * @param {string=} opt_typeUrlPrefix the type URL prefix.\n" + " */\n" + "proto.google.protobuf.Any.prototype.pack = function(serialized, name,\n" + " opt_typeUrlPrefix) " + "{\n" + " if (!opt_typeUrlPrefix) {\n" + " opt_typeUrlPrefix = 'type.googleapis.com/';\n" + " }\n" + "\n" + " if (opt_typeUrlPrefix.substr(-1) != '/') {\n" + " this.setTypeUrl(opt_typeUrlPrefix + '/' + name);\n" + " } else {\n" + " this.setTypeUrl(opt_typeUrlPrefix + name);\n" + " }\n" + "\n" + " this.setValue(serialized);\n" + "};\n" + "\n" + "\n" + "/**\n" + " * @template T\n" + " * Unpacks this Any into the given message object.\n" + " * @param {function(Uint8Array):T} deserialize Function that will " + "deserialize\n" + " * the binary data properly.\n" + " * @param {string} name The expected type name of this message object.\n" + " * @return {?T} If the name matched the expected name, returns the " + "deserialized\n" + " * object, otherwise returns null.\n" + " */\n" + "proto.google.protobuf.Any.prototype.unpack = function(deserialize, name) " + "{\n" + " if (this.getTypeName() == name) {\n" + " return deserialize(this.getValue_asU8());\n" + " } else {\n" + " return null;\n" + " }\n" + "};\n"}, + {"timestamp.js", + "/* This code will be inserted into generated code for\n" + " * google/protobuf/timestamp.proto. */\n" + "\n" + "/**\n" + " * Returns a JavaScript 'Date' object corresponding to this Timestamp.\n" + " * @return {!Date}\n" + " */\n" + "proto.google.protobuf.Timestamp.prototype.toDate = function() {\n" + " var seconds = this.getSeconds();\n" + " var nanos = this.getNanos();\n" + "\n" + " return new Date((seconds * 1000) + (nanos / 1000000));\n" + "};\n" + "\n" + "\n" + "/**\n" + " * Sets the value of this Timestamp object to be the given Date.\n" + " * @param {!Date} value The value to set.\n" + " */\n" + "proto.google.protobuf.Timestamp.prototype.fromDate = function(value) {\n" + " this.setSeconds(Math.floor(value.getTime() / 1000));\n" + " this.setNanos(value.getMilliseconds() * 1000000);\n" + "};\n"}, + {"struct.js", + "/* This code will be inserted into generated code for\n" + " * google/protobuf/struct.proto. */\n" + "\n" + "/**\n" + " * Typedef representing plain JavaScript values that can go into a\n" + " * Struct.\n" + " * @typedef {null|number|string|boolean|Array|Object}\n" + " */\n" + "proto.google.protobuf.JavaScriptValue;\n" + "\n" + "\n" + "/**\n" + " * Converts this Value object to a plain JavaScript value.\n" + " * @return {?proto.google.protobuf.JavaScriptValue} a plain JavaScript\n" + " * value representing this Struct.\n" + " */\n" + "proto.google.protobuf.Value.prototype.toJavaScript = function() {\n" + " var kindCase = proto.google.protobuf.Value.KindCase;\n" + " switch (this.getKindCase()) {\n" + " case kindCase.NULL_VALUE:\n" + " return null;\n" + " case kindCase.NUMBER_VALUE:\n" + " return this.getNumberValue();\n" + " case kindCase.STRING_VALUE:\n" + " return this.getStringValue();\n" + " case kindCase.BOOL_VALUE:\n" + " return this.getBoolValue();\n" + " case kindCase.STRUCT_VALUE:\n" + " return this.getStructValue().toJavaScript();\n" + " case kindCase.LIST_VALUE:\n" + " return this.getListValue().toJavaScript();\n" + " default:\n" + " throw new Error('Unexpected struct type');\n" + " }\n" + "};\n" + "\n" + "\n" + "/**\n" + " * Converts this JavaScript value to a new Value proto.\n" + " * @param {!proto.google.protobuf.JavaScriptValue} value The value to\n" + " * convert.\n" + " * @return {!proto.google.protobuf.Value} The newly constructed value.\n" + " */\n" + "proto.google.protobuf.Value.fromJavaScript = function(value) {\n" + " var ret = new proto.google.protobuf.Value();\n" + " switch (goog.typeOf(value)) {\n" + " case 'string':\n" + " ret.setStringValue(/** @type {string} */ (value));\n" + " break;\n" + " case 'number':\n" + " ret.setNumberValue(/** @type {number} */ (value));\n" + " break;\n" + " case 'boolean':\n" + " ret.setBoolValue(/** @type {boolean} */ (value));\n" + " break;\n" + " case 'null':\n" + " ret.setNullValue(proto.google.protobuf.NullValue.NULL_VALUE);\n" + " break;\n" + " case 'array':\n" + " ret.setListValue(proto.google.protobuf.ListValue.fromJavaScript(\n" + " /** @type{!Array} */ (value)));\n" + " break;\n" + " case 'object':\n" + " ret.setStructValue(proto.google.protobuf.Struct.fromJavaScript(\n" + " /** @type{!Object} */ (value)));\n" + " break;\n" + " default:\n" + " throw new Error('Unexpected struct type.');\n" + " }\n" + "\n" + " return ret;\n" + "};\n" + "\n" + "\n" + "/**\n" + " * Converts this ListValue object to a plain JavaScript array.\n" + " * @return {!Array} a plain JavaScript array representing this List.\n" + " */\n" + "proto.google.protobuf.ListValue.prototype.toJavaScript = function() {\n" + " var ret = [];\n" + " var values = this.getValuesList();\n" + "\n" + " for (var i = 0; i < values.length; i++) {\n" + " ret[i] = values[i].toJavaScript();\n" + " }\n" + "\n" + " return ret;\n" + "};\n" + "\n" + "\n" + "/**\n" + " * Constructs a ListValue protobuf from this plain JavaScript array.\n" + " * @param {!Array} array a plain JavaScript array\n" + " * @return {proto.google.protobuf.ListValue} a new ListValue object\n" + " */\n" + "proto.google.protobuf.ListValue.fromJavaScript = function(array) {\n" + " var ret = new proto.google.protobuf.ListValue();\n" + "\n" + " for (var i = 0; i < array.length; i++) {\n" + " " + "ret.addValues(proto.google.protobuf.Value.fromJavaScript(array[i]));\n" + " }\n" + "\n" + " return ret;\n" + "};\n" + "\n" + "\n" + "/**\n" + " * Converts this Struct object to a plain JavaScript object.\n" + " * @return {!Object<string, !proto.google.protobuf.JavaScriptValue>} a " + "plain\n" + " * JavaScript object representing this Struct.\n" + " */\n" + "proto.google.protobuf.Struct.prototype.toJavaScript = function() {\n" + " var ret = {};\n" + "\n" + " this.getFieldsMap().forEach(function(value, key) {\n" + " ret[key] = value.toJavaScript();\n" + " });\n" + "\n" + " return ret;\n" + "};\n" + "\n" + "\n" + "/**\n" + " * Constructs a Struct protobuf from this plain JavaScript object.\n" + " * @param {!Object} obj a plain JavaScript object\n" + " * @return {proto.google.protobuf.Struct} a new Struct object\n" + " */\n" + "proto.google.protobuf.Struct.fromJavaScript = function(obj) {\n" + " var ret = new proto.google.protobuf.Struct();\n" + " var map = ret.getFieldsMap();\n" + "\n" + " for (var property in obj) {\n" + " var val = obj[property];\n" + " map.set(property, proto.google.protobuf.Value.fromJavaScript(val));\n" + " }\n" + "\n" + " return ret;\n" + "};\n"}, + {NULL, NULL} // Terminate the list. +}; 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/mock_code_generator.cc b/src/google/protobuf/compiler/mock_code_generator.cc index 7719ec3d..e150f97d 100644 --- a/src/google/protobuf/compiler/mock_code_generator.cc +++ b/src/google/protobuf/compiler/mock_code_generator.cc @@ -35,9 +35,6 @@ #include <stdlib.h> #include <iostream> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <vector> @@ -103,8 +100,7 @@ void MockCodeGenerator::ExpectGenerated( File::GetContents(output_directory + "/" + GetOutputFileName(name, file), &content, true)); - std::vector<string> lines = - Split(content, "\n", true); + std::vector<string> lines = Split(content, "\n", true); while (!lines.empty() && lines.back().empty()) { lines.pop_back(); @@ -232,7 +228,7 @@ bool MockCodeGenerator::Generate( for (size_t i = 0; i < insert_into.size(); i++) { { - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->OpenForInsert( + std::unique_ptr<io::ZeroCopyOutputStream> output(context->OpenForInsert( GetOutputFileName(insert_into[i], file), kFirstInsertionPointName)); io::Printer printer(output.get(), '$'); printer.PrintRaw(GetOutputFileContent(name_, "first_insert", @@ -244,7 +240,7 @@ bool MockCodeGenerator::Generate( } { - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( context->OpenForInsert(GetOutputFileName(insert_into[i], file), kSecondInsertionPointName)); io::Printer printer(output.get(), '$'); @@ -257,7 +253,7 @@ bool MockCodeGenerator::Generate( } } } else { - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( context->Open(GetOutputFileName(name_, file))); GeneratedCodeInfo annotations; @@ -287,7 +283,7 @@ bool MockCodeGenerator::Generate( return false; } if (annotate) { - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> meta_output( + std::unique_ptr<io::ZeroCopyOutputStream> meta_output( context->Open(GetOutputFileName(name_, file) + ".meta")); if (!TextFormat::Print(annotations, meta_output.get())) { *error = "MockCodeGenerator couldn't write .meta"; diff --git a/src/google/protobuf/compiler/objectivec/objectivec_enum.cc b/src/google/protobuf/compiler/objectivec/objectivec_enum.cc index 02d60b3e..978e985c 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_enum.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_enum.cc @@ -149,7 +149,7 @@ void EnumGenerator::GenerateSource(io::Printer* printer) { printer->Print( "GPBEnumDescriptor *$name$_EnumDescriptor(void) {\n" - " static GPBEnumDescriptor *descriptor = NULL;\n" + " static _Atomic(GPBEnumDescriptor*) descriptor = nil;\n" " if (!descriptor) {\n", "name", name_); @@ -192,7 +192,8 @@ void EnumGenerator::GenerateSource(io::Printer* printer) { "extraTextFormatInfo", CEscape(text_format_decode_data.Data())); } printer->Print( - " if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) {\n" + " GPBEnumDescriptor *expected = nil;\n" + " if (!atomic_compare_exchange_strong(&descriptor, &expected, worker)) {\n" " [worker release];\n" " }\n" " }\n" diff --git a/src/google/protobuf/compiler/objectivec/objectivec_enum.h b/src/google/protobuf/compiler/objectivec/objectivec_enum.h index 0b41cf73..f52e9e68 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_enum.h +++ b/src/google/protobuf/compiler/objectivec/objectivec_enum.h @@ -59,8 +59,8 @@ class EnumGenerator { private: const EnumDescriptor* descriptor_; - vector<const EnumValueDescriptor*> base_values_; - vector<const EnumValueDescriptor*> all_values_; + std::vector<const EnumValueDescriptor*> base_values_; + std::vector<const EnumValueDescriptor*> all_values_; const string name_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator); diff --git a/src/google/protobuf/compiler/objectivec/objectivec_field.cc b/src/google/protobuf/compiler/objectivec/objectivec_field.cc index b6123fad..f74599ba 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_field.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_field.cc @@ -410,10 +410,8 @@ bool RepeatedFieldGenerator::RuntimeUsesHasBit(void) const { FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor, const Options& options) : descriptor_(descriptor), - field_generators_( - new scoped_ptr<FieldGenerator>[descriptor->field_count()]), - extension_generators_( - new scoped_ptr<FieldGenerator>[descriptor->extension_count()]) { + field_generators_(descriptor->field_count()), + extension_generators_(descriptor->extension_count()) { // Construct all the FieldGenerators. for (int i = 0; i < descriptor->field_count(); i++) { field_generators_[i].reset( diff --git a/src/google/protobuf/compiler/objectivec/objectivec_field.h b/src/google/protobuf/compiler/objectivec/objectivec_field.h index 6bd5db2e..216034d0 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_field.h +++ b/src/google/protobuf/compiler/objectivec/objectivec_field.h @@ -182,8 +182,8 @@ class FieldGeneratorMap { private: const Descriptor* descriptor_; - scoped_array<scoped_ptr<FieldGenerator> > field_generators_; - scoped_array<scoped_ptr<FieldGenerator> > extension_generators_; + std::vector<std::unique_ptr<FieldGenerator>> field_generators_; + std::vector<std::unique_ptr<FieldGenerator>> extension_generators_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap); }; diff --git a/src/google/protobuf/compiler/objectivec/objectivec_file.cc b/src/google/protobuf/compiler/objectivec/objectivec_file.cc index 954b2688..f0d9b4d5 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_file.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_file.cc @@ -56,6 +56,20 @@ const int32 GOOGLE_PROTOBUF_OBJC_VERSION = 30002; const char* kHeaderExtension = ".pbobjc.h"; +// Checks if a message contains any enums definitions (on the message or +// a nested message under it). +bool MessageContainsEnums(const Descriptor* message) { + if (message->enum_type_count() > 0) { + return true; + } + for (int i = 0; i < message->nested_type_count(); i++) { + if (MessageContainsEnums(message->nested_type(i))) { + return true; + } + } + return false; +} + // Checks if a message contains any extension definitions (on the message or // a nested message under it). bool MessageContainsExtensions(const Descriptor* message) { @@ -70,6 +84,20 @@ bool MessageContainsExtensions(const Descriptor* message) { return false; } +// Checks if the file contains any enum definitions (at the root or +// nested under a message). +bool FileContainsEnums(const FileDescriptor* file) { + if (file->enum_type_count() > 0) { + return true; + } + for (int i = 0; i < file->message_type_count(); i++) { + if (MessageContainsEnums(file->message_type(i))) { + return true; + } + } + return false; +} + // Checks if the file contains any extensions definitions (at the root or // nested under a message). bool FileContainsExtensions(const FileDescriptor* file) { @@ -88,9 +116,9 @@ bool FileContainsExtensions(const FileDescriptor* file) { // deps as visited and prunes them from the needed files list. void PruneFileAndDepsMarkingAsVisited( const FileDescriptor* file, - vector<const FileDescriptor*>* files, + std::vector<const FileDescriptor*>* files, std::set<const FileDescriptor*>* files_visited) { - vector<const FileDescriptor*>::iterator iter = + std::vector<const FileDescriptor*>::iterator iter = std::find(files->begin(), files->end(), file); if (iter != files->end()) { files->erase(iter); @@ -104,7 +132,7 @@ void PruneFileAndDepsMarkingAsVisited( // Helper for CollectMinimalFileDepsContainingExtensions. void CollectMinimalFileDepsContainingExtensionsWorker( const FileDescriptor* file, - vector<const FileDescriptor*>* files, + std::vector<const FileDescriptor*>* files, std::set<const FileDescriptor*>* files_visited) { if (files_visited->find(file) != files_visited->end()) { return; @@ -137,7 +165,7 @@ void CollectMinimalFileDepsContainingExtensionsWorker( // specifically). void CollectMinimalFileDepsContainingExtensions( const FileDescriptor* file, - vector<const FileDescriptor*>* files) { + std::vector<const FileDescriptor*>* files) { std::set<const FileDescriptor*> files_visited; for (int i = 0; i < file->dependency_count(); i++) { const FileDescriptor* dep = file->dependency(i); @@ -160,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)); @@ -186,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. @@ -208,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); @@ -230,7 +270,7 @@ void FileGenerator::GenerateHeader(io::Printer *printer) { "\n"); std::set<string> fwd_decls; - for (vector<MessageGenerator *>::iterator iter = message_generators_.begin(); + for (std::vector<MessageGenerator *>::iterator iter = message_generators_.begin(); iter != message_generators_.end(); ++iter) { (*iter)->DetermineForwardDeclarations(&fwd_decls); } @@ -247,12 +287,12 @@ void FileGenerator::GenerateHeader(io::Printer *printer) { "\n"); // need to write out all enums first - for (vector<EnumGenerator *>::iterator iter = enum_generators_.begin(); + for (std::vector<EnumGenerator *>::iterator iter = enum_generators_.begin(); iter != enum_generators_.end(); ++iter) { (*iter)->GenerateHeader(printer); } - for (vector<MessageGenerator *>::iterator iter = message_generators_.begin(); + for (std::vector<MessageGenerator *>::iterator iter = message_generators_.begin(); iter != message_generators_.end(); ++iter) { (*iter)->GenerateEnumHeader(printer); } @@ -283,7 +323,7 @@ void FileGenerator::GenerateHeader(io::Printer *printer) { "@interface $root_class_name$ (DynamicMethods)\n", "root_class_name", root_class_name_); - for (vector<ExtensionGenerator *>::iterator iter = + for (std::vector<ExtensionGenerator *>::iterator iter = extension_generators_.begin(); iter != extension_generators_.end(); ++iter) { (*iter)->GenerateMembersHeader(printer); @@ -292,7 +332,7 @@ void FileGenerator::GenerateHeader(io::Printer *printer) { printer->Print("@end\n\n"); } // extension_generators_.size() > 0 - for (vector<MessageGenerator *>::iterator iter = message_generators_.begin(); + for (std::vector<MessageGenerator *>::iterator iter = message_generators_.begin(); iter != message_generators_.end(); ++iter) { (*iter)->GenerateMessageHeader(printer); } @@ -309,15 +349,25 @@ 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_)) { + printer->Print( + "#import <stdatomic.h>\n" + "\n"); + } - vector<const FileDescriptor*> deps_with_extensions; + std::vector<const FileDescriptor*> deps_with_extensions; CollectMinimalFileDepsContainingExtensions(file_, &deps_with_extensions); { 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. @@ -341,7 +391,7 @@ void FileGenerator::GenerateSource(io::Printer *printer) { // imported so it can get merged into the root's extensions registry. // See the Note by CollectMinimalFileDepsContainingExtensions before // changing this. - for (vector<const FileDescriptor *>::iterator iter = + for (std::vector<const FileDescriptor *>::iterator iter = deps_with_extensions.begin(); iter != deps_with_extensions.end(); ++iter) { if (!IsDirectDependency(*iter, file_)) { @@ -353,7 +403,7 @@ void FileGenerator::GenerateSource(io::Printer *printer) { } bool includes_oneof = false; - for (vector<MessageGenerator *>::iterator iter = message_generators_.begin(); + for (std::vector<MessageGenerator *>::iterator iter = message_generators_.begin(); iter != message_generators_.end(); ++iter) { if ((*iter)->IncludesOneOfDefinition()) { includes_oneof = true; @@ -406,12 +456,12 @@ void FileGenerator::GenerateSource(io::Printer *printer) { printer->Print( "static GPBExtensionDescription descriptions[] = {\n"); printer->Indent(); - for (vector<ExtensionGenerator *>::iterator iter = + for (std::vector<ExtensionGenerator *>::iterator iter = extension_generators_.begin(); iter != extension_generators_.end(); ++iter) { (*iter)->GenerateStaticVariablesInitialization(printer); } - for (vector<MessageGenerator *>::iterator iter = + for (std::vector<MessageGenerator *>::iterator iter = message_generators_.begin(); iter != message_generators_.end(); ++iter) { (*iter)->GenerateStaticVariablesInitialization(printer); @@ -435,7 +485,7 @@ void FileGenerator::GenerateSource(io::Printer *printer) { } else { printer->Print( "// Merge in the imports (direct or indirect) that defined extensions.\n"); - for (vector<const FileDescriptor *>::iterator iter = + for (std::vector<const FileDescriptor *>::iterator iter = deps_with_extensions.begin(); iter != deps_with_extensions.end(); ++iter) { const string root_class_name(FileClassName((*iter))); @@ -511,11 +561,11 @@ void FileGenerator::GenerateSource(io::Printer *printer) { "\n"); } - for (vector<EnumGenerator *>::iterator iter = enum_generators_.begin(); + for (std::vector<EnumGenerator *>::iterator iter = enum_generators_.begin(); iter != enum_generators_.end(); ++iter) { (*iter)->GenerateSource(printer); } - for (vector<MessageGenerator *>::iterator iter = message_generators_.begin(); + for (std::vector<MessageGenerator *>::iterator iter = message_generators_.begin(); iter != message_generators_.end(); ++iter) { (*iter)->GenerateSource(printer); } @@ -531,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" @@ -540,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" @@ -547,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 a60a6885..1754fc0a 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_file.h +++ b/src/google/protobuf/compiler/objectivec/objectivec_file.h @@ -66,15 +66,16 @@ class FileGenerator { private: const FileDescriptor* file_; string root_class_name_; + bool is_bundled_proto_; - vector<EnumGenerator*> enum_generators_; - vector<MessageGenerator*> message_generators_; - vector<ExtensionGenerator*> extension_generators_; + std::vector<EnumGenerator*> enum_generators_; + std::vector<MessageGenerator*> message_generators_; + std::vector<ExtensionGenerator*> extension_generators_; 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_generator.cc b/src/google/protobuf/compiler/objectivec/objectivec_generator.cc index 36407467..e0597cc7 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_generator.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_generator.cc @@ -57,7 +57,7 @@ bool ObjectiveCGenerator::Generate(const FileDescriptor* file, return false; } -bool ObjectiveCGenerator::GenerateAll(const vector<const FileDescriptor*>& files, +bool ObjectiveCGenerator::GenerateAll(const std::vector<const FileDescriptor*>& files, const string& parameter, GeneratorContext* context, string* error) const { @@ -71,7 +71,7 @@ bool ObjectiveCGenerator::GenerateAll(const vector<const FileDescriptor*>& files Options generation_options; - vector<pair<string, string> > options; + std::vector<std::pair<string, string> > options; ParseGeneratorParameter(parameter, &options); for (int i = 0; i < options.size(); i++) { if (options[i].first == "expected_prefixes_path") { @@ -142,7 +142,7 @@ bool ObjectiveCGenerator::GenerateAll(const vector<const FileDescriptor*>& files // Generate header. { - scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( context->Open(filepath + ".pbobjc.h")); io::Printer printer(output.get(), '$'); file_generator.GenerateHeader(&printer); @@ -150,7 +150,7 @@ bool ObjectiveCGenerator::GenerateAll(const vector<const FileDescriptor*>& files // Generate m file. { - scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( context->Open(filepath + ".pbobjc.m")); io::Printer printer(output.get(), '$'); file_generator.GenerateSource(&printer); diff --git a/src/google/protobuf/compiler/objectivec/objectivec_generator.h b/src/google/protobuf/compiler/objectivec/objectivec_generator.h index b1723318..3e43f732 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_generator.h +++ b/src/google/protobuf/compiler/objectivec/objectivec_generator.h @@ -56,7 +56,7 @@ class LIBPROTOC_EXPORT ObjectiveCGenerator : public CodeGenerator { const string& parameter, GeneratorContext* context, string* error) const; - bool GenerateAll(const vector<const FileDescriptor*>& files, + bool GenerateAll(const std::vector<const FileDescriptor*>& files, const string& parameter, GeneratorContext* context, string* error) const; diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc index 14715ef6..df71c8bb 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc @@ -100,7 +100,7 @@ bool ascii_isnewline(char c) { // Do not expose this outside of helpers, stick to having functions for specific // cases (ClassName(), FieldName()), so there is always consistent suffix rules. string UnderscoresToCamelCase(const string& input, bool first_capitalized) { - vector<string> values; + std::vector<string> values; string current; bool last_char_was_number = false; @@ -141,7 +141,7 @@ string UnderscoresToCamelCase(const string& input, bool first_capitalized) { string result; bool first_segment_forces_upper = false; - for (vector<string>::iterator i = values.begin(); i != values.end(); ++i) { + for (std::vector<string>::iterator i = values.begin(); i != values.end(); ++i) { string value = *i; bool all_upper = (kUpperSegments.count(value) > 0); if (all_upper && (result.length() == 0)) { @@ -864,7 +864,7 @@ bool HasNonZeroDefaultValue(const FieldDescriptor* field) { } string BuildFlagsString(const FlagType flag_type, - const vector<string>& strings) { + const std::vector<string>& strings) { if (strings.size() == 0) { return GetZeroEnumNameForFlagType(flag_type); } else if (strings.size() == 1) { @@ -886,7 +886,7 @@ string BuildCommentsString(const SourceLocation& location, const string& comments = location.leading_comments.empty() ? location.trailing_comments : location.leading_comments; - vector<string> lines; + std::vector<string> lines; SplitStringAllowEmpty(comments, "\n", &lines); while (!lines.empty() && lines.back().empty()) { lines.pop_back(); @@ -1156,7 +1156,7 @@ bool ValidateObjCClassPrefix( } // namespace -bool ValidateObjCClassPrefixes(const vector<const FileDescriptor*>& files, +bool ValidateObjCClassPrefixes(const std::vector<const FileDescriptor*>& files, const Options& generation_options, string* out_error) { // Load the expected package prefixes, if available, to validate against. @@ -1187,7 +1187,7 @@ TextFormatDecodeData::~TextFormatDecodeData() { } void TextFormatDecodeData::AddString(int32 key, const string& input_for_decode, const string& desired_output) { - for (vector<DataEntry>::const_iterator i = entries_.begin(); + for (std::vector<DataEntry>::const_iterator i = entries_.begin(); i != entries_.end(); ++i) { if (i->first == key) { std::cerr << "error: duplicate key (" << key @@ -1211,7 +1211,7 @@ string TextFormatDecodeData::Data() const { io::CodedOutputStream output_stream(&data_outputstream); output_stream.WriteVarint32(num_entries()); - for (vector<DataEntry>::const_iterator i = entries_.begin(); + for (std::vector<DataEntry>::const_iterator i = entries_.begin(); i != entries_.end(); ++i) { output_stream.WriteVarint32(i->first); output_stream.WriteString(i->second); @@ -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; } @@ -1561,7 +1568,7 @@ void ImportWriter::Print(io::Printer* printer) const { printer->Print( "#if $cpp_symbol$\n", "cpp_symbol", cpp_symbol); - for (vector<string>::const_iterator iter = protobuf_framework_imports_.begin(); + for (std::vector<string>::const_iterator iter = protobuf_framework_imports_.begin(); iter != protobuf_framework_imports_.end(); ++iter) { printer->Print( " #import <$framework_name$/$header$>\n", @@ -1570,7 +1577,7 @@ void ImportWriter::Print(io::Printer* printer) const { } printer->Print( "#else\n"); - for (vector<string>::const_iterator iter = protobuf_non_framework_imports_.begin(); + for (std::vector<string>::const_iterator iter = protobuf_non_framework_imports_.begin(); iter != protobuf_non_framework_imports_.end(); ++iter) { printer->Print( " #import \"$header$\"\n", @@ -1587,10 +1594,10 @@ void ImportWriter::Print(io::Printer* printer) const { printer->Print("\n"); } - for (vector<string>::const_iterator iter = other_framework_imports_.begin(); + for (std::vector<string>::const_iterator iter = other_framework_imports_.begin(); iter != other_framework_imports_.end(); ++iter) { printer->Print( - " #import <$header$>\n", + "#import <$header$>\n", "header", *iter); } @@ -1602,10 +1609,10 @@ void ImportWriter::Print(io::Printer* printer) const { printer->Print("\n"); } - for (vector<string>::const_iterator iter = other_imports_.begin(); + for (std::vector<string>::const_iterator iter = other_imports_.begin(); iter != other_imports_.end(); ++iter) { printer->Print( - " #import \"$header$\"\n", + "#import \"$header$\"\n", "header", *iter); } } diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h index daea7609..8999aa59 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h +++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h @@ -190,7 +190,7 @@ string LIBPROTOC_EXPORT GPBGenericValueFieldName(const FieldDescriptor* field); string LIBPROTOC_EXPORT DefaultValue(const FieldDescriptor* field); bool LIBPROTOC_EXPORT HasNonZeroDefaultValue(const FieldDescriptor* field); -string LIBPROTOC_EXPORT BuildFlagsString(const FlagType type, const vector<string>& strings); +string LIBPROTOC_EXPORT BuildFlagsString(const FlagType type, const std::vector<string>& strings); // Builds HeaderDoc/appledoc style comments out of the comments in the .proto // file. @@ -210,7 +210,7 @@ bool LIBPROTOC_EXPORT IsProtobufLibraryBundledProtoFile(const FileDescriptor* fi // Checks the prefix for the given files and outputs any warnings as needed. If // there are flat out errors, then out_error is filled in with the first error // and the result is false. -bool LIBPROTOC_EXPORT ValidateObjCClassPrefixes(const vector<const FileDescriptor*>& files, +bool LIBPROTOC_EXPORT ValidateObjCClassPrefixes(const std::vector<const FileDescriptor*>& files, const Options& generation_options, string* out_error); @@ -233,7 +233,7 @@ class LIBPROTOC_EXPORT TextFormatDecodeData { GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TextFormatDecodeData); typedef std::pair<int32, string> DataEntry; - vector<DataEntry> entries_; + std::vector<DataEntry> entries_; }; // Helper for parsing simple files. @@ -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,13 +276,14 @@ 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_; - vector<string> protobuf_framework_imports_; - vector<string> protobuf_non_framework_imports_; - vector<string> other_framework_imports_; - vector<string> other_imports_; + std::vector<string> protobuf_framework_imports_; + std::vector<string> protobuf_non_framework_imports_; + std::vector<string> other_framework_imports_; + std::vector<string> other_imports_; }; } // namespace objectivec diff --git a/src/google/protobuf/compiler/objectivec/objectivec_map_field.h b/src/google/protobuf/compiler/objectivec/objectivec_map_field.h index 6664d849..dc7beacf 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_map_field.h +++ b/src/google/protobuf/compiler/objectivec/objectivec_map_field.h @@ -54,7 +54,7 @@ class MapFieldGenerator : public RepeatedFieldGenerator { virtual void DetermineForwardDeclarations(std::set<string>* fwd_decls) const; private: - scoped_ptr<FieldGenerator> value_field_generator_; + std::unique_ptr<FieldGenerator> value_field_generator_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldGenerator); }; diff --git a/src/google/protobuf/compiler/objectivec/objectivec_message.cc b/src/google/protobuf/compiler/objectivec/objectivec_message.cc index 4f22e290..83888854 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_message.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_message.cc @@ -220,13 +220,13 @@ MessageGenerator::~MessageGenerator() { void MessageGenerator::GenerateStaticVariablesInitialization( io::Printer* printer) { - for (vector<ExtensionGenerator*>::iterator iter = + for (std::vector<ExtensionGenerator*>::iterator iter = extension_generators_.begin(); iter != extension_generators_.end(); ++iter) { (*iter)->GenerateStaticVariablesInitialization(printer); } - for (vector<MessageGenerator*>::iterator iter = + for (std::vector<MessageGenerator*>::iterator iter = nested_message_generators_.begin(); iter != nested_message_generators_.end(); ++iter) { (*iter)->GenerateStaticVariablesInitialization(printer); @@ -242,7 +242,7 @@ void MessageGenerator::DetermineForwardDeclarations(std::set<string>* fwd_decls) } } - for (vector<MessageGenerator*>::iterator iter = + for (std::vector<MessageGenerator*>::iterator iter = nested_message_generators_.begin(); iter != nested_message_generators_.end(); ++iter) { (*iter)->DetermineForwardDeclarations(fwd_decls); @@ -254,7 +254,7 @@ bool MessageGenerator::IncludesOneOfDefinition() const { return true; } - for (vector<MessageGenerator*>::const_iterator iter = + for (std::vector<MessageGenerator*>::const_iterator iter = nested_message_generators_.begin(); iter != nested_message_generators_.end(); ++iter) { if ((*iter)->IncludesOneOfDefinition()) { @@ -266,12 +266,12 @@ bool MessageGenerator::IncludesOneOfDefinition() const { } void MessageGenerator::GenerateEnumHeader(io::Printer* printer) { - for (vector<EnumGenerator*>::iterator iter = enum_generators_.begin(); + for (std::vector<EnumGenerator*>::iterator iter = enum_generators_.begin(); iter != enum_generators_.end(); ++iter) { (*iter)->GenerateHeader(printer); } - for (vector<MessageGenerator*>::iterator iter = + for (std::vector<MessageGenerator*>::iterator iter = nested_message_generators_.begin(); iter != nested_message_generators_.end(); ++iter) { (*iter)->GenerateEnumHeader(printer); @@ -280,13 +280,13 @@ void MessageGenerator::GenerateEnumHeader(io::Printer* printer) { void MessageGenerator::GenerateExtensionRegistrationSource( io::Printer* printer) { - for (vector<ExtensionGenerator*>::iterator iter = + for (std::vector<ExtensionGenerator*>::iterator iter = extension_generators_.begin(); iter != extension_generators_.end(); ++iter) { (*iter)->GenerateRegistrationSource(printer); } - for (vector<MessageGenerator*>::iterator iter = + for (std::vector<MessageGenerator*>::iterator iter = nested_message_generators_.begin(); iter != nested_message_generators_.end(); ++iter) { (*iter)->GenerateExtensionRegistrationSource(printer); @@ -296,7 +296,7 @@ void MessageGenerator::GenerateExtensionRegistrationSource( void MessageGenerator::GenerateMessageHeader(io::Printer* printer) { // This a a map entry message, just recurse and do nothing directly. if (IsMapEntryMessage(descriptor_)) { - for (vector<MessageGenerator*>::iterator iter = + for (std::vector<MessageGenerator*>::iterator iter = nested_message_generators_.begin(); iter != nested_message_generators_.end(); ++iter) { (*iter)->GenerateMessageHeader(printer); @@ -310,7 +310,7 @@ void MessageGenerator::GenerateMessageHeader(io::Printer* printer) { "classname", class_name_); if (descriptor_->field_count()) { - scoped_array<const FieldDescriptor*> sorted_fields( + std::unique_ptr<const FieldDescriptor*[]> sorted_fields( SortFieldsByNumber(descriptor_)); printer->Print("typedef GPB_ENUM($classname$_FieldNumber) {\n", @@ -326,7 +326,7 @@ void MessageGenerator::GenerateMessageHeader(io::Printer* printer) { printer->Print("};\n\n"); } - for (vector<OneofGenerator*>::iterator iter = oneof_generators_.begin(); + for (std::vector<OneofGenerator*>::iterator iter = oneof_generators_.begin(); iter != oneof_generators_.end(); ++iter) { (*iter)->GenerateCaseEnum(printer); } @@ -345,7 +345,7 @@ void MessageGenerator::GenerateMessageHeader(io::Printer* printer) { "deprecated_attribute", deprecated_attribute_, "comments", message_comments); - vector<char> seen_oneofs(descriptor_->oneof_decl_count(), 0); + std::vector<char> seen_oneofs(descriptor_->oneof_decl_count(), 0); for (int i = 0; i < descriptor_->field_count(); i++) { const FieldDescriptor* field = descriptor_->field(i); if (field->containing_oneof() != NULL) { @@ -367,7 +367,7 @@ void MessageGenerator::GenerateMessageHeader(io::Printer* printer) { } if (!oneof_generators_.empty()) { - for (vector<OneofGenerator*>::iterator iter = oneof_generators_.begin(); + for (std::vector<OneofGenerator*>::iterator iter = oneof_generators_.begin(); iter != oneof_generators_.end(); ++iter) { (*iter)->GenerateClearFunctionDeclaration(printer); } @@ -377,7 +377,7 @@ void MessageGenerator::GenerateMessageHeader(io::Printer* printer) { if (descriptor_->extension_count() > 0) { printer->Print("@interface $classname$ (DynamicMethods)\n\n", "classname", class_name_); - for (vector<ExtensionGenerator*>::iterator iter = + for (std::vector<ExtensionGenerator*>::iterator iter = extension_generators_.begin(); iter != extension_generators_.end(); ++iter) { (*iter)->GenerateMembersHeader(printer); @@ -385,7 +385,7 @@ void MessageGenerator::GenerateMessageHeader(io::Printer* printer) { printer->Print("@end\n\n"); } - for (vector<MessageGenerator*>::iterator iter = + for (std::vector<MessageGenerator*>::iterator iter = nested_message_generators_.begin(); iter != nested_message_generators_.end(); ++iter) { (*iter)->GenerateMessageHeader(printer); @@ -410,7 +410,7 @@ void MessageGenerator::GenerateSource(io::Printer* printer) { printer->Print("@implementation $classname$\n\n", "classname", class_name_); - for (vector<OneofGenerator*>::iterator iter = oneof_generators_.begin(); + for (std::vector<OneofGenerator*>::iterator iter = oneof_generators_.begin(); iter != oneof_generators_.end(); ++iter) { (*iter)->GeneratePropertyImplementation(printer); } @@ -420,12 +420,12 @@ void MessageGenerator::GenerateSource(io::Printer* printer) { .GeneratePropertyImplementation(printer); } - scoped_array<const FieldDescriptor*> sorted_fields( + std::unique_ptr<const FieldDescriptor*[]> sorted_fields( SortFieldsByNumber(descriptor_)); - scoped_array<const FieldDescriptor*> size_order_fields( + std::unique_ptr<const FieldDescriptor*[]> size_order_fields( SortFieldsByStorageSize(descriptor_)); - vector<const Descriptor::ExtensionRange*> sorted_extensions; + std::vector<const Descriptor::ExtensionRange*> sorted_extensions; for (int i = 0; i < descriptor_->extension_range_count(); ++i) { sorted_extensions.push_back(descriptor_->extension_range(i)); } @@ -448,7 +448,7 @@ void MessageGenerator::GenerateSource(io::Printer* printer) { sizeof_has_storage = 1; } // Tell all the fields the oneof base. - for (vector<OneofGenerator*>::iterator iter = oneof_generators_.begin(); + for (std::vector<OneofGenerator*>::iterator iter = oneof_generators_.begin(); iter != oneof_generators_.end(); ++iter) { (*iter)->SetOneofIndexBase(sizeof_has_storage); } @@ -548,7 +548,7 @@ void MessageGenerator::GenerateSource(io::Printer* printer) { if (oneof_generators_.size() != 0) { printer->Print( " static const char *oneofs[] = {\n"); - for (vector<OneofGenerator*>::iterator iter = oneof_generators_.begin(); + for (std::vector<OneofGenerator*>::iterator iter = oneof_generators_.begin(); iter != oneof_generators_.end(); ++iter) { printer->Print( " \"$name$\",\n", @@ -623,18 +623,18 @@ void MessageGenerator::GenerateSource(io::Printer* printer) { .GenerateCFunctionImplementations(printer); } - for (vector<OneofGenerator*>::iterator iter = oneof_generators_.begin(); + for (std::vector<OneofGenerator*>::iterator iter = oneof_generators_.begin(); iter != oneof_generators_.end(); ++iter) { (*iter)->GenerateClearFunctionImplementation(printer); } } - for (vector<EnumGenerator*>::iterator iter = enum_generators_.begin(); + for (std::vector<EnumGenerator*>::iterator iter = enum_generators_.begin(); iter != enum_generators_.end(); ++iter) { (*iter)->GenerateSource(printer); } - for (vector<MessageGenerator*>::iterator iter = + for (std::vector<MessageGenerator*>::iterator iter = nested_message_generators_.begin(); iter != nested_message_generators_.end(); ++iter) { (*iter)->GenerateSource(printer); diff --git a/src/google/protobuf/compiler/objectivec/objectivec_message.h b/src/google/protobuf/compiler/objectivec/objectivec_message.h index 8f317ac0..2de03f12 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_message.h +++ b/src/google/protobuf/compiler/objectivec/objectivec_message.h @@ -86,10 +86,10 @@ class MessageGenerator { FieldGeneratorMap field_generators_; const string class_name_; const string deprecated_attribute_; - vector<ExtensionGenerator*> extension_generators_; - vector<EnumGenerator*> enum_generators_; - vector<MessageGenerator*> nested_message_generators_; - vector<OneofGenerator*> oneof_generators_; + std::vector<ExtensionGenerator*> extension_generators_; + std::vector<EnumGenerator*> enum_generators_; + std::vector<MessageGenerator*> nested_message_generators_; + std::vector<OneofGenerator*> oneof_generators_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator); }; diff --git a/src/google/protobuf/compiler/parser.cc b/src/google/protobuf/compiler/parser.cc index 03d05ad4..5c7047a6 100644 --- a/src/google/protobuf/compiler/parser.cc +++ b/src/google/protobuf/compiler/parser.cc @@ -39,13 +39,14 @@ #include <limits> +#include <google/protobuf/stubs/casts.h> +#include <google/protobuf/stubs/logging.h> +#include <google/protobuf/stubs/common.h> #include <google/protobuf/compiler/parser.h> -#include <google/protobuf/descriptor.h> #include <google/protobuf/descriptor.pb.h> -#include <google/protobuf/wire_format.h> #include <google/protobuf/io/tokenizer.h> -#include <google/protobuf/stubs/logging.h> -#include <google/protobuf/stubs/common.h> +#include <google/protobuf/descriptor.h> +#include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/map_util.h> @@ -336,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); @@ -402,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 { @@ -1495,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. @@ -1517,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)); @@ -1650,10 +1688,6 @@ bool Parser::ParseReservedNumbers(EnumDescriptorProto* message, if (TryConsume("max")) { // This is in the enum descriptor path, which doesn't have the message // set duality to fix up, so it doesn't integrate with the sentinel. - - // Evaluate 'max' to INT_MAX - 1 so that incrementing to create the - // exclusive range end doesn't cause an overflow. - // Note, this prevents reserving the actual INT_MAX enum value. end = INT_MAX; } else { DO(ConsumeSignedInteger(&end, "Expected integer.")); diff --git a/src/google/protobuf/compiler/parser.h b/src/google/protobuf/compiler/parser.h index 33b4c700..5d98e5e1 100644 --- a/src/google/protobuf/compiler/parser.h +++ b/src/google/protobuf/compiler/parser.h @@ -40,10 +40,10 @@ #include <map> #include <string> #include <utility> -#include <google/protobuf/descriptor.h> #include <google/protobuf/descriptor.pb.h> -#include <google/protobuf/repeated_field.h> #include <google/protobuf/io/tokenizer.h> +#include <google/protobuf/descriptor.h> +#include <google/protobuf/repeated_field.h> namespace google { namespace protobuf { class Message; } @@ -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/parser_unittest.cc b/src/google/protobuf/compiler/parser_unittest.cc index 9b59842e..0725a682 100644 --- a/src/google/protobuf/compiler/parser_unittest.cc +++ b/src/google/protobuf/compiler/parser_unittest.cc @@ -33,9 +33,6 @@ // Sanjay Ghemawat, Jeff Dean, and others. #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <vector> #include <algorithm> #include <map> @@ -50,6 +47,7 @@ #include <google/protobuf/text_format.h> #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/substitute.h> + #include <google/protobuf/stubs/map_util.h> #include <google/protobuf/testing/googletest.h> @@ -177,9 +175,9 @@ class ParserTest : public testing::Test { MockErrorCollector error_collector_; DescriptorPool pool_; - google::protobuf::scoped_ptr<io::ZeroCopyInputStream> raw_input_; - google::protobuf::scoped_ptr<io::Tokenizer> input_; - google::protobuf::scoped_ptr<Parser> parser_; + std::unique_ptr<io::ZeroCopyInputStream> raw_input_; + std::unique_ptr<io::Tokenizer> input_; + std::unique_ptr<Parser> parser_; bool require_syntax_identifier_; }; diff --git a/src/google/protobuf/compiler/php/php_generator.cc b/src/google/protobuf/compiler/php/php_generator.cc index dd4392c2..a58e1754 100644 --- a/src/google/protobuf/compiler/php/php_generator.cc +++ b/src/google/protobuf/compiler/php/php_generator.cc @@ -40,8 +40,6 @@ #include <sstream> -using google::protobuf::internal::scoped_ptr; - const std::string kDescriptorFile = "google/protobuf/descriptor.proto"; const std::string kEmptyFile = "google/protobuf/empty.proto"; const std::string kEmptyMetadataFile = "GPBMetadata/Google/Protobuf/GPBEmpty.php"; @@ -85,7 +83,7 @@ std::string PhpName(const std::string& full_name, bool is_descriptor); std::string DefaultForField(FieldDescriptor* field); std::string IntToString(int32 value); std::string FilenameToClassname(const string& filename); -std::string GeneratedMetadataFileName(const std::string& proto_file, +std::string GeneratedMetadataFileName(const FileDescriptor* file, bool is_descriptor); std::string LabelForField(FieldDescriptor* field); std::string TypeName(FieldDescriptor* field); @@ -96,6 +94,9 @@ void Indent(io::Printer* printer); void Outdent(io::Printer* printer); void GenerateMessageDocComment(io::Printer* printer, const Descriptor* message, int is_descriptor); +void GenerateMessageConstructorDocComment(io::Printer* printer, + const Descriptor* message, + int is_descriptor); void GenerateFieldDocComment(io::Printer* printer, const FieldDescriptor* field, int is_descriptor, int function_type); void GenerateEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_, @@ -107,31 +108,40 @@ void GenerateServiceDocComment(io::Printer* printer, void GenerateServiceMethodDocComment(io::Printer* printer, const MethodDescriptor* method); -std::string RenameEmpty(const std::string& name) { - if (name == "Empty") { - return "GPBEmpty"; - } else { - return name; + +std::string ReservedNamePrefix(const string& classname, + const FileDescriptor* file) { + bool is_reserved = false; + + string lower = classname; + transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + + for (int i = 0; i < kReservedNamesSize; i++) { + if (lower == kReservedNames[i]) { + is_reserved = true; + break; + } } -} -std::string MessageFullName(const Descriptor* message, bool is_descriptor) { - if (is_descriptor) { - return StringReplace(message->full_name(), - "google.protobuf", - "google.protobuf.internal", false); - } else { - return message->full_name(); + if (is_reserved) { + if (file->package() == "google.protobuf") { + return "GPB"; + } else { + return "PB"; + } } + + return ""; } -std::string EnumFullName(const EnumDescriptor* envm, bool is_descriptor) { +template <typename DescriptorType> +std::string DescriptorFullName(const DescriptorType* desc, bool is_descriptor) { if (is_descriptor) { - return StringReplace(envm->full_name(), + return StringReplace(desc->full_name(), "google.protobuf", "google.protobuf.internal", false); } else { - return envm->full_name(); + return desc->full_name(); } } @@ -143,22 +153,55 @@ std::string ClassNamePrefix(const string& classname, return prefix; } - bool is_reserved = false; + return ReservedNamePrefix(classname, desc->file()); +} + +template <typename DescriptorType> +std::string GeneratedClassNameImpl(const DescriptorType* desc) { + std::string classname = ClassNamePrefix(desc->name(), desc) + desc->name(); + const Descriptor* containing = desc->containing_type(); + while (containing != NULL) { + classname = ClassNamePrefix(containing->name(), desc) + containing->name() + + '\\' + classname; + containing = containing->containing_type(); + } + return classname; +} + +std::string GeneratedClassNameImpl(const ServiceDescriptor* desc) { + std::string classname = desc->name(); + return ClassNamePrefix(classname, desc) + classname; +} + +std::string GeneratedClassName(const Descriptor* desc) { + return GeneratedClassNameImpl(desc); +} + +std::string GeneratedClassName(const EnumDescriptor* desc) { + return GeneratedClassNameImpl(desc); +} + +std::string GeneratedClassName(const ServiceDescriptor* desc) { + return GeneratedClassNameImpl(desc); +} +template <typename DescriptorType> +std::string LegacyGeneratedClassName(const DescriptorType* desc) { + std::string classname = desc->name(); + const Descriptor* containing = desc->containing_type(); + while (containing != NULL) { + classname = containing->name() + '_' + classname; + containing = containing->containing_type(); + } + return ClassNamePrefix(classname, desc) + classname; +} + +std::string ClassNamePrefix(const string& classname) { string lower = classname; transform(lower.begin(), lower.end(), lower.begin(), ::tolower); for (int i = 0; i < kReservedNamesSize; i++) { if (lower == kReservedNames[i]) { - is_reserved = true; - break; - } - } - - if (is_reserved) { - if (desc->file()->package() == "google.protobuf") { - return "GPB"; - } else { return "PB"; } } @@ -194,34 +237,39 @@ std::string ConstantNamePrefix(const string& classname) { } template <typename DescriptorType> -std::string NamespacedName(const string& classname, - const DescriptorType* desc, bool is_descriptor) { +std::string RootPhpNamespace(const DescriptorType* desc, bool is_descriptor) { if (desc->file()->options().has_php_namespace()) { const string& php_namespace = desc->file()->options().php_namespace(); if (php_namespace != "") { - return php_namespace + '\\' + classname; - } else { - return classname; + return php_namespace; } + return ""; } - if (desc->file()->package() == "") { - return classname; - } else { - return PhpName(desc->file()->package(), is_descriptor) + '\\' + - classname; + if (desc->file()->package() != "") { + return PhpName(desc->file()->package(), is_descriptor); } + return ""; } template <typename DescriptorType> std::string FullClassName(const DescriptorType* desc, bool is_descriptor) { - string classname = GeneratedClassName(desc); - return NamespacedName(classname, desc, is_descriptor); + string classname = GeneratedClassNameImpl(desc); + string php_namespace = RootPhpNamespace(desc, is_descriptor); + if (php_namespace != "") { + return php_namespace + "\\" + classname; + } + return classname; } -std::string FullClassName(const ServiceDescriptor* desc, bool is_descriptor) { - string classname = GeneratedClassName(desc); - return NamespacedName(classname, desc, is_descriptor); +template <typename DescriptorType> +std::string LegacyFullClassName(const DescriptorType* desc, bool is_descriptor) { + string classname = LegacyGeneratedClassName(desc); + string php_namespace = RootPhpNamespace(desc, is_descriptor); + if (php_namespace != "") { + return php_namespace + "\\" + classname; + } + return classname; } std::string PhpName(const std::string& full_name, bool is_descriptor) { @@ -229,20 +277,23 @@ std::string PhpName(const std::string& full_name, bool is_descriptor) { return kDescriptorPackageName; } + std::string segment; std::string result; bool cap_next_letter = true; for (int i = 0; i < full_name.size(); i++) { if ('a' <= full_name[i] && full_name[i] <= 'z' && cap_next_letter) { - result += full_name[i] + ('A' - 'a'); + segment += full_name[i] + ('A' - 'a'); cap_next_letter = false; } else if (full_name[i] == '.') { - result += '\\'; + result += ClassNamePrefix(segment) + segment + '\\'; + segment = ""; cap_next_letter = true; } else { - result += full_name[i]; + segment += full_name[i]; cap_next_letter = false; } } + result += ClassNamePrefix(segment) + segment; return result; } @@ -270,11 +321,13 @@ std::string DefaultForField(const FieldDescriptor* field) { } } -std::string GeneratedMetadataFileName(const std::string& proto_file, +std::string GeneratedMetadataFileName(const FileDescriptor* file, bool is_descriptor) { + const string& proto_file = file->name(); int start_index = 0; int first_index = proto_file.find_first_of("/", start_index); - std::string result = "GPBMetadata/"; + std::string result = ""; + std::string segment = ""; if (proto_file == kEmptyFile) { return kEmptyMetadataFile; @@ -292,24 +345,44 @@ std::string GeneratedMetadataFileName(const std::string& proto_file, file_no_suffix = proto_file.substr(0, lastindex); } - while (first_index != string::npos) { - result += UnderscoresToCamelCase( - file_no_suffix.substr(start_index, first_index - start_index), true); - result += "/"; - start_index = first_index + 1; - first_index = file_no_suffix.find_first_of("/", start_index); + if (file->options().has_php_metadata_namespace()) { + const string& php_metadata_namespace = + file->options().php_metadata_namespace(); + if (php_metadata_namespace != "" && php_metadata_namespace != "\\") { + result += php_metadata_namespace; + std::replace(result.begin(), result.end(), '\\', '/'); + if (result.at(result.size() - 1) != '/') { + result += "/"; + } + } + } else { + result += "GPBMetadata/"; + while (first_index != string::npos) { + segment = UnderscoresToCamelCase( + file_no_suffix.substr(start_index, first_index - start_index), true); + result += ReservedNamePrefix(segment, file) + segment + "/"; + start_index = first_index + 1; + first_index = file_no_suffix.find_first_of("/", start_index); + } } // Append file name. - result += RenameEmpty(UnderscoresToCamelCase( - file_no_suffix.substr(start_index, first_index - start_index), true)); + int file_name_start = file_no_suffix.find_last_of("/"); + if (file_name_start == string::npos) { + file_name_start = 0; + } else { + file_name_start += 1; + } + segment = UnderscoresToCamelCase( + file_no_suffix.substr(file_name_start, first_index - file_name_start), true); - return result += ".php"; + return result + ReservedNamePrefix(segment, file) + segment + ".php"; } -std::string GeneratedMessageFileName(const Descriptor* message, +template <typename DescriptorType> +std::string GeneratedClassFileName(const DescriptorType* desc, bool is_descriptor) { - std::string result = FullClassName(message, is_descriptor); + std::string result = FullClassName(desc, is_descriptor); for (int i = 0; i < result.size(); i++) { if (result[i] == '\\') { result[i] = '/'; @@ -318,9 +391,11 @@ std::string GeneratedMessageFileName(const Descriptor* message, return result + ".php"; } -std::string GeneratedEnumFileName(const EnumDescriptor* en, - bool is_descriptor) { - std::string result = FullClassName(en, is_descriptor); +template <typename DescriptorType> +std::string LegacyGeneratedClassFileName(const DescriptorType* desc, + bool is_descriptor) { + std::string result = LegacyFullClassName(desc, is_descriptor); + for (int i = 0; i < result.size(); i++) { if (result[i] == '\\') { result[i] = '/'; @@ -463,10 +538,10 @@ std::string PhpGetterTypeName(const FieldDescriptor* field, bool is_descriptor) std::string EnumOrMessageSuffix( const FieldDescriptor* field, bool is_descriptor) { if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - return ", '" + MessageFullName(field->message_type(), is_descriptor) + "'"; + return ", '" + DescriptorFullName(field->message_type(), is_descriptor) + "'"; } if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { - return ", '" + EnumFullName(field->enum_type(), is_descriptor) + "'"; + return ", '" + DescriptorFullName(field->enum_type(), is_descriptor) + "'"; } return ""; } @@ -653,11 +728,11 @@ void GenerateFieldAccessor(const FieldDescriptor* field, bool is_descriptor, } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { printer->Print( "GPBUtil::checkMessage($var, \\^class_name^::class);\n", - "class_name", FullClassName(field->message_type(), is_descriptor)); + "class_name", LegacyFullClassName(field->message_type(), is_descriptor)); } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { printer->Print( "GPBUtil::checkEnum($var, \\^class_name^::class);\n", - "class_name", FullClassName(field->enum_type(), is_descriptor)); + "class_name", LegacyFullClassName(field->enum_type(), is_descriptor)); } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) { printer->Print( "GPBUtil::checkString($var, ^utf8^);\n", @@ -713,7 +788,7 @@ void GenerateEnumToPool(const EnumDescriptor* en, io::Printer* printer) { printer->Print( "$pool->addEnum('^name^', " "\\Google\\Protobuf\\Internal\\^class_name^::class)\n", - "name", EnumFullName(en, true), + "name", DescriptorFullName(en, true), "class_name", en->name()); Indent(printer); @@ -745,13 +820,13 @@ void GenerateMessageToPool(const string& name_prefix, const Descriptor* message, if (message->options().map_entry()) { return; } - string class_name = name_prefix.empty()? - message->name() : name_prefix + "_" + message->name(); + string class_name = (name_prefix.empty() ? "" : name_prefix + "\\") + + ReservedNamePrefix(message->name(), message->file()) + message->name(); printer->Print( "$pool->addMessage('^message^', " "\\Google\\Protobuf\\Internal\\^class_name^::class)\n", - "message", MessageFullName(message, true), + "message", DescriptorFullName(message, true), "class_name", class_name); Indent(printer); @@ -853,7 +928,7 @@ void GenerateAddFileToPool(const FileDescriptor* file, bool is_descriptor, continue; } std::string dependency_filename = - GeneratedMetadataFileName(name, is_descriptor); + GeneratedMetadataFileName(file->dependency(i), is_descriptor); printer->Print( "\\^name^::initOnce();\n", "name", FilenameToClassname(dependency_filename)); @@ -947,8 +1022,8 @@ std::string FilenameToClassname(const string& filename) { void GenerateMetadataFile(const FileDescriptor* file, bool is_descriptor, GeneratorContext* generator_context) { - std::string filename = GeneratedMetadataFileName(file->name(), is_descriptor); - scoped_ptr<io::ZeroCopyOutputStream> output( + std::string filename = GeneratedMetadataFileName(file, is_descriptor); + std::unique_ptr<io::ZeroCopyOutputStream> output( generator_context->Open(filename)); io::Printer printer(output.get(), '^'); @@ -957,12 +1032,12 @@ void GenerateMetadataFile(const FileDescriptor* file, std::string fullname = FilenameToClassname(filename); int lastindex = fullname.find_last_of("\\"); - printer.Print( - "namespace ^name^;\n\n", - "name", fullname.substr(0, lastindex)); - if (lastindex != string::npos) { printer.Print( + "namespace ^name^;\n\n", + "name", fullname.substr(0, lastindex)); + + printer.Print( "class ^name^\n" "{\n", "name", fullname.substr(lastindex + 1)); @@ -980,10 +1055,48 @@ void GenerateMetadataFile(const FileDescriptor* file, printer.Print("}\n\n"); } +template <typename DescriptorType> +void LegacyGenerateClassFile(const FileDescriptor* file, const DescriptorType* desc, + bool is_descriptor, + GeneratorContext* generator_context) { + + std::string filename = LegacyGeneratedClassFileName(desc, is_descriptor); + std::unique_ptr<io::ZeroCopyOutputStream> output( + generator_context->Open(filename)); + io::Printer printer(output.get(), '^'); + + GenerateHead(file, &printer); + + std::string php_namespace = RootPhpNamespace(desc, is_descriptor); + if (php_namespace != "") { + printer.Print( + "namespace ^name^;\n\n", + "name", php_namespace); + } + std::string newname = FullClassName(desc, is_descriptor); + printer.Print("if (false) {\n"); + Indent(&printer); + printer.Print("/**\n"); + printer.Print(" * This class is deprecated. Use ^new^ instead.\n", + "new", newname); + printer.Print(" * @deprecated\n"); + printer.Print(" */\n"); + printer.Print("class ^old^ {}\n", + "old", LegacyGeneratedClassName(desc)); + Outdent(&printer); + printer.Print("}\n"); + printer.Print("class_exists(^new^::class);\n", + "new", GeneratedClassNameImpl(desc)); + printer.Print("@trigger_error('^old^ is deprecated and will be removed in " + "the next major release. Use ^fullname^ instead', E_USER_DEPRECATED);\n\n", + "old", LegacyFullClassName(desc, is_descriptor), + "fullname", newname); +} + void GenerateEnumFile(const FileDescriptor* file, const EnumDescriptor* en, bool is_descriptor, GeneratorContext* generator_context) { - std::string filename = GeneratedEnumFileName(en, is_descriptor); - scoped_ptr<io::ZeroCopyOutputStream> output( + std::string filename = GeneratedClassFileName(en, is_descriptor); + std::unique_ptr<io::ZeroCopyOutputStream> output( generator_context->Open(filename)); io::Printer printer(output.get(), '^'); @@ -992,32 +1105,22 @@ void GenerateEnumFile(const FileDescriptor* file, const EnumDescriptor* en, std::string fullname = FilenameToClassname(filename); int lastindex = fullname.find_last_of("\\"); - if (file->options().has_php_namespace()) { - const string& php_namespace = file->options().php_namespace(); - if (!php_namespace.empty()) { - printer.Print( - "namespace ^name^;\n\n", - "name", php_namespace); - } - } else if (!file->package().empty()) { + if (lastindex != string::npos) { printer.Print( "namespace ^name^;\n\n", "name", fullname.substr(0, lastindex)); } - GenerateEnumDocComment(&printer, en, is_descriptor); - if (lastindex != string::npos) { - printer.Print( - "class ^name^\n" - "{\n", - "name", fullname.substr(lastindex + 1)); - } else { - printer.Print( - "class ^name^\n" - "{\n", - "name", fullname); + fullname = fullname.substr(lastindex + 1); } + + GenerateEnumDocComment(&printer, en, is_descriptor); + + printer.Print( + "class ^name^\n" + "{\n", + "name", fullname); Indent(&printer); for (int i = 0; i < en->value_count(); i++) { @@ -1030,6 +1133,17 @@ void GenerateEnumFile(const FileDescriptor* file, const EnumDescriptor* en, Outdent(&printer); printer.Print("}\n\n"); + + // write legacy file for backwards compatiblity with nested messages and enums + if (en->containing_type() != NULL) { + printer.Print( + "// Adding a class alias for backwards compatibility with the previous class name.\n"); + printer.Print( + "class_alias(^new^::class, \\^old^::class);\n\n", + "new", fullname, + "old", LegacyFullClassName(en, is_descriptor)); + LegacyGenerateClassFile(file, en, is_descriptor, generator_context); + } } void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message, @@ -1041,8 +1155,8 @@ void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message, return; } - std::string filename = GeneratedMessageFileName(message, is_descriptor); - scoped_ptr<io::ZeroCopyOutputStream> output( + std::string filename = GeneratedClassFileName(message, is_descriptor); + std::unique_ptr<io::ZeroCopyOutputStream> output( generator_context->Open(filename)); io::Printer printer(output.get(), '^'); @@ -1051,14 +1165,7 @@ void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message, std::string fullname = FilenameToClassname(filename); int lastindex = fullname.find_last_of("\\"); - if (file->options().has_php_namespace()) { - const string& php_namespace = file->options().php_namespace(); - if (!php_namespace.empty()) { - printer.Print( - "namespace ^name^;\n\n", - "name", php_namespace); - } - } else if (!file->package().empty()) { + if (lastindex != string::npos) { printer.Print( "namespace ^name^;\n\n", "name", fullname.substr(0, lastindex)); @@ -1068,16 +1175,13 @@ void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message, GenerateMessageDocComment(&printer, message, is_descriptor); if (lastindex != string::npos) { - printer.Print( - "class ^name^ extends \\Google\\Protobuf\\Internal\\Message\n" - "{\n", - "name", fullname.substr(lastindex + 1)); - } else { - printer.Print( - "class ^name^ extends \\Google\\Protobuf\\Internal\\Message\n" - "{\n", - "name", fullname); + fullname = fullname.substr(lastindex + 1); } + + printer.Print( + "class ^name^ extends \\Google\\Protobuf\\Internal\\Message\n" + "{\n", + "name", fullname); Indent(&printer); // Field and oneof definitions. @@ -1091,16 +1195,17 @@ void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message, } printer.Print("\n"); + GenerateMessageConstructorDocComment(&printer, message, is_descriptor); printer.Print( - "public function __construct() {\n"); + "public function __construct($data = NULL) {\n"); Indent(&printer); std::string metadata_filename = - GeneratedMetadataFileName(file->name(), is_descriptor); + GeneratedMetadataFileName(file, is_descriptor); std::string metadata_fullname = FilenameToClassname(metadata_filename); printer.Print( "\\^fullname^::initOnce();\n" - "parent::__construct();\n", + "parent::__construct($data);\n", "fullname", metadata_fullname); Outdent(&printer); @@ -1128,6 +1233,17 @@ void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message, Outdent(&printer); printer.Print("}\n\n"); + // write legacy file for backwards compatiblity with nested messages and enums + if (message->containing_type() != NULL) { + printer.Print( + "// Adding a class alias for backwards compatibility with the previous class name.\n"); + printer.Print( + "class_alias(^new^::class, \\^old^::class);\n\n", + "new", fullname, + "old", LegacyFullClassName(message, is_descriptor)); + LegacyGenerateClassFile(file, message, is_descriptor, generator_context); + } + // Nested messages and enums. for (int i = 0; i < message->nested_type_count(); i++) { GenerateMessageFile(file, message->nested_type(i), is_descriptor, @@ -1143,7 +1259,7 @@ void GenerateServiceFile(const FileDescriptor* file, const ServiceDescriptor* service, bool is_descriptor, GeneratorContext* generator_context) { std::string filename = GeneratedServiceFileName(service, is_descriptor); - scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( generator_context->Open(filename)); io::Printer printer(output.get(), '^'); @@ -1152,14 +1268,9 @@ void GenerateServiceFile(const FileDescriptor* file, std::string fullname = FilenameToClassname(filename); int lastindex = fullname.find_last_of("\\"); - if (file->options().has_php_namespace()) { - const string& php_namespace = file->options().php_namespace(); - if (!php_namespace.empty()) { - printer.Print( - "namespace ^name^;\n\n", - "name", php_namespace); - } - } else if (!file->package().empty()) { + if (!file->options().php_namespace().empty() || + (!file->options().has_php_namespace() && !file->package().empty()) || + lastindex != string::npos) { printer.Print( "namespace ^name^;\n\n", "name", fullname.substr(0, lastindex)); @@ -1253,7 +1364,8 @@ static string EscapePhpdoc(const string& input) { } static void GenerateDocCommentBodyForLocation( - io::Printer* printer, const SourceLocation& location) { + io::Printer* printer, const SourceLocation& location, bool trailingNewline, + int indentCount) { string comments = location.leading_comments.empty() ? location.trailing_comments : location.leading_comments; if (!comments.empty()) { @@ -1265,7 +1377,7 @@ static void GenerateDocCommentBodyForLocation( // HTML-escape them so that they don't accidentally close the doc comment. comments = EscapePhpdoc(comments); - vector<string> lines = Split(comments, "\n"); + std::vector<string> lines = Split(comments, "\n"); while (!lines.empty() && lines.back().empty()) { lines.pop_back(); } @@ -1274,14 +1386,16 @@ static void GenerateDocCommentBodyForLocation( // Most lines should start with a space. Watch out for lines that start // with a /, since putting that right after the leading asterisk will // close the comment. - if (!lines[i].empty() && lines[i][0] == '/') { + if (indentCount == 0 && !lines[i].empty() && lines[i][0] == '/') { printer->Print(" * ^line^\n", "line", lines[i]); } else { - printer->Print(" *^line^\n", "line", lines[i]); + std::string indent = std::string(indentCount, ' '); + printer->Print(" *^ind^^line^\n", "ind", indent, "line", lines[i]); } } - printer->Print( - " *\n"); + if (trailingNewline) { + printer->Print(" *\n"); + } } } @@ -1290,7 +1404,7 @@ static void GenerateDocCommentBody( io::Printer* printer, const DescriptorType* descriptor) { SourceLocation location; if (descriptor->GetSourceLocation(&location)) { - GenerateDocCommentBodyForLocation(printer, location); + GenerateDocCommentBodyForLocation(printer, location, true, 0); } } @@ -1312,10 +1426,41 @@ void GenerateMessageDocComment(io::Printer* printer, printer->Print( " * Generated from protobuf message <code>^messagename^</code>\n" " */\n", - "fullname", EscapePhpdoc(PhpName(message->full_name(), is_descriptor)), + "fullname", EscapePhpdoc(FullClassName(message, is_descriptor)), "messagename", EscapePhpdoc(message->full_name())); } +void GenerateMessageConstructorDocComment(io::Printer* printer, + const Descriptor* message, + int is_descriptor) { + // In theory we should have slightly different comments for setters, getters, + // etc., but in practice everyone already knows the difference between these + // so it's redundant information. + + // We start the comment with the main body based on the comments from the + // .proto file (if present). We then end with the field declaration, e.g.: + // optional string foo = 5; + // If the field is a group, the debug string might end with {. + printer->Print("/**\n"); + printer->Print(" * Constructor.\n"); + printer->Print(" *\n"); + printer->Print(" * @param array $data {\n"); + printer->Print(" * Optional. Data for populating the Message object.\n"); + printer->Print(" *\n"); + for (int i = 0; i < message->field_count(); i++) { + const FieldDescriptor* field = message->field(i); + printer->Print(" * @type ^php_type^ $^var^\n", + "php_type", PhpSetterTypeName(field, is_descriptor), + "var", field->name()); + SourceLocation location; + if (field->GetSourceLocation(&location)) { + GenerateDocCommentBodyForLocation(printer, location, false, 10); + } + } + printer->Print(" * }\n"); + printer->Print(" */\n"); +} + void GenerateServiceDocComment(io::Printer* printer, const ServiceDescriptor* service) { printer->Print("/**\n"); @@ -1357,9 +1502,9 @@ void GenerateEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_, printer->Print("/**\n"); GenerateDocCommentBody(printer, enum_); printer->Print( - " * Protobuf enum <code>^fullname^</code>\n" + " * Protobuf type <code>^fullname^</code>\n" " */\n", - "fullname", EscapePhpdoc(PhpName(enum_->full_name(), is_descriptor))); + "fullname", EscapePhpdoc(enum_->full_name())); } void GenerateEnumValueDocComment(io::Printer* printer, @@ -1412,31 +1557,6 @@ bool Generator::Generate(const FileDescriptor* file, const string& parameter, return true; } -std::string GeneratedClassName(const Descriptor* desc) { - std::string classname = desc->name(); - const Descriptor* containing = desc->containing_type(); - while (containing != NULL) { - classname = containing->name() + '_' + classname; - containing = containing->containing_type(); - } - return ClassNamePrefix(classname, desc) + classname; -} - -std::string GeneratedClassName(const EnumDescriptor* desc) { - std::string classname = desc->name(); - const Descriptor* containing = desc->containing_type(); - while (containing != NULL) { - classname = containing->name() + '_' + classname; - containing = containing->containing_type(); - } - return ClassNamePrefix(classname, desc) + classname; -} - -std::string GeneratedClassName(const ServiceDescriptor* desc) { - std::string classname = desc->name(); - return ClassNamePrefix(classname, desc) + classname; -} - } // namespace php } // namespace compiler } // namespace protobuf diff --git a/src/google/protobuf/compiler/php/php_generator.h b/src/google/protobuf/compiler/php/php_generator.h index 67e70bc7..b851d9b4 100644 --- a/src/google/protobuf/compiler/php/php_generator.h +++ b/src/google/protobuf/compiler/php/php_generator.h @@ -48,15 +48,17 @@ class LIBPROTOC_EXPORT Generator const string& parameter, GeneratorContext* generator_context, string* error) const; - }; // 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/compiler/plugin.cc b/src/google/protobuf/compiler/plugin.cc index bde3d798..9c1c757c 100644 --- a/src/google/protobuf/compiler/plugin.cc +++ b/src/google/protobuf/compiler/plugin.cc @@ -45,8 +45,8 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/compiler/plugin.pb.h> #include <google/protobuf/compiler/code_generator.h> -#include <google/protobuf/descriptor.h> #include <google/protobuf/io/zero_copy_stream_impl.h> +#include <google/protobuf/descriptor.h> #include <google/protobuf/stubs/io_win32.h> diff --git a/src/google/protobuf/compiler/plugin.pb.cc b/src/google/protobuf/compiler/plugin.pb.cc index d13ad2b3..20aa82c7 100644 --- a/src/google/protobuf/compiler/plugin.pb.cc +++ b/src/google/protobuf/compiler/plugin.pb.cc @@ -7,7 +7,6 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> -#include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> @@ -19,6 +18,14 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + +namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_CodeGeneratorResponse_File; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Version; +} // namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto +namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<6> scc_info_FileDescriptorProto; +} // namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto namespace google { namespace protobuf { namespace compiler { @@ -46,14 +53,9 @@ class CodeGeneratorResponseDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto { -void InitDefaultsVersionImpl() { +static void InitDefaultsVersion() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::compiler::_Version_default_instance_; new (ptr) ::google::protobuf::compiler::Version(); @@ -62,21 +64,12 @@ void InitDefaultsVersionImpl() { ::google::protobuf::compiler::Version::InitAsDefaultInstance(); } -void InitDefaultsVersion() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsVersionImpl); -} +LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Version = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsVersion}, {}}; -void InitDefaultsCodeGeneratorRequestImpl() { +static void InitDefaultsCodeGeneratorRequest() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto(); - protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsVersion(); { void* ptr = &::google::protobuf::compiler::_CodeGeneratorRequest_default_instance_; new (ptr) ::google::protobuf::compiler::CodeGeneratorRequest(); @@ -85,19 +78,14 @@ void InitDefaultsCodeGeneratorRequestImpl() { ::google::protobuf::compiler::CodeGeneratorRequest::InitAsDefaultInstance(); } -void InitDefaultsCodeGeneratorRequest() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsCodeGeneratorRequestImpl); -} +LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<2> scc_info_CodeGeneratorRequest = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsCodeGeneratorRequest}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base, + &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_Version.base,}}; -void InitDefaultsCodeGeneratorResponse_FileImpl() { +static void InitDefaultsCodeGeneratorResponse_File() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::compiler::_CodeGeneratorResponse_File_default_instance_; new (ptr) ::google::protobuf::compiler::CodeGeneratorResponse_File(); @@ -106,20 +94,12 @@ void InitDefaultsCodeGeneratorResponse_FileImpl() { ::google::protobuf::compiler::CodeGeneratorResponse_File::InitAsDefaultInstance(); } -void InitDefaultsCodeGeneratorResponse_File() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsCodeGeneratorResponse_FileImpl); -} +LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_CodeGeneratorResponse_File = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCodeGeneratorResponse_File}, {}}; -void InitDefaultsCodeGeneratorResponseImpl() { +static void InitDefaultsCodeGeneratorResponse() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse_File(); { void* ptr = &::google::protobuf::compiler::_CodeGeneratorResponse_default_instance_; new (ptr) ::google::protobuf::compiler::CodeGeneratorResponse(); @@ -128,9 +108,15 @@ void InitDefaultsCodeGeneratorResponseImpl() { ::google::protobuf::compiler::CodeGeneratorResponse::InitAsDefaultInstance(); } -void InitDefaultsCodeGeneratorResponse() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsCodeGeneratorResponseImpl); +LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_CodeGeneratorResponse = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsCodeGeneratorResponse}, { + &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse_File.base,}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_Version.base); + ::google::protobuf::internal::InitSCC(&scc_info_CodeGeneratorRequest.base); + ::google::protobuf::internal::InitSCC(&scc_info_CodeGeneratorResponse_File.base); + ::google::protobuf::internal::InitSCC(&scc_info_CodeGeneratorResponse.base); } ::google::protobuf::Metadata file_level_metadata[4]; @@ -197,17 +183,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::compiler::_CodeGeneratorResponse_default_instance_), }; -void protobuf_AssignDescriptors() { +static void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/compiler/plugin.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/compiler/plugin.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } -void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); +static void protobuf_AssignDescriptorsOnce() { + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -216,7 +201,7 @@ void protobuf_RegisterTypes(const ::std::string&) { ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 4); } -void AddDescriptorsImpl() { +static void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n%google/protobuf/compiler/plugin.proto\022" @@ -244,8 +229,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -271,17 +256,15 @@ const int Version::kSuffixFieldNumber; Version::Version() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsVersion(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_Version.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.compiler.Version) } Version::Version(const Version& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); suffix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_suffix()) { @@ -294,7 +277,6 @@ Version::Version(const Version& from) } void Version::SharedCtor() { - _cached_size_ = 0; suffix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&major_, 0, static_cast<size_t>( reinterpret_cast<char*>(&patch_) - @@ -311,9 +293,7 @@ void Version::SharedDtor() { } void Version::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Version::descriptor() { ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); @@ -321,7 +301,7 @@ const ::google::protobuf::Descriptor* Version::descriptor() { } const Version& Version::default_instance() { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsVersion(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_Version.base); return *internal_default_instance(); } @@ -334,8 +314,7 @@ void Version::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!suffix_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - suffix_.UnsafeMutablePointer()->clear(); + suffix_.ClearNonDefaultToEmptyNoArena(); } if (cached_has_bits & 14u) { ::memset(&major_, 0, static_cast<size_t>( @@ -352,7 +331,7 @@ bool Version::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.compiler.Version) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -555,9 +534,7 @@ size_t Version::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -626,13 +603,13 @@ void Version::Swap(Version* other) { } void Version::InternalSwap(Version* other) { using std::swap; - suffix_.Swap(&other->suffix_); + suffix_.Swap(&other->suffix_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(major_, other->major_); swap(minor_, other->minor_); swap(patch_, other->patch_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Version::GetMetadata() const { @@ -659,9 +636,8 @@ const int CodeGeneratorRequest::kCompilerVersionFieldNumber; CodeGeneratorRequest::CodeGeneratorRequest() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorRequest(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorRequest.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorRequest) } @@ -669,7 +645,6 @@ CodeGeneratorRequest::CodeGeneratorRequest(const CodeGeneratorRequest& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), file_to_generate_(from.file_to_generate_), proto_file_(from.proto_file_) { _internal_metadata_.MergeFrom(from._internal_metadata_); @@ -686,7 +661,6 @@ CodeGeneratorRequest::CodeGeneratorRequest(const CodeGeneratorRequest& from) } void CodeGeneratorRequest::SharedCtor() { - _cached_size_ = 0; parameter_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); compiler_version_ = NULL; } @@ -702,9 +676,7 @@ void CodeGeneratorRequest::SharedDtor() { } void CodeGeneratorRequest::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* CodeGeneratorRequest::descriptor() { ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); @@ -712,7 +684,7 @@ const ::google::protobuf::Descriptor* CodeGeneratorRequest::descriptor() { } const CodeGeneratorRequest& CodeGeneratorRequest::default_instance() { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorRequest(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorRequest.base); return *internal_default_instance(); } @@ -728,8 +700,7 @@ void CodeGeneratorRequest::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!parameter_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - parameter_.UnsafeMutablePointer()->clear(); + parameter_.ClearNonDefaultToEmptyNoArena(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(compiler_version_ != NULL); @@ -746,7 +717,7 @@ bool CodeGeneratorRequest::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorRequest) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -857,7 +828,7 @@ void CodeGeneratorRequest::SerializeWithCachedSizes( // optional .google.protobuf.compiler.Version compiler_version = 3; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, *compiler_version_, output); + 3, this->_internal_compiler_version(), output); } // repeated .google.protobuf.FileDescriptorProto proto_file = 15; @@ -909,7 +880,7 @@ void CodeGeneratorRequest::SerializeWithCachedSizes( if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 3, *compiler_version_, deterministic, target); + 3, this->_internal_compiler_version(), deterministic, target); } // repeated .google.protobuf.FileDescriptorProto proto_file = 15; @@ -973,9 +944,7 @@ size_t CodeGeneratorRequest::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1042,11 +1011,11 @@ void CodeGeneratorRequest::InternalSwap(CodeGeneratorRequest* other) { using std::swap; file_to_generate_.InternalSwap(CastToBase(&other->file_to_generate_)); CastToBase(&proto_file_)->InternalSwap(CastToBase(&other->proto_file_)); - parameter_.Swap(&other->parameter_); + parameter_.Swap(&other->parameter_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(compiler_version_, other->compiler_version_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata CodeGeneratorRequest::GetMetadata() const { @@ -1067,17 +1036,15 @@ const int CodeGeneratorResponse_File::kContentFieldNumber; CodeGeneratorResponse_File::CodeGeneratorResponse_File() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse_File(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse_File.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorResponse.File) } CodeGeneratorResponse_File::CodeGeneratorResponse_File(const CodeGeneratorResponse_File& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { @@ -1095,7 +1062,6 @@ CodeGeneratorResponse_File::CodeGeneratorResponse_File(const CodeGeneratorRespon } void CodeGeneratorResponse_File::SharedCtor() { - _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); insertion_point_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); content_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -1113,9 +1079,7 @@ void CodeGeneratorResponse_File::SharedDtor() { } void CodeGeneratorResponse_File::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* CodeGeneratorResponse_File::descriptor() { ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1123,7 +1087,7 @@ const ::google::protobuf::Descriptor* CodeGeneratorResponse_File::descriptor() { } const CodeGeneratorResponse_File& CodeGeneratorResponse_File::default_instance() { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse_File(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse_File.base); return *internal_default_instance(); } @@ -1137,16 +1101,13 @@ void CodeGeneratorResponse_File::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 7u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_.UnsafeMutablePointer()->clear(); + name_.ClearNonDefaultToEmptyNoArena(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(!insertion_point_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - insertion_point_.UnsafeMutablePointer()->clear(); + insertion_point_.ClearNonDefaultToEmptyNoArena(); } if (cached_has_bits & 0x00000004u) { - GOOGLE_DCHECK(!content_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - content_.UnsafeMutablePointer()->clear(); + content_.ClearNonDefaultToEmptyNoArena(); } } _has_bits_.Clear(); @@ -1159,7 +1120,7 @@ bool CodeGeneratorResponse_File::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorResponse.File) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1357,9 +1318,7 @@ size_t CodeGeneratorResponse_File::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1426,12 +1385,14 @@ void CodeGeneratorResponse_File::Swap(CodeGeneratorResponse_File* other) { } void CodeGeneratorResponse_File::InternalSwap(CodeGeneratorResponse_File* other) { using std::swap; - name_.Swap(&other->name_); - insertion_point_.Swap(&other->insertion_point_); - content_.Swap(&other->content_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + insertion_point_.Swap(&other->insertion_point_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + content_.Swap(&other->content_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata CodeGeneratorResponse_File::GetMetadata() const { @@ -1451,9 +1412,8 @@ const int CodeGeneratorResponse::kFileFieldNumber; CodeGeneratorResponse::CodeGeneratorResponse() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorResponse) } @@ -1461,7 +1421,6 @@ CodeGeneratorResponse::CodeGeneratorResponse(const CodeGeneratorResponse& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), file_(from.file_) { _internal_metadata_.MergeFrom(from._internal_metadata_); error_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -1472,7 +1431,6 @@ CodeGeneratorResponse::CodeGeneratorResponse(const CodeGeneratorResponse& from) } void CodeGeneratorResponse::SharedCtor() { - _cached_size_ = 0; error_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } @@ -1486,9 +1444,7 @@ void CodeGeneratorResponse::SharedDtor() { } void CodeGeneratorResponse::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* CodeGeneratorResponse::descriptor() { ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1496,7 +1452,7 @@ const ::google::protobuf::Descriptor* CodeGeneratorResponse::descriptor() { } const CodeGeneratorResponse& CodeGeneratorResponse::default_instance() { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse.base); return *internal_default_instance(); } @@ -1510,8 +1466,7 @@ void CodeGeneratorResponse::Clear() { file_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!error_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - error_.UnsafeMutablePointer()->clear(); + error_.ClearNonDefaultToEmptyNoArena(); } _has_bits_.Clear(); _internal_metadata_.Clear(); @@ -1523,7 +1478,7 @@ bool CodeGeneratorResponse::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorResponse) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1671,9 +1626,7 @@ size_t CodeGeneratorResponse::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1731,10 +1684,10 @@ void CodeGeneratorResponse::Swap(CodeGeneratorResponse* other) { void CodeGeneratorResponse::InternalSwap(CodeGeneratorResponse* other) { using std::swap; CastToBase(&file_)->InternalSwap(CastToBase(&other->file_)); - error_.Swap(&other->error_); + error_.Swap(&other->error_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata CodeGeneratorResponse::GetMetadata() const { @@ -1749,16 +1702,16 @@ void CodeGeneratorResponse::InternalSwap(CodeGeneratorResponse* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::Version* Arena::Create< ::google::protobuf::compiler::Version >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::Version* Arena::CreateMaybeMessage< ::google::protobuf::compiler::Version >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::compiler::Version >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorRequest* Arena::Create< ::google::protobuf::compiler::CodeGeneratorRequest >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorRequest >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorRequest >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::Create< ::google::protobuf::compiler::CodeGeneratorResponse_File >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse_File >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorResponse_File >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse* Arena::Create< ::google::protobuf::compiler::CodeGeneratorResponse >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorResponse >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/compiler/plugin.pb.h b/src/google/protobuf/compiler/plugin.pb.h index a6c1300e..5ad6b4d3 100644 --- a/src/google/protobuf/compiler/plugin.pb.h +++ b/src/google/protobuf/compiler/plugin.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/compiler/plugin.proto -#ifndef PROTOBUF_google_2fprotobuf_2fcompiler_2fplugin_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2fcompiler_2fplugin_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto #include <string> @@ -24,6 +24,7 @@ #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> +#include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export @@ -31,6 +32,7 @@ #include <google/protobuf/unknown_field_set.h> #include <google/protobuf/descriptor.pb.h> // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto LIBPROTOC_EXPORT #ifdef major #undef major #endif @@ -49,20 +51,6 @@ struct LIBPROTOC_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOC_EXPORT AddDescriptors(); -void LIBPROTOC_EXPORT InitDefaultsVersionImpl(); -void LIBPROTOC_EXPORT InitDefaultsVersion(); -void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorRequestImpl(); -void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorRequest(); -void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorResponse_FileImpl(); -void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorResponse_File(); -void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorResponseImpl(); -void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorResponse(); -inline void LIBPROTOC_EXPORT InitDefaults() { - InitDefaultsVersion(); - InitDefaultsCodeGeneratorRequest(); - InitDefaultsCodeGeneratorResponse_File(); - InitDefaultsCodeGeneratorResponse(); -} } // namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto namespace google { namespace protobuf { @@ -84,10 +72,10 @@ LIBPROTOC_EXPORT extern VersionDefaultTypeInternal _Version_default_instance_; } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorRequest* Arena::Create< ::google::protobuf::compiler::CodeGeneratorRequest>(Arena*); -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse* Arena::Create< ::google::protobuf::compiler::CodeGeneratorResponse>(Arena*); -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::Create< ::google::protobuf::compiler::CodeGeneratorResponse_File>(Arena*); -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::Version* Arena::Create< ::google::protobuf::compiler::Version>(Arena*); +template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorRequest>(Arena*); +template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorResponse>(Arena*); +template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorResponse_File>(Arena*); +template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::Version* Arena::CreateMaybeMessage<::google::protobuf::compiler::Version>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -137,7 +125,7 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_ return reinterpret_cast<const Version*>( &_Version_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void Swap(Version* other); @@ -147,32 +135,33 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_ // implements Message ---------------------------------------------- - inline Version* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<Version>(NULL); + inline Version* New() const final { + return CreateMaybeMessage<Version>(NULL); } - Version* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<Version>(arena); + Version* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<Version>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Version& from); void MergeFrom(const Version& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Version* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -183,7 +172,7 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_ } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -238,13 +227,12 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_ ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::internal::ArenaStringPtr suffix_; ::google::protobuf::int32 major_; ::google::protobuf::int32 minor_; ::google::protobuf::int32 patch_; friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsVersionImpl(); }; // ------------------------------------------------------------------- @@ -289,7 +277,7 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message return reinterpret_cast<const CodeGeneratorRequest*>( &_CodeGeneratorRequest_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 1; void Swap(CodeGeneratorRequest* other); @@ -299,32 +287,33 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message // implements Message ---------------------------------------------- - inline CodeGeneratorRequest* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<CodeGeneratorRequest>(NULL); + inline CodeGeneratorRequest* New() const final { + return CreateMaybeMessage<CodeGeneratorRequest>(NULL); } - CodeGeneratorRequest* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<CodeGeneratorRequest>(arena); + CodeGeneratorRequest* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<CodeGeneratorRequest>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const CodeGeneratorRequest& from); void MergeFrom(const CodeGeneratorRequest& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(CodeGeneratorRequest* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -335,7 +324,7 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -394,6 +383,9 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message bool has_compiler_version() const; void clear_compiler_version(); static const int kCompilerVersionFieldNumber = 3; + private: + const ::google::protobuf::compiler::Version& _internal_compiler_version() const; + public: const ::google::protobuf::compiler::Version& compiler_version() const; ::google::protobuf::compiler::Version* release_compiler_version(); ::google::protobuf::compiler::Version* mutable_compiler_version(); @@ -408,13 +400,12 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::std::string> file_to_generate_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto > proto_file_; ::google::protobuf::internal::ArenaStringPtr parameter_; ::google::protobuf::compiler::Version* compiler_version_; friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorRequestImpl(); }; // ------------------------------------------------------------------- @@ -459,7 +450,7 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M return reinterpret_cast<const CodeGeneratorResponse_File*>( &_CodeGeneratorResponse_File_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 2; void Swap(CodeGeneratorResponse_File* other); @@ -469,32 +460,33 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M // implements Message ---------------------------------------------- - inline CodeGeneratorResponse_File* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<CodeGeneratorResponse_File>(NULL); + inline CodeGeneratorResponse_File* New() const final { + return CreateMaybeMessage<CodeGeneratorResponse_File>(NULL); } - CodeGeneratorResponse_File* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<CodeGeneratorResponse_File>(arena); + CodeGeneratorResponse_File* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<CodeGeneratorResponse_File>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const CodeGeneratorResponse_File& from); void MergeFrom(const CodeGeneratorResponse_File& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(CodeGeneratorResponse_File* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -505,7 +497,7 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -567,12 +559,11 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::internal::ArenaStringPtr insertion_point_; ::google::protobuf::internal::ArenaStringPtr content_; friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse_FileImpl(); }; // ------------------------------------------------------------------- @@ -617,7 +608,7 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag return reinterpret_cast<const CodeGeneratorResponse*>( &_CodeGeneratorResponse_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 3; void Swap(CodeGeneratorResponse* other); @@ -627,32 +618,33 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag // implements Message ---------------------------------------------- - inline CodeGeneratorResponse* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<CodeGeneratorResponse>(NULL); + inline CodeGeneratorResponse* New() const final { + return CreateMaybeMessage<CodeGeneratorResponse>(NULL); } - CodeGeneratorResponse* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<CodeGeneratorResponse>(arena); + CodeGeneratorResponse* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<CodeGeneratorResponse>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const CodeGeneratorResponse& from); void MergeFrom(const CodeGeneratorResponse& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(CodeGeneratorResponse* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -663,7 +655,7 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -705,11 +697,10 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File > file_; ::google::protobuf::internal::ArenaStringPtr error_; friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponseImpl(); }; // =================================================================== @@ -844,8 +835,11 @@ inline ::std::string* Version::mutable_suffix() { } inline ::std::string* Version::release_suffix() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.Version.suffix) + if (!has_suffix()) { + return NULL; + } clear_has_suffix(); - return suffix_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return suffix_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void Version::set_allocated_suffix(::std::string* suffix) { if (suffix != NULL) { @@ -980,8 +974,11 @@ inline ::std::string* CodeGeneratorRequest::mutable_parameter() { } inline ::std::string* CodeGeneratorRequest::release_parameter() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorRequest.parameter) + if (!has_parameter()) { + return NULL; + } clear_has_parameter(); - return parameter_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return parameter_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void CodeGeneratorRequest::set_allocated_parameter(::std::string* parameter) { if (parameter != NULL) { @@ -1034,6 +1031,9 @@ inline void CodeGeneratorRequest::clear_compiler_version() { if (compiler_version_ != NULL) compiler_version_->Clear(); clear_has_compiler_version(); } +inline const ::google::protobuf::compiler::Version& CodeGeneratorRequest::_internal_compiler_version() const { + return *compiler_version_; +} inline const ::google::protobuf::compiler::Version& CodeGeneratorRequest::compiler_version() const { const ::google::protobuf::compiler::Version* p = compiler_version_; // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.compiler_version) @@ -1050,8 +1050,8 @@ inline ::google::protobuf::compiler::Version* CodeGeneratorRequest::release_comp inline ::google::protobuf::compiler::Version* CodeGeneratorRequest::mutable_compiler_version() { set_has_compiler_version(); if (compiler_version_ == NULL) { - compiler_version_ = ::google::protobuf::Arena::Create< ::google::protobuf::compiler::Version >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::compiler::Version>(GetArenaNoVirtual()); + compiler_version_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.compiler_version) return compiler_version_; @@ -1129,8 +1129,11 @@ inline ::std::string* CodeGeneratorResponse_File::mutable_name() { } inline ::std::string* CodeGeneratorResponse_File::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.name) + if (!has_name()) { + return NULL; + } clear_has_name(); - return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return name_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void CodeGeneratorResponse_File::set_allocated_name(::std::string* name) { if (name != NULL) { @@ -1192,8 +1195,11 @@ inline ::std::string* CodeGeneratorResponse_File::mutable_insertion_point() { } inline ::std::string* CodeGeneratorResponse_File::release_insertion_point() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) + if (!has_insertion_point()) { + return NULL; + } clear_has_insertion_point(); - return insertion_point_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return insertion_point_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void CodeGeneratorResponse_File::set_allocated_insertion_point(::std::string* insertion_point) { if (insertion_point != NULL) { @@ -1255,8 +1261,11 @@ inline ::std::string* CodeGeneratorResponse_File::mutable_content() { } inline ::std::string* CodeGeneratorResponse_File::release_content() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.content) + if (!has_content()) { + return NULL; + } clear_has_content(); - return content_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return content_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void CodeGeneratorResponse_File::set_allocated_content(::std::string* content) { if (content != NULL) { @@ -1322,8 +1331,11 @@ inline ::std::string* CodeGeneratorResponse::mutable_error() { } inline ::std::string* CodeGeneratorResponse::release_error() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.error) + if (!has_error()) { + return NULL; + } clear_has_error(); - return error_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return error_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void CodeGeneratorResponse::set_allocated_error(::std::string* error) { if (error != NULL) { @@ -1383,4 +1395,4 @@ CodeGeneratorResponse::file() const { // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2fcompiler_2fplugin_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto diff --git a/src/google/protobuf/compiler/python/python_generator.cc b/src/google/protobuf/compiler/python/python_generator.cc index 5ca6b4ee..01f28b37 100644 --- a/src/google/protobuf/compiler/python/python_generator.cc +++ b/src/google/protobuf/compiler/python/python_generator.cc @@ -49,9 +49,6 @@ #include <limits> #include <map> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <string> #include <utility> #include <vector> @@ -202,11 +199,6 @@ void PrintTopBoilerplate( "from google.protobuf import service_reflection\n"); } - // Avoid circular imports if this module is descriptor_pb2. - if (!descriptor_proto) { - printer->Print( - "from google.protobuf import descriptor_pb2\n"); - } printer->Print( "# @@protoc_insertion_point(imports)\n\n" "_sym_db = _symbol_database.Default()\n"); @@ -338,7 +330,7 @@ bool Generator::Generate(const FileDescriptor* file, fdp.SerializeToString(&file_descriptor_serialized_); - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename)); + std::unique_ptr<io::ZeroCopyOutputStream> output(context->Open(filename)); GOOGLE_CHECK(output.get()); io::Printer printer(output.get(), '$'); printer_ = &printer; @@ -422,11 +414,13 @@ void Generator::PrintFileDescriptor() const { m["name"] = file_->name(); m["package"] = file_->package(); m["syntax"] = StringifySyntax(file_->syntax()); + m["options"] = OptionsValue(file_->options().SerializeAsString()); const char file_descriptor_template[] = "$descriptor_name$ = _descriptor.FileDescriptor(\n" " name='$name$',\n" " package='$package$',\n" - " syntax='$syntax$',\n"; + " syntax='$syntax$',\n" + " serialized_options=$options$,\n"; printer_->Print(m, file_descriptor_template); printer_->Indent(); printer_->Print( @@ -526,9 +520,9 @@ void Generator::PrintEnum(const EnumDescriptor& enum_descriptor) const { printer_->Outdent(); printer_->Print("],\n"); printer_->Print("containing_type=None,\n"); - printer_->Print("options=$options_value$,\n", + printer_->Print("serialized_options=$options_value$,\n", "options_value", - OptionsValue("EnumOptions", options_string)); + OptionsValue(options_string)); EnumDescriptorProto edp; PrintSerializedPbInterval(enum_descriptor, edp); printer_->Outdent(); @@ -606,13 +600,13 @@ void Generator::PrintServiceDescriptor( m["full_name"] = descriptor.full_name(); m["file"] = kDescriptorKey; m["index"] = SimpleItoa(descriptor.index()); - m["options_value"] = OptionsValue("ServiceOptions", options_string); + m["options_value"] = OptionsValue(options_string); const char required_function_arguments[] = "name='$name$',\n" "full_name='$full_name$',\n" "file=$file$,\n" "index=$index$,\n" - "options=$options_value$,\n"; + "serialized_options=$options_value$,\n"; printer_->Print(m, required_function_arguments); ServiceDescriptorProto sdp; @@ -630,7 +624,7 @@ void Generator::PrintServiceDescriptor( m["serialized_options"] = CEscape(options_string); m["input_type"] = ModuleLevelDescriptorName(*(method->input_type())); m["output_type"] = ModuleLevelDescriptorName(*(method->output_type())); - m["options_value"] = OptionsValue("MethodOptions", options_string); + m["options_value"] = OptionsValue(options_string); printer_->Print("_descriptor.MethodDescriptor(\n"); printer_->Indent(); printer_->Print( @@ -641,7 +635,7 @@ void Generator::PrintServiceDescriptor( "containing_service=None,\n" "input_type=$input_type$,\n" "output_type=$output_type$,\n" - "options=$options_value$,\n"); + "serialized_options=$options_value$,\n"); printer_->Outdent(); printer_->Print("),\n"); } @@ -737,10 +731,10 @@ void Generator::PrintDescriptor(const Descriptor& message_descriptor) const { string options_string; message_descriptor.options().SerializeToString(&options_string); printer_->Print( - "options=$options_value$,\n" + "serialized_options=$options_value$,\n" "is_extendable=$extendable$,\n" "syntax='$syntax$'", - "options_value", OptionsValue("MessageOptions", options_string), + "options_value", OptionsValue(options_string), "extendable", message_descriptor.extension_range_count() > 0 ? "True" : "False", "syntax", StringifySyntax(message_descriptor.file()->syntax())); @@ -765,17 +759,18 @@ void Generator::PrintDescriptor(const Descriptor& message_descriptor) const { m["full_name"] = desc->full_name(); m["index"] = SimpleItoa(desc->index()); string options_string = - OptionsValue("OneofOptions", desc->options().SerializeAsString()); + OptionsValue(desc->options().SerializeAsString()); if (options_string == "None") { - m["options"] = ""; + m["serialized_options"] = ""; } else { - m["options"] = ", options=" + options_string; + m["serialized_options"] = ", serialized_options=" + options_string; } printer_->Print( m, "_descriptor.OneofDescriptor(\n" " name='$name$', full_name='$full_name$',\n" - " index=$index$, containing_type=None, fields=[]$options$),\n"); + " index=$index$, containing_type=None, " + "fields=[]$serialized_options$),\n"); } printer_->Outdent(); printer_->Print("],\n"); @@ -1098,27 +1093,22 @@ void Generator::PrintEnumValueDescriptor( m["name"] = descriptor.name(); m["index"] = SimpleItoa(descriptor.index()); m["number"] = SimpleItoa(descriptor.number()); - m["options"] = OptionsValue("EnumValueOptions", options_string); + m["options"] = OptionsValue(options_string); printer_->Print( m, "_descriptor.EnumValueDescriptor(\n" " name='$name$', index=$index$, number=$number$,\n" - " options=$options$,\n" + " serialized_options=$options$,\n" " type=None)"); } -// Returns a Python expression that calls descriptor._ParseOptions using -// the given descriptor class name and serialized options protobuf string. -string Generator::OptionsValue( - const string& class_name, const string& serialized_options) const { +// Returns a CEscaped string of serialized_options. +string Generator::OptionsValue(const string& serialized_options) const { if (serialized_options.length() == 0 || GeneratingDescriptorProto()) { return "None"; } else { - string full_class_name = "descriptor_pb2." + class_name; -//##!PY25 return "_descriptor._ParseOptions(" + full_class_name + "(), b'" -//##!PY25 + CEscape(serialized_options)+ "')"; - return "_descriptor._ParseOptions(" + full_class_name + "(), _b('" //##PY25 - + CEscape(serialized_options)+ "'))"; //##PY25 +//##!PY25 return "b'('" + CEscape(serialized_options)+ "')"; + return "_b('"+ CEscape(serialized_options) + "')"; //##PY25 } } @@ -1138,7 +1128,7 @@ void Generator::PrintFieldDescriptor( m["has_default_value"] = field.has_default_value() ? "True" : "False"; m["default_value"] = StringifyDefaultValue(field); m["is_extension"] = is_extension ? "True" : "False"; - m["options"] = OptionsValue("FieldOptions", options_string); + m["serialized_options"] = OptionsValue(options_string); m["json_name"] = field.has_json_name() ? ", json_name='" + field.json_name() + "'": ""; // We always set message_type and enum_type to None at this point, and then @@ -1151,7 +1141,7 @@ void Generator::PrintFieldDescriptor( " has_default_value=$has_default_value$, default_value=$default_value$,\n" " message_type=None, enum_type=None, containing_type=None,\n" " is_extension=$is_extension$, extension_scope=None,\n" - " options=$options$$json_name$, file=DESCRIPTOR)"; + " serialized_options=$serialized_options$$json_name$, file=DESCRIPTOR)"; printer_->Print(m, field_descriptor_decl); } @@ -1280,23 +1270,18 @@ namespace { void PrintDescriptorOptionsFixingCode(const string& descriptor, const string& options, io::Printer* printer) { - // TODO(xiaofeng): I have added a method _SetOptions() to DescriptorBase - // in proto2 python runtime but it couldn't be used here because appengine - // uses a snapshot version of the library in which the new method is not - // yet present. After appengine has synced their runtime library, the code - // below should be cleaned up to use _SetOptions(). + // Reset the _options to None thus DescriptorBase.GetOptions() can + // parse _options again after extensions are registered. printer->Print( - "$descriptor$.has_options = True\n" - "$descriptor$._options = $options$\n", - "descriptor", descriptor, "options", options); + "$descriptor$._options = None\n", + "descriptor", descriptor); } } // namespace // Prints expressions that set the options field of all descriptors. void Generator::FixAllDescriptorOptions() const { // Prints an expression that sets the file descriptor's options. - string file_options = OptionsValue( - "FileOptions", file_->options().SerializeAsString()); + string file_options = OptionsValue(file_->options().SerializeAsString()); if (file_options != "None") { PrintDescriptorOptionsFixingCode(kDescriptorKey, file_options, printer_); } @@ -1318,8 +1303,7 @@ void Generator::FixAllDescriptorOptions() const { } void Generator::FixOptionsForOneof(const OneofDescriptor& oneof) const { - string oneof_options = OptionsValue( - "OneofOptions", oneof.options().SerializeAsString()); + string oneof_options = OptionsValue(oneof.options().SerializeAsString()); if (oneof_options != "None") { string oneof_name = strings::Substitute( "$0.$1['$2']", @@ -1334,14 +1318,14 @@ void Generator::FixOptionsForOneof(const OneofDescriptor& oneof) const { void Generator::FixOptionsForEnum(const EnumDescriptor& enum_descriptor) const { string descriptor_name = ModuleLevelDescriptorName(enum_descriptor); string enum_options = OptionsValue( - "EnumOptions", enum_descriptor.options().SerializeAsString()); + enum_descriptor.options().SerializeAsString()); if (enum_options != "None") { PrintDescriptorOptionsFixingCode(descriptor_name, enum_options, printer_); } for (int i = 0; i < enum_descriptor.value_count(); ++i) { const EnumValueDescriptor& value_descriptor = *enum_descriptor.value(i); string value_options = OptionsValue( - "EnumValueOptions", value_descriptor.options().SerializeAsString()); + value_descriptor.options().SerializeAsString()); if (value_options != "None") { PrintDescriptorOptionsFixingCode( StringPrintf("%s.values_by_name[\"%s\"]", descriptor_name.c_str(), @@ -1355,8 +1339,7 @@ void Generator::FixOptionsForEnum(const EnumDescriptor& enum_descriptor) const { // extensions). void Generator::FixOptionsForField( const FieldDescriptor& field) const { - string field_options = OptionsValue( - "FieldOptions", field.options().SerializeAsString()); + string field_options = OptionsValue(field.options().SerializeAsString()); if (field_options != "None") { string field_name; if (field.is_extension()) { @@ -1402,7 +1385,7 @@ void Generator::FixOptionsForMessage(const Descriptor& descriptor) const { } // Message option for this message. string message_options = OptionsValue( - "MessageOptions", descriptor.options().SerializeAsString()); + descriptor.options().SerializeAsString()); if (message_options != "None") { string descriptor_name = ModuleLevelDescriptorName(descriptor); PrintDescriptorOptionsFixingCode(descriptor_name, diff --git a/src/google/protobuf/compiler/python/python_generator.h b/src/google/protobuf/compiler/python/python_generator.h index 2b5a028b..8e4050de 100644 --- a/src/google/protobuf/compiler/python/python_generator.h +++ b/src/google/protobuf/compiler/python/python_generator.h @@ -135,8 +135,7 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { const ServiceDescriptor& descriptor) const; void PrintEnumValueDescriptor(const EnumValueDescriptor& descriptor) const; - string OptionsValue(const string& class_name, - const string& serialized_options) const; + string OptionsValue(const string& serialized_options) const; bool GeneratingDescriptorProto() const; template <typename DescriptorT> diff --git a/src/google/protobuf/compiler/python/python_plugin_unittest.cc b/src/google/protobuf/compiler/python/python_plugin_unittest.cc index 34f857fd..2f096808 100644 --- a/src/google/protobuf/compiler/python/python_plugin_unittest.cc +++ b/src/google/protobuf/compiler/python/python_plugin_unittest.cc @@ -35,9 +35,6 @@ // worth. #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/compiler/python/python_generator.h> #include <google/protobuf/compiler/command_line_interface.h> @@ -74,7 +71,7 @@ class TestGenerator : public CodeGenerator { void TryInsert(const string& filename, const string& insertion_point, GeneratorContext* context) const { - google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( context->OpenForInsert(filename, insertion_point)); io::Printer printer(output.get(), '$'); printer.Print("// inserted $name$\n", "name", insertion_point); diff --git a/src/google/protobuf/compiler/ruby/ruby_generator.cc b/src/google/protobuf/compiler/ruby/ruby_generator.cc index fbe3b4cb..bd737c02 100644 --- a/src/google/protobuf/compiler/ruby/ruby_generator.cc +++ b/src/google/protobuf/compiler/ruby/ruby_generator.cc @@ -39,8 +39,6 @@ #include <google/protobuf/compiler/ruby/ruby_generator.h> -using google::protobuf::internal::scoped_ptr; - namespace google { namespace protobuf { namespace compiler { @@ -339,9 +337,20 @@ void GenerateEnumAssignment( } int GeneratePackageModules( - std::string package_name, + const FileDescriptor* file, google::protobuf::io::Printer* printer) { int levels = 0; + bool need_change_to_module; + std::string package_name; + + if (file->options().has_ruby_package()) { + package_name = file->options().ruby_package(); + need_change_to_module = false; + } else { + package_name = file->package(); + need_change_to_module = true; + } + while (!package_name.empty()) { size_t dot_index = package_name.find("."); string component; @@ -352,7 +361,9 @@ int GeneratePackageModules( component = package_name.substr(0, dot_index); package_name = package_name.substr(dot_index + 1); } - component = PackageToModule(component); + if (need_change_to_module) { + component = PackageToModule(component); + } printer->Print( "module $name$\n", "name", component); @@ -464,7 +475,7 @@ bool GenerateFile(const FileDescriptor* file, io::Printer* printer, printer->Print( "end\n\n"); - int levels = GeneratePackageModules(file->package(), printer); + int levels = GeneratePackageModules(file, printer); for (int i = 0; i < file->message_type_count(); i++) { GenerateMessageAssignment("", file->message_type(i), printer); } @@ -488,7 +499,7 @@ bool Generator::Generate( return false; } - scoped_ptr<io::ZeroCopyOutputStream> output( + std::unique_ptr<io::ZeroCopyOutputStream> output( generator_context->Open(GetOutputFilename(file->name()))); io::Printer printer(output.get(), '$'); diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index 9d48bfba..dae24f9e 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -38,24 +38,22 @@ #include <limits> #include <map> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <set> #include <string> #include <vector> +#include <google/protobuf/stubs/casts.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/mutex.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/stubs/stringprintf.h> #include <google/protobuf/stubs/strutil.h> +#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/strtod.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/tokenizer.h> #include <google/protobuf/io/zero_copy_stream_impl.h> -#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/descriptor_database.h> #include <google/protobuf/dynamic_message.h> @@ -65,6 +63,7 @@ #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/substitute.h> + #include <google/protobuf/stubs/map_util.h> #include <google/protobuf/stubs/stl_util.h> @@ -347,14 +346,14 @@ class PrefixRemover { } if (ascii_tolower(str[i]) != prefix_[j++]) { - return str.as_string(); + return string(str); } } // If we didn't make it through the prefix, we've failed to strip the // prefix. if (j < prefix_.size()) { - return str.as_string(); + return string(str); } // Skip underscores between prefix and further characters. @@ -364,12 +363,12 @@ class PrefixRemover { // Enum label can't be the empty string. if (i == str.size()) { - return str.as_string(); + return string(str); } // We successfully stripped the prefix. str.remove_prefix(i); - return str.as_string(); + return string(str); } private: @@ -407,9 +406,10 @@ typedef std::pair<const EnumDescriptor*, int> EnumIntPair; template<typename PairType> struct PointerIntegerPairHash { size_t operator()(const PairType& p) const { - // FIXME(kenton): What is the best way to compute this hash? I have - // no idea! This seems a bit better than an XOR. - return reinterpret_cast<intptr_t>(p.first) * ((1 << 16) - 1) + p.second; + static const size_t prime1 = 16777499; + static const size_t prime2 = 16777619; + return reinterpret_cast<size_t>(p.first) * prime1 ^ + static_cast<size_t>(p.second) * prime2; } #ifdef _MSC_VER @@ -425,11 +425,10 @@ struct PointerIntegerPairHash { struct PointerStringPairHash { size_t operator()(const PointerStringPair& p) const { - // FIXME(kenton): What is the best way to compute this hash? I have - // no idea! This seems a bit better than an XOR. + static const size_t prime = 16777619; hash<const char*> cstring_hash; - return reinterpret_cast<intptr_t>(p.first) * ((1 << 16) - 1) + - cstring_hash(p.second); + return reinterpret_cast<size_t>(p.first) * prime ^ + static_cast<size_t>(cstring_hash(p.second)); } #ifdef _MSC_VER @@ -1802,6 +1801,15 @@ FileDescriptor::FindExtensionByCamelcaseName(const string& key) const { } } +void Descriptor::ExtensionRange::CopyTo( + DescriptorProto_ExtensionRange* proto) const { + proto->set_start(this->start); + proto->set_end(this->end); + if (options_ != &google::protobuf::ExtensionRangeOptions::default_instance()) { + *proto->mutable_options() = *options_; + } +} + const Descriptor::ExtensionRange* Descriptor::FindExtensionRangeContainingNumber(int number) const { // Linear search should be fine because we don't expect a message to have @@ -2069,13 +2077,7 @@ void Descriptor::CopyTo(DescriptorProto* proto) const { enum_type(i)->CopyTo(proto->add_enum_type()); } for (int i = 0; i < extension_range_count(); i++) { - DescriptorProto::ExtensionRange* range = proto->add_extension_range(); - range->set_start(extension_range(i)->start); - range->set_end(extension_range(i)->end); - const ExtensionRangeOptions* options = extension_range(i)->options_; - if (options != &ExtensionRangeOptions::default_instance()) { - range->mutable_options()->CopyFrom(*options); - } + extension_range(i)->CopyTo(proto->add_extension_range()); } for (int i = 0; i < extension_count(); i++) { extension(i)->CopyTo(proto->add_extension()); @@ -2306,7 +2308,7 @@ bool RetrieveOptions(int depth, const Message& options, return RetrieveOptionsAssumingRightPool(depth, options, option_entries); } DynamicMessageFactory factory; - google::protobuf::scoped_ptr<Message> dynamic_options( + std::unique_ptr<Message> dynamic_options( factory.GetPrototype(option_descriptor)->New()); if (dynamic_options->ParseFromString(options.SerializeAsString())) { return RetrieveOptionsAssumingRightPool(depth, *dynamic_options, @@ -3116,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; }; @@ -3291,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); @@ -3301,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. @@ -3390,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 @@ -3471,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_; @@ -4088,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 = @@ -4128,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)); } } @@ -4266,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 { @@ -4465,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 @@ -4536,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(), @@ -4916,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); } @@ -4950,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); } } @@ -5003,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(), @@ -5120,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(), @@ -5132,13 +5180,13 @@ void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto, for (int j = i + 1; j < proto.reserved_range_size(); j++) { const EnumDescriptorProto_EnumReservedRange& range2 = proto.reserved_range(j); - if (range1.end() > range2.start() && range2.end() > range1.start()) { + if (range1.end() >= range2.start() && range2.end() >= range1.start()) { AddError(result->full_name(), proto.reserved_range(i), DescriptorPool::ErrorCollector::NUMBER, strings::Substitute("Reserved range $0 to $1 overlaps with " "already-defined range $2 to $3.", - range2.start(), range2.end() - 1, - range1.start(), range1.end() - 1)); + range2.start(), range2.end(), + range1.start(), range1.end())); } } } @@ -5197,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 @@ -5264,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(), @@ -5292,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(); @@ -5661,13 +5712,15 @@ void DescriptorBuilder::CrossLinkField( if (!tables_->AddExtension(field)) { const FieldDescriptor* conflicting_field = tables_->FindExtension(field->containing_type(), field->number()); + string containing_type_name = + field->containing_type() == NULL + ? "unknown" + : field->containing_type()->full_name(); string error_msg = strings::Substitute( "Extension number $0 has already been used in \"$1\" by extension " "\"$2\" defined in $3.", - field->number(), - field->containing_type()->full_name(), - conflicting_field->full_name(), - conflicting_field->file()->name()); + field->number(), containing_type_name, + conflicting_field->full_name(), conflicting_field->file()->name()); // Conflicting extension numbers should be an error. However, before // turning this into an error we need to fix all existing broken // protos first. @@ -6262,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()-> @@ -6272,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; @@ -6312,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 @@ -6358,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) { @@ -6420,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(); + } } } } @@ -6453,10 +6519,9 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( return false; // ExamineIfOptionIsSet() already added the error. } - // First set the value on the UnknownFieldSet corresponding to the // innermost message. - google::protobuf::scoped_ptr<UnknownFieldSet> unknown_fields(new UnknownFieldSet()); + std::unique_ptr<UnknownFieldSet> unknown_fields(new UnknownFieldSet()); if (!SetOptionValue(field, unknown_fields.get())) { return false; // SetOptionValue() already added the error. } @@ -6466,7 +6531,7 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( for (std::vector<const FieldDescriptor*>::reverse_iterator iter = intermediate_fields.rbegin(); iter != intermediate_fields.rend(); ++iter) { - google::protobuf::scoped_ptr<UnknownFieldSet> parent_unknown_fields( + std::unique_ptr<UnknownFieldSet> parent_unknown_fields( new UnknownFieldSet()); switch ((*iter)->type()) { case FieldDescriptor::TYPE_MESSAGE: { @@ -6499,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 = @@ -6854,7 +7020,7 @@ bool DescriptorBuilder::OptionInterpreter::SetAggregateOption( } const Descriptor* type = option_field->message_type(); - google::protobuf::scoped_ptr<Message> dynamic(dynamic_factory_.GetPrototype(type)->New()); + std::unique_ptr<Message> dynamic(dynamic_factory_.GetPrototype(type)->New()); GOOGLE_CHECK(dynamic.get() != NULL) << "Could not create an instance of " << option_field->DebugString(); diff --git a/src/google/protobuf/descriptor.h b/src/google/protobuf/descriptor.h index 5f5159a8..115d4ddc 100644 --- a/src/google/protobuf/descriptor.h +++ b/src/google/protobuf/descriptor.h @@ -55,9 +55,6 @@ #define GOOGLE_PROTOBUF_DESCRIPTOR_H__ #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <set> #include <string> #include <vector> @@ -87,6 +84,7 @@ class DescriptorPool; // Defined in descriptor.proto class DescriptorProto; +class DescriptorProto_ExtensionRange; class FieldDescriptorProto; class OneofDescriptorProto; class EnumDescriptorProto; @@ -340,6 +338,9 @@ class LIBPROTOBUF_EXPORT Descriptor { struct ExtensionRange { typedef ExtensionRangeOptions OptionsType; + // See Descriptor::CopyTo(). + void CopyTo(DescriptorProto_ExtensionRange* proto) const; + int start; // inclusive int end; // exclusive @@ -1802,7 +1803,7 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // This class contains a lot of hash maps with complicated types that // we'd like to keep out of the header. class Tables; - google::protobuf::scoped_ptr<Tables> tables_; + std::unique_ptr<Tables> tables_; bool enforce_dependencies_; bool lazily_build_dependencies_; diff --git a/src/google/protobuf/descriptor.pb.cc b/src/google/protobuf/descriptor.pb.cc index c8362376..2ccf189c 100644 --- a/src/google/protobuf/descriptor.pb.cc +++ b/src/google/protobuf/descriptor.pb.cc @@ -7,7 +7,6 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> -#include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> @@ -19,6 +18,34 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + +namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_DescriptorProto_ReservedRange; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_EnumDescriptorProto_EnumReservedRange; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_GeneratedCodeInfo_Annotation; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SourceCodeInfo_Location; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_UninterpretedOption_NamePart; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_DescriptorProto_ExtensionRange; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumOptions; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueDescriptorProto; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueOptions; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_ExtensionRangeOptions; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FieldDescriptorProto; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FieldOptions; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FileOptions; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_MessageOptions; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_MethodDescriptorProto; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_MethodOptions; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_OneofDescriptorProto; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_OneofOptions; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_ServiceOptions; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_SourceCodeInfo; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_UninterpretedOption; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_ServiceDescriptorProto; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<3> scc_info_EnumDescriptorProto; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<6> scc_info_DescriptorProto; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<6> scc_info_FileDescriptorProto; +} // namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto namespace google { namespace protobuf { class FileDescriptorSetDefaultTypeInternal { @@ -159,15 +186,9 @@ class GeneratedCodeInfoDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto { -void InitDefaultsFileDescriptorSetImpl() { +static void InitDefaultsFileDescriptorSet() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto(); { void* ptr = &::google::protobuf::_FileDescriptorSet_default_instance_; new (ptr) ::google::protobuf::FileDescriptorSet(); @@ -176,25 +197,13 @@ void InitDefaultsFileDescriptorSetImpl() { ::google::protobuf::FileDescriptorSet::InitAsDefaultInstance(); } -void InitDefaultsFileDescriptorSet() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFileDescriptorSetImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FileDescriptorSet = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFileDescriptorSet}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base,}}; -void InitDefaultsFileDescriptorProtoImpl() { +static void InitDefaultsFileDescriptorProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProto(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptions(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo(); { void* ptr = &::google::protobuf::_FileDescriptorProto_default_instance_; new (ptr) ::google::protobuf::FileDescriptorProto(); @@ -203,20 +212,18 @@ void InitDefaultsFileDescriptorProtoImpl() { ::google::protobuf::FileDescriptorProto::InitAsDefaultInstance(); } -void InitDefaultsFileDescriptorProto() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFileDescriptorProtoImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<6> scc_info_FileDescriptorProto = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 6, InitDefaultsFileDescriptorProto}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base,}}; -void InitDefaultsDescriptorProto_ExtensionRangeImpl() { +static void InitDefaultsDescriptorProto_ExtensionRange() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptions(); { void* ptr = &::google::protobuf::_DescriptorProto_ExtensionRange_default_instance_; new (ptr) ::google::protobuf::DescriptorProto_ExtensionRange(); @@ -225,19 +232,13 @@ void InitDefaultsDescriptorProto_ExtensionRangeImpl() { ::google::protobuf::DescriptorProto_ExtensionRange::InitAsDefaultInstance(); } -void InitDefaultsDescriptorProto_ExtensionRange() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDescriptorProto_ExtensionRangeImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_DescriptorProto_ExtensionRange = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsDescriptorProto_ExtensionRange}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base,}}; -void InitDefaultsDescriptorProto_ReservedRangeImpl() { +static void InitDefaultsDescriptorProto_ReservedRange() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_DescriptorProto_ReservedRange_default_instance_; new (ptr) ::google::protobuf::DescriptorProto_ReservedRange(); @@ -246,25 +247,12 @@ void InitDefaultsDescriptorProto_ReservedRangeImpl() { ::google::protobuf::DescriptorProto_ReservedRange::InitAsDefaultInstance(); } -void InitDefaultsDescriptorProto_ReservedRange() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDescriptorProto_ReservedRangeImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_DescriptorProto_ReservedRange = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDescriptorProto_ReservedRange}, {}}; -void InitDefaultsDescriptorProtoImpl() { +static void InitDefaultsDescriptorProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRange(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProto(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptions(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRange(); { void* ptr = &::google::protobuf::_DescriptorProto_default_instance_; new (ptr) ::google::protobuf::DescriptorProto(); @@ -273,20 +261,18 @@ void InitDefaultsDescriptorProtoImpl() { ::google::protobuf::DescriptorProto::InitAsDefaultInstance(); } -void InitDefaultsDescriptorProto() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDescriptorProtoImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<6> scc_info_DescriptorProto = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 6, InitDefaultsDescriptorProto}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ExtensionRange.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofDescriptorProto.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ReservedRange.base,}}; -void InitDefaultsExtensionRangeOptionsImpl() { +static void InitDefaultsExtensionRangeOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); { void* ptr = &::google::protobuf::_ExtensionRangeOptions_default_instance_; new (ptr) ::google::protobuf::ExtensionRangeOptions(); @@ -295,20 +281,13 @@ void InitDefaultsExtensionRangeOptionsImpl() { ::google::protobuf::ExtensionRangeOptions::InitAsDefaultInstance(); } -void InitDefaultsExtensionRangeOptions() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsExtensionRangeOptionsImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_ExtensionRangeOptions = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsExtensionRangeOptions}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; -void InitDefaultsFieldDescriptorProtoImpl() { +static void InitDefaultsFieldDescriptorProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptions(); { void* ptr = &::google::protobuf::_FieldDescriptorProto_default_instance_; new (ptr) ::google::protobuf::FieldDescriptorProto(); @@ -317,20 +296,13 @@ void InitDefaultsFieldDescriptorProtoImpl() { ::google::protobuf::FieldDescriptorProto::InitAsDefaultInstance(); } -void InitDefaultsFieldDescriptorProto() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFieldDescriptorProtoImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FieldDescriptorProto = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFieldDescriptorProto}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base,}}; -void InitDefaultsOneofDescriptorProtoImpl() { +static void InitDefaultsOneofDescriptorProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptions(); { void* ptr = &::google::protobuf::_OneofDescriptorProto_default_instance_; new (ptr) ::google::protobuf::OneofDescriptorProto(); @@ -339,19 +311,13 @@ void InitDefaultsOneofDescriptorProtoImpl() { ::google::protobuf::OneofDescriptorProto::InitAsDefaultInstance(); } -void InitDefaultsOneofDescriptorProto() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsOneofDescriptorProtoImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_OneofDescriptorProto = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsOneofDescriptorProto}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base,}}; -void InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl() { +static void InitDefaultsEnumDescriptorProto_EnumReservedRange() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_EnumDescriptorProto_EnumReservedRange_default_instance_; new (ptr) ::google::protobuf::EnumDescriptorProto_EnumReservedRange(); @@ -360,22 +326,12 @@ void InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl() { ::google::protobuf::EnumDescriptorProto_EnumReservedRange::InitAsDefaultInstance(); } -void InitDefaultsEnumDescriptorProto_EnumReservedRange() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_EnumDescriptorProto_EnumReservedRange = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsEnumDescriptorProto_EnumReservedRange}, {}}; -void InitDefaultsEnumDescriptorProtoImpl() { +static void InitDefaultsEnumDescriptorProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProto(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptions(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRange(); { void* ptr = &::google::protobuf::_EnumDescriptorProto_default_instance_; new (ptr) ::google::protobuf::EnumDescriptorProto(); @@ -384,20 +340,15 @@ void InitDefaultsEnumDescriptorProtoImpl() { ::google::protobuf::EnumDescriptorProto::InitAsDefaultInstance(); } -void InitDefaultsEnumDescriptorProto() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumDescriptorProtoImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<3> scc_info_EnumDescriptorProto = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsEnumDescriptorProto}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueDescriptorProto.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto_EnumReservedRange.base,}}; -void InitDefaultsEnumValueDescriptorProtoImpl() { +static void InitDefaultsEnumValueDescriptorProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptions(); { void* ptr = &::google::protobuf::_EnumValueDescriptorProto_default_instance_; new (ptr) ::google::protobuf::EnumValueDescriptorProto(); @@ -406,21 +357,13 @@ void InitDefaultsEnumValueDescriptorProtoImpl() { ::google::protobuf::EnumValueDescriptorProto::InitAsDefaultInstance(); } -void InitDefaultsEnumValueDescriptorProto() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumValueDescriptorProtoImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueDescriptorProto = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumValueDescriptorProto}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base,}}; -void InitDefaultsServiceDescriptorProtoImpl() { +static void InitDefaultsServiceDescriptorProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProto(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptions(); { void* ptr = &::google::protobuf::_ServiceDescriptorProto_default_instance_; new (ptr) ::google::protobuf::ServiceDescriptorProto(); @@ -429,20 +372,14 @@ void InitDefaultsServiceDescriptorProtoImpl() { ::google::protobuf::ServiceDescriptorProto::InitAsDefaultInstance(); } -void InitDefaultsServiceDescriptorProto() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsServiceDescriptorProtoImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<2> scc_info_ServiceDescriptorProto = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsServiceDescriptorProto}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodDescriptorProto.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base,}}; -void InitDefaultsMethodDescriptorProtoImpl() { +static void InitDefaultsMethodDescriptorProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptions(); { void* ptr = &::google::protobuf::_MethodDescriptorProto_default_instance_; new (ptr) ::google::protobuf::MethodDescriptorProto(); @@ -451,20 +388,13 @@ void InitDefaultsMethodDescriptorProtoImpl() { ::google::protobuf::MethodDescriptorProto::InitAsDefaultInstance(); } -void InitDefaultsMethodDescriptorProto() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMethodDescriptorProtoImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MethodDescriptorProto = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethodDescriptorProto}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base,}}; -void InitDefaultsFileOptionsImpl() { +static void InitDefaultsFileOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); { void* ptr = &::google::protobuf::_FileOptions_default_instance_; new (ptr) ::google::protobuf::FileOptions(); @@ -473,20 +403,13 @@ void InitDefaultsFileOptionsImpl() { ::google::protobuf::FileOptions::InitAsDefaultInstance(); } -void InitDefaultsFileOptions() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFileOptionsImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FileOptions = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFileOptions}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; -void InitDefaultsMessageOptionsImpl() { +static void InitDefaultsMessageOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); { void* ptr = &::google::protobuf::_MessageOptions_default_instance_; new (ptr) ::google::protobuf::MessageOptions(); @@ -495,20 +418,13 @@ void InitDefaultsMessageOptionsImpl() { ::google::protobuf::MessageOptions::InitAsDefaultInstance(); } -void InitDefaultsMessageOptions() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMessageOptionsImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MessageOptions = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMessageOptions}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; -void InitDefaultsFieldOptionsImpl() { +static void InitDefaultsFieldOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); { void* ptr = &::google::protobuf::_FieldOptions_default_instance_; new (ptr) ::google::protobuf::FieldOptions(); @@ -517,20 +433,13 @@ void InitDefaultsFieldOptionsImpl() { ::google::protobuf::FieldOptions::InitAsDefaultInstance(); } -void InitDefaultsFieldOptions() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFieldOptionsImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FieldOptions = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFieldOptions}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; -void InitDefaultsOneofOptionsImpl() { +static void InitDefaultsOneofOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); { void* ptr = &::google::protobuf::_OneofOptions_default_instance_; new (ptr) ::google::protobuf::OneofOptions(); @@ -539,20 +448,13 @@ void InitDefaultsOneofOptionsImpl() { ::google::protobuf::OneofOptions::InitAsDefaultInstance(); } -void InitDefaultsOneofOptions() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsOneofOptionsImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_OneofOptions = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsOneofOptions}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; -void InitDefaultsEnumOptionsImpl() { +static void InitDefaultsEnumOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); { void* ptr = &::google::protobuf::_EnumOptions_default_instance_; new (ptr) ::google::protobuf::EnumOptions(); @@ -561,20 +463,13 @@ void InitDefaultsEnumOptionsImpl() { ::google::protobuf::EnumOptions::InitAsDefaultInstance(); } -void InitDefaultsEnumOptions() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumOptionsImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumOptions = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumOptions}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; -void InitDefaultsEnumValueOptionsImpl() { +static void InitDefaultsEnumValueOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); { void* ptr = &::google::protobuf::_EnumValueOptions_default_instance_; new (ptr) ::google::protobuf::EnumValueOptions(); @@ -583,20 +478,13 @@ void InitDefaultsEnumValueOptionsImpl() { ::google::protobuf::EnumValueOptions::InitAsDefaultInstance(); } -void InitDefaultsEnumValueOptions() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumValueOptionsImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueOptions = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumValueOptions}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; -void InitDefaultsServiceOptionsImpl() { +static void InitDefaultsServiceOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); { void* ptr = &::google::protobuf::_ServiceOptions_default_instance_; new (ptr) ::google::protobuf::ServiceOptions(); @@ -605,20 +493,13 @@ void InitDefaultsServiceOptionsImpl() { ::google::protobuf::ServiceOptions::InitAsDefaultInstance(); } -void InitDefaultsServiceOptions() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsServiceOptionsImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_ServiceOptions = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsServiceOptions}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; -void InitDefaultsMethodOptionsImpl() { +static void InitDefaultsMethodOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); { void* ptr = &::google::protobuf::_MethodOptions_default_instance_; new (ptr) ::google::protobuf::MethodOptions(); @@ -627,19 +508,13 @@ void InitDefaultsMethodOptionsImpl() { ::google::protobuf::MethodOptions::InitAsDefaultInstance(); } -void InitDefaultsMethodOptions() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMethodOptionsImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MethodOptions = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethodOptions}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; -void InitDefaultsUninterpretedOption_NamePartImpl() { +static void InitDefaultsUninterpretedOption_NamePart() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_UninterpretedOption_NamePart_default_instance_; new (ptr) ::google::protobuf::UninterpretedOption_NamePart(); @@ -648,20 +523,12 @@ void InitDefaultsUninterpretedOption_NamePartImpl() { ::google::protobuf::UninterpretedOption_NamePart::InitAsDefaultInstance(); } -void InitDefaultsUninterpretedOption_NamePart() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsUninterpretedOption_NamePartImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_UninterpretedOption_NamePart = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsUninterpretedOption_NamePart}, {}}; -void InitDefaultsUninterpretedOptionImpl() { +static void InitDefaultsUninterpretedOption() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePart(); { void* ptr = &::google::protobuf::_UninterpretedOption_default_instance_; new (ptr) ::google::protobuf::UninterpretedOption(); @@ -670,19 +537,13 @@ void InitDefaultsUninterpretedOptionImpl() { ::google::protobuf::UninterpretedOption::InitAsDefaultInstance(); } -void InitDefaultsUninterpretedOption() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsUninterpretedOptionImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_UninterpretedOption = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsUninterpretedOption}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption_NamePart.base,}}; -void InitDefaultsSourceCodeInfo_LocationImpl() { +static void InitDefaultsSourceCodeInfo_Location() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_SourceCodeInfo_Location_default_instance_; new (ptr) ::google::protobuf::SourceCodeInfo_Location(); @@ -691,20 +552,12 @@ void InitDefaultsSourceCodeInfo_LocationImpl() { ::google::protobuf::SourceCodeInfo_Location::InitAsDefaultInstance(); } -void InitDefaultsSourceCodeInfo_Location() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSourceCodeInfo_LocationImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_SourceCodeInfo_Location = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsSourceCodeInfo_Location}, {}}; -void InitDefaultsSourceCodeInfoImpl() { +static void InitDefaultsSourceCodeInfo() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_Location(); { void* ptr = &::google::protobuf::_SourceCodeInfo_default_instance_; new (ptr) ::google::protobuf::SourceCodeInfo(); @@ -713,19 +566,13 @@ void InitDefaultsSourceCodeInfoImpl() { ::google::protobuf::SourceCodeInfo::InitAsDefaultInstance(); } -void InitDefaultsSourceCodeInfo() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSourceCodeInfoImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_SourceCodeInfo = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsSourceCodeInfo}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo_Location.base,}}; -void InitDefaultsGeneratedCodeInfo_AnnotationImpl() { +static void InitDefaultsGeneratedCodeInfo_Annotation() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_GeneratedCodeInfo_Annotation_default_instance_; new (ptr) ::google::protobuf::GeneratedCodeInfo_Annotation(); @@ -734,20 +581,12 @@ void InitDefaultsGeneratedCodeInfo_AnnotationImpl() { ::google::protobuf::GeneratedCodeInfo_Annotation::InitAsDefaultInstance(); } -void InitDefaultsGeneratedCodeInfo_Annotation() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsGeneratedCodeInfo_AnnotationImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_GeneratedCodeInfo_Annotation = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsGeneratedCodeInfo_Annotation}, {}}; -void InitDefaultsGeneratedCodeInfoImpl() { +static void InitDefaultsGeneratedCodeInfo() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_Annotation(); { void* ptr = &::google::protobuf::_GeneratedCodeInfo_default_instance_; new (ptr) ::google::protobuf::GeneratedCodeInfo(); @@ -756,9 +595,38 @@ void InitDefaultsGeneratedCodeInfoImpl() { ::google::protobuf::GeneratedCodeInfo::InitAsDefaultInstance(); } -void InitDefaultsGeneratedCodeInfo() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsGeneratedCodeInfoImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_GeneratedCodeInfo = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsGeneratedCodeInfo}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo_Annotation.base,}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_FileDescriptorSet.base); + ::google::protobuf::internal::InitSCC(&scc_info_FileDescriptorProto.base); + ::google::protobuf::internal::InitSCC(&scc_info_DescriptorProto_ExtensionRange.base); + ::google::protobuf::internal::InitSCC(&scc_info_DescriptorProto_ReservedRange.base); + ::google::protobuf::internal::InitSCC(&scc_info_DescriptorProto.base); + ::google::protobuf::internal::InitSCC(&scc_info_ExtensionRangeOptions.base); + ::google::protobuf::internal::InitSCC(&scc_info_FieldDescriptorProto.base); + ::google::protobuf::internal::InitSCC(&scc_info_OneofDescriptorProto.base); + ::google::protobuf::internal::InitSCC(&scc_info_EnumDescriptorProto_EnumReservedRange.base); + ::google::protobuf::internal::InitSCC(&scc_info_EnumDescriptorProto.base); + ::google::protobuf::internal::InitSCC(&scc_info_EnumValueDescriptorProto.base); + ::google::protobuf::internal::InitSCC(&scc_info_ServiceDescriptorProto.base); + ::google::protobuf::internal::InitSCC(&scc_info_MethodDescriptorProto.base); + ::google::protobuf::internal::InitSCC(&scc_info_FileOptions.base); + ::google::protobuf::internal::InitSCC(&scc_info_MessageOptions.base); + ::google::protobuf::internal::InitSCC(&scc_info_FieldOptions.base); + ::google::protobuf::internal::InitSCC(&scc_info_OneofOptions.base); + ::google::protobuf::internal::InitSCC(&scc_info_EnumOptions.base); + ::google::protobuf::internal::InitSCC(&scc_info_EnumValueOptions.base); + ::google::protobuf::internal::InitSCC(&scc_info_ServiceOptions.base); + ::google::protobuf::internal::InitSCC(&scc_info_MethodOptions.base); + ::google::protobuf::internal::InitSCC(&scc_info_UninterpretedOption_NamePart.base); + ::google::protobuf::internal::InitSCC(&scc_info_UninterpretedOption.base); + ::google::protobuf::internal::InitSCC(&scc_info_SourceCodeInfo_Location.base); + ::google::protobuf::internal::InitSCC(&scc_info_SourceCodeInfo.base); + ::google::protobuf::internal::InitSCC(&scc_info_GeneratedCodeInfo_Annotation.base); + ::google::protobuf::internal::InitSCC(&scc_info_GeneratedCodeInfo.base); } ::google::protobuf::Metadata file_level_metadata[27]; @@ -973,25 +841,29 @@ const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUT GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, swift_prefix_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, php_class_prefix_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, php_namespace_), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, php_metadata_namespace_), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, ruby_package_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, uninterpreted_option_), 0, 1, - 9, 10, 11, - 17, - 2, 12, + 19, + 2, 13, 14, 15, 16, - 8, + 17, + 18, 3, 4, 5, 6, 7, + 8, + 9, ~0u, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, _internal_metadata_), @@ -1159,20 +1031,20 @@ static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROT { 146, 154, sizeof(::google::protobuf::EnumValueDescriptorProto)}, { 157, 165, sizeof(::google::protobuf::ServiceDescriptorProto)}, { 168, 179, sizeof(::google::protobuf::MethodDescriptorProto)}, - { 185, 209, sizeof(::google::protobuf::FileOptions)}, - { 228, 238, sizeof(::google::protobuf::MessageOptions)}, - { 243, 255, sizeof(::google::protobuf::FieldOptions)}, - { 262, 268, sizeof(::google::protobuf::OneofOptions)}, - { 269, 277, sizeof(::google::protobuf::EnumOptions)}, - { 280, 287, sizeof(::google::protobuf::EnumValueOptions)}, - { 289, 296, sizeof(::google::protobuf::ServiceOptions)}, - { 298, 306, sizeof(::google::protobuf::MethodOptions)}, - { 309, 316, sizeof(::google::protobuf::UninterpretedOption_NamePart)}, - { 318, 330, sizeof(::google::protobuf::UninterpretedOption)}, - { 337, 347, sizeof(::google::protobuf::SourceCodeInfo_Location)}, - { 352, 358, sizeof(::google::protobuf::SourceCodeInfo)}, - { 359, 368, sizeof(::google::protobuf::GeneratedCodeInfo_Annotation)}, - { 372, 378, sizeof(::google::protobuf::GeneratedCodeInfo)}, + { 185, 211, sizeof(::google::protobuf::FileOptions)}, + { 232, 242, sizeof(::google::protobuf::MessageOptions)}, + { 247, 259, sizeof(::google::protobuf::FieldOptions)}, + { 266, 272, sizeof(::google::protobuf::OneofOptions)}, + { 273, 281, sizeof(::google::protobuf::EnumOptions)}, + { 284, 291, sizeof(::google::protobuf::EnumValueOptions)}, + { 293, 300, sizeof(::google::protobuf::ServiceOptions)}, + { 302, 310, sizeof(::google::protobuf::MethodOptions)}, + { 313, 320, sizeof(::google::protobuf::UninterpretedOption_NamePart)}, + { 322, 334, sizeof(::google::protobuf::UninterpretedOption)}, + { 341, 351, sizeof(::google::protobuf::SourceCodeInfo_Location)}, + { 356, 362, sizeof(::google::protobuf::SourceCodeInfo)}, + { 363, 372, sizeof(::google::protobuf::GeneratedCodeInfo_Annotation)}, + { 376, 382, sizeof(::google::protobuf::GeneratedCodeInfo)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { @@ -1205,17 +1077,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_GeneratedCodeInfo_default_instance_), }; -void protobuf_AssignDescriptors() { +static void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/descriptor.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/descriptor.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, file_level_enum_descriptors, NULL); } -void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); +static void protobuf_AssignDescriptorsOnce() { + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -1224,7 +1095,7 @@ void protobuf_RegisterTypes(const ::std::string&) { ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 27); } -void AddDescriptorsImpl() { +static void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n google/protobuf/descriptor.proto\022\017goog" @@ -1300,7 +1171,7 @@ void AddDescriptorsImpl() { "ut_type\030\003 \001(\t\022/\n\007options\030\004 \001(\0132\036.google." "protobuf.MethodOptions\022\037\n\020client_streami" "ng\030\005 \001(\010:\005false\022\037\n\020server_streaming\030\006 \001(" - "\010:\005false\"\360\005\n\013FileOptions\022\024\n\014java_package" + "\010:\005false\"\246\006\n\013FileOptions\022\024\n\014java_package" "\030\001 \001(\t\022\034\n\024java_outer_classname\030\010 \001(\t\022\"\n\023" "java_multiple_files\030\n \001(\010:\005false\022)\n\035java" "_generate_equals_and_hash\030\024 \001(\010B\002\030\001\022%\n\026j" @@ -1315,78 +1186,79 @@ void AddDescriptorsImpl() { "\030\037 \001(\010:\005false\022\031\n\021objc_class_prefix\030$ \001(\t" "\022\030\n\020csharp_namespace\030% \001(\t\022\024\n\014swift_pref" "ix\030\' \001(\t\022\030\n\020php_class_prefix\030( \001(\t\022\025\n\rph" - "p_namespace\030) \001(\t\022C\n\024uninterpreted_optio" + "p_namespace\030) \001(\t\022\036\n\026php_metadata_namesp" + "ace\030, \001(\t\022\024\n\014ruby_package\030- \001(\t\022C\n\024unint" + "erpreted_option\030\347\007 \003(\0132$.google.protobuf" + ".UninterpretedOption\":\n\014OptimizeMode\022\t\n\005" + "SPEED\020\001\022\r\n\tCODE_SIZE\020\002\022\020\n\014LITE_RUNTIME\020\003" + "*\t\010\350\007\020\200\200\200\200\002J\004\010&\020\'\"\362\001\n\016MessageOptions\022&\n\027" + "message_set_wire_format\030\001 \001(\010:\005false\022.\n\037" + "no_standard_descriptor_accessor\030\002 \001(\010:\005f" + "alse\022\031\n\ndeprecated\030\003 \001(\010:\005false\022\021\n\tmap_e" + "ntry\030\007 \001(\010\022C\n\024uninterpreted_option\030\347\007 \003(" + "\0132$.google.protobuf.UninterpretedOption*" + "\t\010\350\007\020\200\200\200\200\002J\004\010\010\020\tJ\004\010\t\020\n\"\236\003\n\014FieldOptions\022" + ":\n\005ctype\030\001 \001(\0162#.google.protobuf.FieldOp" + "tions.CType:\006STRING\022\016\n\006packed\030\002 \001(\010\022\?\n\006j" + "stype\030\006 \001(\0162$.google.protobuf.FieldOptio" + "ns.JSType:\tJS_NORMAL\022\023\n\004lazy\030\005 \001(\010:\005fals" + "e\022\031\n\ndeprecated\030\003 \001(\010:\005false\022\023\n\004weak\030\n \001" + "(\010:\005false\022C\n\024uninterpreted_option\030\347\007 \003(\013" + "2$.google.protobuf.UninterpretedOption\"/" + "\n\005CType\022\n\n\006STRING\020\000\022\010\n\004CORD\020\001\022\020\n\014STRING_" + "PIECE\020\002\"5\n\006JSType\022\r\n\tJS_NORMAL\020\000\022\r\n\tJS_S" + "TRING\020\001\022\r\n\tJS_NUMBER\020\002*\t\010\350\007\020\200\200\200\200\002J\004\010\004\020\005\"" + "^\n\014OneofOptions\022C\n\024uninterpreted_option\030" + "\347\007 \003(\0132$.google.protobuf.UninterpretedOp" + "tion*\t\010\350\007\020\200\200\200\200\002\"\223\001\n\013EnumOptions\022\023\n\013allow" + "_alias\030\002 \001(\010\022\031\n\ndeprecated\030\003 \001(\010:\005false\022" + "C\n\024uninterpreted_option\030\347\007 \003(\0132$.google." + "protobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002J" + "\004\010\005\020\006\"}\n\020EnumValueOptions\022\031\n\ndeprecated\030" + "\001 \001(\010:\005false\022C\n\024uninterpreted_option\030\347\007 " + "\003(\0132$.google.protobuf.UninterpretedOptio" + "n*\t\010\350\007\020\200\200\200\200\002\"{\n\016ServiceOptions\022\031\n\ndeprec" + "ated\030! \001(\010:\005false\022C\n\024uninterpreted_optio" "n\030\347\007 \003(\0132$.google.protobuf.Uninterpreted" - "Option\":\n\014OptimizeMode\022\t\n\005SPEED\020\001\022\r\n\tCOD" - "E_SIZE\020\002\022\020\n\014LITE_RUNTIME\020\003*\t\010\350\007\020\200\200\200\200\002J\004\010" - "&\020\'\"\362\001\n\016MessageOptions\022&\n\027message_set_wi" - "re_format\030\001 \001(\010:\005false\022.\n\037no_standard_de" - "scriptor_accessor\030\002 \001(\010:\005false\022\031\n\ndeprec" - "ated\030\003 \001(\010:\005false\022\021\n\tmap_entry\030\007 \001(\010\022C\n\024" - "uninterpreted_option\030\347\007 \003(\0132$.google.pro" - "tobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002J\004\010\010" - "\020\tJ\004\010\t\020\n\"\236\003\n\014FieldOptions\022:\n\005ctype\030\001 \001(\016" - "2#.google.protobuf.FieldOptions.CType:\006S" - "TRING\022\016\n\006packed\030\002 \001(\010\022\?\n\006jstype\030\006 \001(\0162$." - "google.protobuf.FieldOptions.JSType:\tJS_" - "NORMAL\022\023\n\004lazy\030\005 \001(\010:\005false\022\031\n\ndeprecate" - "d\030\003 \001(\010:\005false\022\023\n\004weak\030\n \001(\010:\005false\022C\n\024u" - "ninterpreted_option\030\347\007 \003(\0132$.google.prot" - "obuf.UninterpretedOption\"/\n\005CType\022\n\n\006STR" - "ING\020\000\022\010\n\004CORD\020\001\022\020\n\014STRING_PIECE\020\002\"5\n\006JST" - "ype\022\r\n\tJS_NORMAL\020\000\022\r\n\tJS_STRING\020\001\022\r\n\tJS_" - "NUMBER\020\002*\t\010\350\007\020\200\200\200\200\002J\004\010\004\020\005\"^\n\014OneofOption" - "s\022C\n\024uninterpreted_option\030\347\007 \003(\0132$.googl" - "e.protobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200" - "\002\"\223\001\n\013EnumOptions\022\023\n\013allow_alias\030\002 \001(\010\022\031" - "\n\ndeprecated\030\003 \001(\010:\005false\022C\n\024uninterpret" - "ed_option\030\347\007 \003(\0132$.google.protobuf.Unint" - "erpretedOption*\t\010\350\007\020\200\200\200\200\002J\004\010\005\020\006\"}\n\020EnumV" - "alueOptions\022\031\n\ndeprecated\030\001 \001(\010:\005false\022C" - "\n\024uninterpreted_option\030\347\007 \003(\0132$.google.p" - "rotobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002\"{" - "\n\016ServiceOptions\022\031\n\ndeprecated\030! \001(\010:\005fa" - "lse\022C\n\024uninterpreted_option\030\347\007 \003(\0132$.goo" - "gle.protobuf.UninterpretedOption*\t\010\350\007\020\200\200" - "\200\200\002\"\255\002\n\rMethodOptions\022\031\n\ndeprecated\030! \001(" - "\010:\005false\022_\n\021idempotency_level\030\" \001(\0162/.go" - "ogle.protobuf.MethodOptions.IdempotencyL" - "evel:\023IDEMPOTENCY_UNKNOWN\022C\n\024uninterpret" - "ed_option\030\347\007 \003(\0132$.google.protobuf.Unint" - "erpretedOption\"P\n\020IdempotencyLevel\022\027\n\023ID" - "EMPOTENCY_UNKNOWN\020\000\022\023\n\017NO_SIDE_EFFECTS\020\001" - "\022\016\n\nIDEMPOTENT\020\002*\t\010\350\007\020\200\200\200\200\002\"\236\002\n\023Uninterp" - "retedOption\022;\n\004name\030\002 \003(\0132-.google.proto" - "buf.UninterpretedOption.NamePart\022\030\n\020iden" - "tifier_value\030\003 \001(\t\022\032\n\022positive_int_value" - "\030\004 \001(\004\022\032\n\022negative_int_value\030\005 \001(\003\022\024\n\014do" - "uble_value\030\006 \001(\001\022\024\n\014string_value\030\007 \001(\014\022\027" - "\n\017aggregate_value\030\010 \001(\t\0323\n\010NamePart\022\021\n\tn" - "ame_part\030\001 \002(\t\022\024\n\014is_extension\030\002 \002(\010\"\325\001\n" - "\016SourceCodeInfo\022:\n\010location\030\001 \003(\0132(.goog" - "le.protobuf.SourceCodeInfo.Location\032\206\001\n\010" - "Location\022\020\n\004path\030\001 \003(\005B\002\020\001\022\020\n\004span\030\002 \003(\005" - "B\002\020\001\022\030\n\020leading_comments\030\003 \001(\t\022\031\n\021traili" - "ng_comments\030\004 \001(\t\022!\n\031leading_detached_co" - "mments\030\006 \003(\t\"\247\001\n\021GeneratedCodeInfo\022A\n\nan" - "notation\030\001 \003(\0132-.google.protobuf.Generat" - "edCodeInfo.Annotation\032O\n\nAnnotation\022\020\n\004p" - "ath\030\001 \003(\005B\002\020\001\022\023\n\013source_file\030\002 \001(\t\022\r\n\005be" - "gin\030\003 \001(\005\022\013\n\003end\030\004 \001(\005B\217\001\n\023com.google.pr" - "otobufB\020DescriptorProtosH\001Z>github.com/g" - "olang/protobuf/protoc-gen-go/descriptor;" - "descriptor\370\001\001\242\002\003GPB\252\002\032Google.Protobuf.Re" - "flection" + "Option*\t\010\350\007\020\200\200\200\200\002\"\255\002\n\rMethodOptions\022\031\n\nd" + "eprecated\030! \001(\010:\005false\022_\n\021idempotency_le" + "vel\030\" \001(\0162/.google.protobuf.MethodOption" + "s.IdempotencyLevel:\023IDEMPOTENCY_UNKNOWN\022" + "C\n\024uninterpreted_option\030\347\007 \003(\0132$.google." + "protobuf.UninterpretedOption\"P\n\020Idempote" + "ncyLevel\022\027\n\023IDEMPOTENCY_UNKNOWN\020\000\022\023\n\017NO_" + "SIDE_EFFECTS\020\001\022\016\n\nIDEMPOTENT\020\002*\t\010\350\007\020\200\200\200\200" + "\002\"\236\002\n\023UninterpretedOption\022;\n\004name\030\002 \003(\0132" + "-.google.protobuf.UninterpretedOption.Na" + "mePart\022\030\n\020identifier_value\030\003 \001(\t\022\032\n\022posi" + "tive_int_value\030\004 \001(\004\022\032\n\022negative_int_val" + "ue\030\005 \001(\003\022\024\n\014double_value\030\006 \001(\001\022\024\n\014string" + "_value\030\007 \001(\014\022\027\n\017aggregate_value\030\010 \001(\t\0323\n" + "\010NamePart\022\021\n\tname_part\030\001 \002(\t\022\024\n\014is_exten" + "sion\030\002 \002(\010\"\325\001\n\016SourceCodeInfo\022:\n\010locatio" + "n\030\001 \003(\0132(.google.protobuf.SourceCodeInfo" + ".Location\032\206\001\n\010Location\022\020\n\004path\030\001 \003(\005B\002\020\001" + "\022\020\n\004span\030\002 \003(\005B\002\020\001\022\030\n\020leading_comments\030\003" + " \001(\t\022\031\n\021trailing_comments\030\004 \001(\t\022!\n\031leadi" + "ng_detached_comments\030\006 \003(\t\"\247\001\n\021Generated" + "CodeInfo\022A\n\nannotation\030\001 \003(\0132-.google.pr" + "otobuf.GeneratedCodeInfo.Annotation\032O\n\nA" + "nnotation\022\020\n\004path\030\001 \003(\005B\002\020\001\022\023\n\013source_fi" + "le\030\002 \001(\t\022\r\n\005begin\030\003 \001(\005\022\013\n\003end\030\004 \001(\005B\217\001\n" + "\023com.google.protobufB\020DescriptorProtosH\001" + "Z>github.com/golang/protobuf/protoc-gen-" + "go/descriptor;descriptor\370\001\001\242\002\003GPB\252\002\032Goog" + "le.Protobuf.Reflection" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - descriptor, 5968); + descriptor, 6022); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "google/protobuf/descriptor.proto", &protobuf_RegisterTypes); } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -1576,9 +1448,8 @@ const int FileDescriptorSet::kFileFieldNumber; FileDescriptorSet::FileDescriptorSet() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorSet(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorSet.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FileDescriptorSet) } @@ -1586,7 +1457,7 @@ FileDescriptorSet::FileDescriptorSet(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), file_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorSet(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorSet.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.FileDescriptorSet) @@ -1595,14 +1466,12 @@ FileDescriptorSet::FileDescriptorSet(const FileDescriptorSet& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), file_(from.file_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.FileDescriptorSet) } void FileDescriptorSet::SharedCtor() { - _cached_size_ = 0; } FileDescriptorSet::~FileDescriptorSet() { @@ -1618,12 +1487,10 @@ void FileDescriptorSet::ArenaDtor(void* object) { FileDescriptorSet* _this = reinterpret_cast< FileDescriptorSet* >(object); (void)_this; } -void FileDescriptorSet::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void FileDescriptorSet::RegisterArenaDtor(::google::protobuf::Arena*) { } void FileDescriptorSet::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* FileDescriptorSet::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1631,7 +1498,7 @@ const ::google::protobuf::Descriptor* FileDescriptorSet::descriptor() { } const FileDescriptorSet& FileDescriptorSet::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorSet(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorSet.base); return *internal_default_instance(); } @@ -1653,7 +1520,7 @@ bool FileDescriptorSet::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FileDescriptorSet) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1755,9 +1622,7 @@ size_t FileDescriptorSet::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1829,7 +1694,6 @@ void FileDescriptorSet::InternalSwap(FileDescriptorSet* other) { CastToBase(&file_)->InternalSwap(CastToBase(&other->file_)); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata FileDescriptorSet::GetMetadata() const { @@ -1889,9 +1753,8 @@ const int FileDescriptorProto::kSyntaxFieldNumber; FileDescriptorProto::FileDescriptorProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FileDescriptorProto) } @@ -1905,7 +1768,7 @@ FileDescriptorProto::FileDescriptorProto(::google::protobuf::Arena* arena) extension_(arena), public_dependency_(arena), weak_dependency_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.FileDescriptorProto) @@ -1914,7 +1777,6 @@ FileDescriptorProto::FileDescriptorProto(const FileDescriptorProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), dependency_(from.dependency_), message_type_(from.message_type_), enum_type_(from.enum_type_), @@ -1952,7 +1814,6 @@ FileDescriptorProto::FileDescriptorProto(const FileDescriptorProto& from) } void FileDescriptorProto::SharedCtor() { - _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); syntax_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -1979,12 +1840,10 @@ void FileDescriptorProto::ArenaDtor(void* object) { FileDescriptorProto* _this = reinterpret_cast< FileDescriptorProto* >(object); (void)_this; } -void FileDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void FileDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena*) { } void FileDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* FileDescriptorProto::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1992,7 +1851,7 @@ const ::google::protobuf::Descriptor* FileDescriptorProto::descriptor() { } const FileDescriptorProto& FileDescriptorProto::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base); return *internal_default_instance(); } @@ -2013,16 +1872,13 @@ void FileDescriptorProto::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 31u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(!package_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + package_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { - GOOGLE_DCHECK(!syntax_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - syntax_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + syntax_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { GOOGLE_DCHECK(options_ != NULL); @@ -2043,7 +1899,7 @@ bool FileDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FileDescriptorProto) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -2318,13 +2174,13 @@ void FileDescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.FileOptions options = 8; if (cached_has_bits & 0x00000008u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 8, *options_, output); + 8, this->_internal_options(), output); } // optional .google.protobuf.SourceCodeInfo source_code_info = 9; if (cached_has_bits & 0x00000010u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 9, *source_code_info_, output); + 9, this->_internal_source_code_info(), output); } // repeated int32 public_dependency = 10; @@ -2432,14 +2288,14 @@ void FileDescriptorProto::SerializeWithCachedSizes( if (cached_has_bits & 0x00000008u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 8, *options_, deterministic, target); + 8, this->_internal_options(), deterministic, target); } // optional .google.protobuf.SourceCodeInfo source_code_info = 9; if (cached_has_bits & 0x00000010u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 9, *source_code_info_, deterministic, target); + 9, this->_internal_source_code_info(), deterministic, target); } // repeated int32 public_dependency = 10; @@ -2586,9 +2442,7 @@ size_t FileDescriptorProto::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -2694,14 +2548,16 @@ void FileDescriptorProto::InternalSwap(FileDescriptorProto* other) { CastToBase(&extension_)->InternalSwap(CastToBase(&other->extension_)); public_dependency_.InternalSwap(&other->public_dependency_); weak_dependency_.InternalSwap(&other->weak_dependency_); - name_.Swap(&other->name_); - package_.Swap(&other->package_); - syntax_.Swap(&other->syntax_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + package_.Swap(&other->package_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + syntax_.Swap(&other->syntax_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(options_, other->options_); swap(source_code_info_, other->source_code_info_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata FileDescriptorProto::GetMetadata() const { @@ -2737,16 +2593,15 @@ const int DescriptorProto_ExtensionRange::kOptionsFieldNumber; DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRange(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ExtensionRange.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto.ExtensionRange) } DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRange(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ExtensionRange.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto.ExtensionRange) @@ -2754,8 +2609,7 @@ DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(::google::protobu DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(const DescriptorProto_ExtensionRange& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_options()) { options_ = new ::google::protobuf::ExtensionRangeOptions(*from.options_); @@ -2769,7 +2623,6 @@ DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(const DescriptorP } void DescriptorProto_ExtensionRange::SharedCtor() { - _cached_size_ = 0; ::memset(&options_, 0, static_cast<size_t>( reinterpret_cast<char*>(&end_) - reinterpret_cast<char*>(&options_)) + sizeof(end_)); @@ -2789,12 +2642,10 @@ void DescriptorProto_ExtensionRange::ArenaDtor(void* object) { DescriptorProto_ExtensionRange* _this = reinterpret_cast< DescriptorProto_ExtensionRange* >(object); (void)_this; } -void DescriptorProto_ExtensionRange::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void DescriptorProto_ExtensionRange::RegisterArenaDtor(::google::protobuf::Arena*) { } void DescriptorProto_ExtensionRange::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* DescriptorProto_ExtensionRange::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -2802,7 +2653,7 @@ const ::google::protobuf::Descriptor* DescriptorProto_ExtensionRange::descriptor } const DescriptorProto_ExtensionRange& DescriptorProto_ExtensionRange::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRange(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ExtensionRange.base); return *internal_default_instance(); } @@ -2833,7 +2684,7 @@ bool DescriptorProto_ExtensionRange::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.DescriptorProto.ExtensionRange) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -2917,7 +2768,7 @@ void DescriptorProto_ExtensionRange::SerializeWithCachedSizes( // optional .google.protobuf.ExtensionRangeOptions options = 3; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, *options_, output); + 3, this->_internal_options(), output); } if (_internal_metadata_.have_unknown_fields()) { @@ -2949,7 +2800,7 @@ void DescriptorProto_ExtensionRange::SerializeWithCachedSizes( if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 3, *options_, deterministic, target); + 3, this->_internal_options(), deterministic, target); } if (_internal_metadata_.have_unknown_fields()) { @@ -2993,9 +2844,7 @@ size_t DescriptorProto_ExtensionRange::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -3083,7 +2932,6 @@ void DescriptorProto_ExtensionRange::InternalSwap(DescriptorProto_ExtensionRange swap(end_, other->end_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata DescriptorProto_ExtensionRange::GetMetadata() const { @@ -3103,16 +2951,15 @@ const int DescriptorProto_ReservedRange::kEndFieldNumber; DescriptorProto_ReservedRange::DescriptorProto_ReservedRange() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRange(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ReservedRange.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto.ReservedRange) } DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRange(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ReservedRange.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto.ReservedRange) @@ -3120,8 +2967,7 @@ DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(::google::protobuf: DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(const DescriptorProto_ReservedRange& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&start_, &from.start_, static_cast<size_t>(reinterpret_cast<char*>(&end_) - @@ -3130,7 +2976,6 @@ DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(const DescriptorPro } void DescriptorProto_ReservedRange::SharedCtor() { - _cached_size_ = 0; ::memset(&start_, 0, static_cast<size_t>( reinterpret_cast<char*>(&end_) - reinterpret_cast<char*>(&start_)) + sizeof(end_)); @@ -3149,12 +2994,10 @@ void DescriptorProto_ReservedRange::ArenaDtor(void* object) { DescriptorProto_ReservedRange* _this = reinterpret_cast< DescriptorProto_ReservedRange* >(object); (void)_this; } -void DescriptorProto_ReservedRange::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void DescriptorProto_ReservedRange::RegisterArenaDtor(::google::protobuf::Arena*) { } void DescriptorProto_ReservedRange::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* DescriptorProto_ReservedRange::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -3162,7 +3005,7 @@ const ::google::protobuf::Descriptor* DescriptorProto_ReservedRange::descriptor( } const DescriptorProto_ReservedRange& DescriptorProto_ReservedRange::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRange(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ReservedRange.base); return *internal_default_instance(); } @@ -3189,7 +3032,7 @@ bool DescriptorProto_ReservedRange::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.DescriptorProto.ReservedRange) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -3317,9 +3160,7 @@ size_t DescriptorProto_ReservedRange::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -3400,7 +3241,6 @@ void DescriptorProto_ReservedRange::InternalSwap(DescriptorProto_ReservedRange* swap(end_, other->end_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata DescriptorProto_ReservedRange::GetMetadata() const { @@ -3443,9 +3283,8 @@ const int DescriptorProto::kReservedNameFieldNumber; DescriptorProto::DescriptorProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto) } @@ -3460,7 +3299,7 @@ DescriptorProto::DescriptorProto(::google::protobuf::Arena* arena) oneof_decl_(arena), reserved_range_(arena), reserved_name_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto) @@ -3469,7 +3308,6 @@ DescriptorProto::DescriptorProto(const DescriptorProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), field_(from.field_), nested_type_(from.nested_type_), enum_type_(from.enum_type_), @@ -3493,7 +3331,6 @@ DescriptorProto::DescriptorProto(const DescriptorProto& from) } void DescriptorProto::SharedCtor() { - _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); options_ = NULL; } @@ -3513,12 +3350,10 @@ void DescriptorProto::ArenaDtor(void* object) { DescriptorProto* _this = reinterpret_cast< DescriptorProto* >(object); (void)_this; } -void DescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void DescriptorProto::RegisterArenaDtor(::google::protobuf::Arena*) { } void DescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* DescriptorProto::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -3526,7 +3361,7 @@ const ::google::protobuf::Descriptor* DescriptorProto::descriptor() { } const DescriptorProto& DescriptorProto::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base); return *internal_default_instance(); } @@ -3548,8 +3383,7 @@ void DescriptorProto::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(options_ != NULL); @@ -3566,7 +3400,7 @@ bool DescriptorProto::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.DescriptorProto) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -3784,7 +3618,7 @@ void DescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.MessageOptions options = 7; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 7, *options_, output); + 7, this->_internal_options(), output); } // repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8; @@ -3885,7 +3719,7 @@ void DescriptorProto::SerializeWithCachedSizes( if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 7, *options_, deterministic, target); + 7, this->_internal_options(), deterministic, target); } // repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8; @@ -4033,9 +3867,7 @@ size_t DescriptorProto::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -4136,11 +3968,11 @@ void DescriptorProto::InternalSwap(DescriptorProto* other) { CastToBase(&oneof_decl_)->InternalSwap(CastToBase(&other->oneof_decl_)); CastToBase(&reserved_range_)->InternalSwap(CastToBase(&other->reserved_range_)); reserved_name_.InternalSwap(CastToBase(&other->reserved_name_)); - name_.Swap(&other->name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(options_, other->options_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata DescriptorProto::GetMetadata() const { @@ -4159,9 +3991,8 @@ const int ExtensionRangeOptions::kUninterpretedOptionFieldNumber; ExtensionRangeOptions::ExtensionRangeOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptions(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.ExtensionRangeOptions) } @@ -4170,7 +4001,7 @@ ExtensionRangeOptions::ExtensionRangeOptions(::google::protobuf::Arena* arena) _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.ExtensionRangeOptions) @@ -4179,7 +4010,6 @@ ExtensionRangeOptions::ExtensionRangeOptions(const ExtensionRangeOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); @@ -4187,7 +4017,6 @@ ExtensionRangeOptions::ExtensionRangeOptions(const ExtensionRangeOptions& from) } void ExtensionRangeOptions::SharedCtor() { - _cached_size_ = 0; } ExtensionRangeOptions::~ExtensionRangeOptions() { @@ -4203,12 +4032,10 @@ void ExtensionRangeOptions::ArenaDtor(void* object) { ExtensionRangeOptions* _this = reinterpret_cast< ExtensionRangeOptions* >(object); (void)_this; } -void ExtensionRangeOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void ExtensionRangeOptions::RegisterArenaDtor(::google::protobuf::Arena*) { } void ExtensionRangeOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* ExtensionRangeOptions::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -4216,7 +4043,7 @@ const ::google::protobuf::Descriptor* ExtensionRangeOptions::descriptor() { } const ExtensionRangeOptions& ExtensionRangeOptions::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base); return *internal_default_instance(); } @@ -4239,7 +4066,7 @@ bool ExtensionRangeOptions::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.ExtensionRangeOptions) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -4357,9 +4184,7 @@ size_t ExtensionRangeOptions::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -4436,7 +4261,6 @@ void ExtensionRangeOptions::InternalSwap(ExtensionRangeOptions* other) { CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_)); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); _extensions_.Swap(&other->_extensions_); } @@ -4480,16 +4304,15 @@ const int FieldDescriptorProto::kOptionsFieldNumber; FieldDescriptorProto::FieldDescriptorProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FieldDescriptorProto) } FieldDescriptorProto::FieldDescriptorProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.FieldDescriptorProto) @@ -4497,8 +4320,7 @@ FieldDescriptorProto::FieldDescriptorProto(::google::protobuf::Arena* arena) FieldDescriptorProto::FieldDescriptorProto(const FieldDescriptorProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { @@ -4537,7 +4359,6 @@ FieldDescriptorProto::FieldDescriptorProto(const FieldDescriptorProto& from) } void FieldDescriptorProto::SharedCtor() { - _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); extendee_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); type_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -4569,12 +4390,10 @@ void FieldDescriptorProto::ArenaDtor(void* object) { FieldDescriptorProto* _this = reinterpret_cast< FieldDescriptorProto* >(object); (void)_this; } -void FieldDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void FieldDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena*) { } void FieldDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* FieldDescriptorProto::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -4582,7 +4401,7 @@ const ::google::protobuf::Descriptor* FieldDescriptorProto::descriptor() { } const FieldDescriptorProto& FieldDescriptorProto::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base); return *internal_default_instance(); } @@ -4596,24 +4415,19 @@ void FieldDescriptorProto::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 63u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(!extendee_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - extendee_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + extendee_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { - GOOGLE_DCHECK(!type_name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - type_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + type_name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { - GOOGLE_DCHECK(!default_value_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - default_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + default_value_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000010u) { - GOOGLE_DCHECK(!json_name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - json_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + json_name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000020u) { GOOGLE_DCHECK(options_ != NULL); @@ -4639,7 +4453,7 @@ bool FieldDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FieldDescriptorProto) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -4890,7 +4704,7 @@ void FieldDescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.FieldOptions options = 8; if (cached_has_bits & 0x00000020u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 8, *options_, output); + 8, this->_internal_options(), output); } // optional int32 oneof_index = 9; @@ -4988,7 +4802,7 @@ void FieldDescriptorProto::SerializeWithCachedSizes( if (cached_has_bits & 0x00000020u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 8, *options_, deterministic, target); + 8, this->_internal_options(), deterministic, target); } // optional int32 oneof_index = 9; @@ -5097,9 +4911,7 @@ size_t FieldDescriptorProto::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -5206,11 +5018,16 @@ void FieldDescriptorProto::UnsafeArenaSwap(FieldDescriptorProto* other) { } void FieldDescriptorProto::InternalSwap(FieldDescriptorProto* other) { using std::swap; - name_.Swap(&other->name_); - extendee_.Swap(&other->extendee_); - type_name_.Swap(&other->type_name_); - default_value_.Swap(&other->default_value_); - json_name_.Swap(&other->json_name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + extendee_.Swap(&other->extendee_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + type_name_.Swap(&other->type_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + default_value_.Swap(&other->default_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + json_name_.Swap(&other->json_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(options_, other->options_); swap(number_, other->number_); swap(oneof_index_, other->oneof_index_); @@ -5218,7 +5035,6 @@ void FieldDescriptorProto::InternalSwap(FieldDescriptorProto* other) { swap(type_, other->type_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata FieldDescriptorProto::GetMetadata() const { @@ -5253,16 +5069,15 @@ const int OneofDescriptorProto::kOptionsFieldNumber; OneofDescriptorProto::OneofDescriptorProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProto(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofDescriptorProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.OneofDescriptorProto) } OneofDescriptorProto::OneofDescriptorProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.OneofDescriptorProto) @@ -5270,8 +5085,7 @@ OneofDescriptorProto::OneofDescriptorProto(::google::protobuf::Arena* arena) OneofDescriptorProto::OneofDescriptorProto(const OneofDescriptorProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { @@ -5287,7 +5101,6 @@ OneofDescriptorProto::OneofDescriptorProto(const OneofDescriptorProto& from) } void OneofDescriptorProto::SharedCtor() { - _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); options_ = NULL; } @@ -5307,12 +5120,10 @@ void OneofDescriptorProto::ArenaDtor(void* object) { OneofDescriptorProto* _this = reinterpret_cast< OneofDescriptorProto* >(object); (void)_this; } -void OneofDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void OneofDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena*) { } void OneofDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* OneofDescriptorProto::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -5320,7 +5131,7 @@ const ::google::protobuf::Descriptor* OneofDescriptorProto::descriptor() { } const OneofDescriptorProto& OneofDescriptorProto::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofDescriptorProto.base); return *internal_default_instance(); } @@ -5334,8 +5145,7 @@ void OneofDescriptorProto::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(options_ != NULL); @@ -5352,7 +5162,7 @@ bool OneofDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.OneofDescriptorProto) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -5424,7 +5234,7 @@ void OneofDescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.OneofOptions options = 2; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 2, *options_, output); + 2, this->_internal_options(), output); } if (_internal_metadata_.have_unknown_fields()) { @@ -5457,7 +5267,7 @@ void OneofDescriptorProto::SerializeWithCachedSizes( if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 2, *options_, deterministic, target); + 2, this->_internal_options(), deterministic, target); } if (_internal_metadata_.have_unknown_fields()) { @@ -5494,9 +5304,7 @@ size_t OneofDescriptorProto::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -5575,11 +5383,11 @@ void OneofDescriptorProto::UnsafeArenaSwap(OneofDescriptorProto* other) { } void OneofDescriptorProto::InternalSwap(OneofDescriptorProto* other) { using std::swap; - name_.Swap(&other->name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(options_, other->options_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata OneofDescriptorProto::GetMetadata() const { @@ -5599,16 +5407,15 @@ const int EnumDescriptorProto_EnumReservedRange::kEndFieldNumber; EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRange(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto_EnumReservedRange.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.EnumDescriptorProto.EnumReservedRange) } EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRange(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto_EnumReservedRange.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumDescriptorProto.EnumReservedRange) @@ -5616,8 +5423,7 @@ EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(::g EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(const EnumDescriptorProto_EnumReservedRange& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&start_, &from.start_, static_cast<size_t>(reinterpret_cast<char*>(&end_) - @@ -5626,7 +5432,6 @@ EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(con } void EnumDescriptorProto_EnumReservedRange::SharedCtor() { - _cached_size_ = 0; ::memset(&start_, 0, static_cast<size_t>( reinterpret_cast<char*>(&end_) - reinterpret_cast<char*>(&start_)) + sizeof(end_)); @@ -5645,12 +5450,10 @@ void EnumDescriptorProto_EnumReservedRange::ArenaDtor(void* object) { EnumDescriptorProto_EnumReservedRange* _this = reinterpret_cast< EnumDescriptorProto_EnumReservedRange* >(object); (void)_this; } -void EnumDescriptorProto_EnumReservedRange::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void EnumDescriptorProto_EnumReservedRange::RegisterArenaDtor(::google::protobuf::Arena*) { } void EnumDescriptorProto_EnumReservedRange::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* EnumDescriptorProto_EnumReservedRange::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -5658,7 +5461,7 @@ const ::google::protobuf::Descriptor* EnumDescriptorProto_EnumReservedRange::des } const EnumDescriptorProto_EnumReservedRange& EnumDescriptorProto_EnumReservedRange::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRange(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto_EnumReservedRange.base); return *internal_default_instance(); } @@ -5685,7 +5488,7 @@ bool EnumDescriptorProto_EnumReservedRange::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumDescriptorProto.EnumReservedRange) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -5813,9 +5616,7 @@ size_t EnumDescriptorProto_EnumReservedRange::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -5896,7 +5697,6 @@ void EnumDescriptorProto_EnumReservedRange::InternalSwap(EnumDescriptorProto_Enu swap(end_, other->end_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata EnumDescriptorProto_EnumReservedRange::GetMetadata() const { @@ -5934,9 +5734,8 @@ const int EnumDescriptorProto::kReservedNameFieldNumber; EnumDescriptorProto::EnumDescriptorProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.EnumDescriptorProto) } @@ -5946,7 +5745,7 @@ EnumDescriptorProto::EnumDescriptorProto(::google::protobuf::Arena* arena) value_(arena), reserved_range_(arena), reserved_name_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumDescriptorProto) @@ -5955,7 +5754,6 @@ EnumDescriptorProto::EnumDescriptorProto(const EnumDescriptorProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), value_(from.value_), reserved_range_(from.reserved_range_), reserved_name_(from.reserved_name_) { @@ -5974,7 +5772,6 @@ EnumDescriptorProto::EnumDescriptorProto(const EnumDescriptorProto& from) } void EnumDescriptorProto::SharedCtor() { - _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); options_ = NULL; } @@ -5994,12 +5791,10 @@ void EnumDescriptorProto::ArenaDtor(void* object) { EnumDescriptorProto* _this = reinterpret_cast< EnumDescriptorProto* >(object); (void)_this; } -void EnumDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void EnumDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena*) { } void EnumDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* EnumDescriptorProto::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -6007,7 +5802,7 @@ const ::google::protobuf::Descriptor* EnumDescriptorProto::descriptor() { } const EnumDescriptorProto& EnumDescriptorProto::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base); return *internal_default_instance(); } @@ -6024,8 +5819,7 @@ void EnumDescriptorProto::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(options_ != NULL); @@ -6042,7 +5836,7 @@ bool EnumDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumDescriptorProto) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -6164,7 +5958,7 @@ void EnumDescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.EnumOptions options = 3; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, *options_, output); + 3, this->_internal_options(), output); } // repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4; @@ -6224,7 +6018,7 @@ void EnumDescriptorProto::SerializeWithCachedSizes( if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 3, *options_, deterministic, target); + 3, this->_internal_options(), deterministic, target); } // repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4; @@ -6309,9 +6103,7 @@ size_t EnumDescriptorProto::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -6397,11 +6189,11 @@ void EnumDescriptorProto::InternalSwap(EnumDescriptorProto* other) { CastToBase(&value_)->InternalSwap(CastToBase(&other->value_)); CastToBase(&reserved_range_)->InternalSwap(CastToBase(&other->reserved_range_)); reserved_name_.InternalSwap(CastToBase(&other->reserved_name_)); - name_.Swap(&other->name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(options_, other->options_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata EnumDescriptorProto::GetMetadata() const { @@ -6437,16 +6229,15 @@ const int EnumValueDescriptorProto::kOptionsFieldNumber; EnumValueDescriptorProto::EnumValueDescriptorProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProto(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueDescriptorProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.EnumValueDescriptorProto) } EnumValueDescriptorProto::EnumValueDescriptorProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValueDescriptorProto) @@ -6454,8 +6245,7 @@ EnumValueDescriptorProto::EnumValueDescriptorProto(::google::protobuf::Arena* ar EnumValueDescriptorProto::EnumValueDescriptorProto(const EnumValueDescriptorProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { @@ -6472,7 +6262,6 @@ EnumValueDescriptorProto::EnumValueDescriptorProto(const EnumValueDescriptorProt } void EnumValueDescriptorProto::SharedCtor() { - _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&options_, 0, static_cast<size_t>( reinterpret_cast<char*>(&number_) - @@ -6494,12 +6283,10 @@ void EnumValueDescriptorProto::ArenaDtor(void* object) { EnumValueDescriptorProto* _this = reinterpret_cast< EnumValueDescriptorProto* >(object); (void)_this; } -void EnumValueDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void EnumValueDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena*) { } void EnumValueDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* EnumValueDescriptorProto::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -6507,7 +6294,7 @@ const ::google::protobuf::Descriptor* EnumValueDescriptorProto::descriptor() { } const EnumValueDescriptorProto& EnumValueDescriptorProto::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueDescriptorProto.base); return *internal_default_instance(); } @@ -6521,8 +6308,7 @@ void EnumValueDescriptorProto::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(options_ != NULL); @@ -6540,7 +6326,7 @@ bool EnumValueDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumValueDescriptorProto) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -6631,7 +6417,7 @@ void EnumValueDescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.EnumValueOptions options = 3; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, *options_, output); + 3, this->_internal_options(), output); } if (_internal_metadata_.have_unknown_fields()) { @@ -6669,7 +6455,7 @@ void EnumValueDescriptorProto::SerializeWithCachedSizes( if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 3, *options_, deterministic, target); + 3, this->_internal_options(), deterministic, target); } if (_internal_metadata_.have_unknown_fields()) { @@ -6713,9 +6499,7 @@ size_t EnumValueDescriptorProto::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -6798,12 +6582,12 @@ void EnumValueDescriptorProto::UnsafeArenaSwap(EnumValueDescriptorProto* other) } void EnumValueDescriptorProto::InternalSwap(EnumValueDescriptorProto* other) { using std::swap; - name_.Swap(&other->name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(options_, other->options_); swap(number_, other->number_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata EnumValueDescriptorProto::GetMetadata() const { @@ -6839,9 +6623,8 @@ const int ServiceDescriptorProto::kOptionsFieldNumber; ServiceDescriptorProto::ServiceDescriptorProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProto(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.ServiceDescriptorProto) } @@ -6849,7 +6632,7 @@ ServiceDescriptorProto::ServiceDescriptorProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), method_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.ServiceDescriptorProto) @@ -6858,7 +6641,6 @@ ServiceDescriptorProto::ServiceDescriptorProto(const ServiceDescriptorProto& fro : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), method_(from.method_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -6875,7 +6657,6 @@ ServiceDescriptorProto::ServiceDescriptorProto(const ServiceDescriptorProto& fro } void ServiceDescriptorProto::SharedCtor() { - _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); options_ = NULL; } @@ -6895,12 +6676,10 @@ void ServiceDescriptorProto::ArenaDtor(void* object) { ServiceDescriptorProto* _this = reinterpret_cast< ServiceDescriptorProto* >(object); (void)_this; } -void ServiceDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void ServiceDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena*) { } void ServiceDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* ServiceDescriptorProto::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -6908,7 +6687,7 @@ const ::google::protobuf::Descriptor* ServiceDescriptorProto::descriptor() { } const ServiceDescriptorProto& ServiceDescriptorProto::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base); return *internal_default_instance(); } @@ -6923,8 +6702,7 @@ void ServiceDescriptorProto::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(options_ != NULL); @@ -6941,7 +6719,7 @@ bool ServiceDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.ServiceDescriptorProto) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -7034,7 +6812,7 @@ void ServiceDescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.ServiceOptions options = 3; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, *options_, output); + 3, this->_internal_options(), output); } if (_internal_metadata_.have_unknown_fields()) { @@ -7075,7 +6853,7 @@ void ServiceDescriptorProto::SerializeWithCachedSizes( if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 3, *options_, deterministic, target); + 3, this->_internal_options(), deterministic, target); } if (_internal_metadata_.have_unknown_fields()) { @@ -7123,9 +6901,7 @@ size_t ServiceDescriptorProto::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -7207,11 +6983,11 @@ void ServiceDescriptorProto::UnsafeArenaSwap(ServiceDescriptorProto* other) { void ServiceDescriptorProto::InternalSwap(ServiceDescriptorProto* other) { using std::swap; CastToBase(&method_)->InternalSwap(CastToBase(&other->method_)); - name_.Swap(&other->name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(options_, other->options_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata ServiceDescriptorProto::GetMetadata() const { @@ -7250,16 +7026,15 @@ const int MethodDescriptorProto::kServerStreamingFieldNumber; MethodDescriptorProto::MethodDescriptorProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProto(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodDescriptorProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.MethodDescriptorProto) } MethodDescriptorProto::MethodDescriptorProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.MethodDescriptorProto) @@ -7267,8 +7042,7 @@ MethodDescriptorProto::MethodDescriptorProto(::google::protobuf::Arena* arena) MethodDescriptorProto::MethodDescriptorProto(const MethodDescriptorProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { @@ -7297,7 +7071,6 @@ MethodDescriptorProto::MethodDescriptorProto(const MethodDescriptorProto& from) } void MethodDescriptorProto::SharedCtor() { - _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); input_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); output_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -7323,12 +7096,10 @@ void MethodDescriptorProto::ArenaDtor(void* object) { MethodDescriptorProto* _this = reinterpret_cast< MethodDescriptorProto* >(object); (void)_this; } -void MethodDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void MethodDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena*) { } void MethodDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* MethodDescriptorProto::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -7336,7 +7107,7 @@ const ::google::protobuf::Descriptor* MethodDescriptorProto::descriptor() { } const MethodDescriptorProto& MethodDescriptorProto::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodDescriptorProto.base); return *internal_default_instance(); } @@ -7350,16 +7121,13 @@ void MethodDescriptorProto::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 15u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(!input_type_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - input_type_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + input_type_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { - GOOGLE_DCHECK(!output_type_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - output_type_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + output_type_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { GOOGLE_DCHECK(options_ != NULL); @@ -7379,7 +7147,7 @@ bool MethodDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.MethodDescriptorProto) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -7531,7 +7299,7 @@ void MethodDescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.MethodOptions options = 4; if (cached_has_bits & 0x00000008u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 4, *options_, output); + 4, this->_internal_options(), output); } // optional bool client_streaming = 5 [default = false]; @@ -7596,7 +7364,7 @@ void MethodDescriptorProto::SerializeWithCachedSizes( if (cached_has_bits & 0x00000008u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 4, *options_, deterministic, target); + 4, this->_internal_options(), deterministic, target); } // optional bool client_streaming = 5 [default = false]; @@ -7667,9 +7435,7 @@ size_t MethodDescriptorProto::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -7761,15 +7527,17 @@ void MethodDescriptorProto::UnsafeArenaSwap(MethodDescriptorProto* other) { } void MethodDescriptorProto::InternalSwap(MethodDescriptorProto* other) { using std::swap; - name_.Swap(&other->name_); - input_type_.Swap(&other->input_type_); - output_type_.Swap(&other->output_type_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + input_type_.Swap(&other->input_type_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + output_type_.Swap(&other->output_type_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(options_, other->options_); swap(client_streaming_, other->client_streaming_); swap(server_streaming_, other->server_streaming_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata MethodDescriptorProto::GetMetadata() const { @@ -7801,14 +7569,15 @@ const int FileOptions::kCsharpNamespaceFieldNumber; const int FileOptions::kSwiftPrefixFieldNumber; const int FileOptions::kPhpClassPrefixFieldNumber; const int FileOptions::kPhpNamespaceFieldNumber; +const int FileOptions::kPhpMetadataNamespaceFieldNumber; +const int FileOptions::kRubyPackageFieldNumber; const int FileOptions::kUninterpretedOptionFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 FileOptions::FileOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptions(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FileOptions) } @@ -7817,7 +7586,7 @@ FileOptions::FileOptions(::google::protobuf::Arena* arena) _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.FileOptions) @@ -7826,7 +7595,6 @@ FileOptions::FileOptions(const FileOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); @@ -7870,14 +7638,23 @@ FileOptions::FileOptions(const FileOptions& from) php_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.php_namespace(), GetArenaNoVirtual()); } - ::memcpy(&cc_enable_arenas_, &from.cc_enable_arenas_, + php_metadata_namespace_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + if (from.has_php_metadata_namespace()) { + php_metadata_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.php_metadata_namespace(), + GetArenaNoVirtual()); + } + ruby_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + if (from.has_ruby_package()) { + ruby_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.ruby_package(), + GetArenaNoVirtual()); + } + ::memcpy(&java_multiple_files_, &from.java_multiple_files_, static_cast<size_t>(reinterpret_cast<char*>(&optimize_for_) - - reinterpret_cast<char*>(&cc_enable_arenas_)) + sizeof(optimize_for_)); + reinterpret_cast<char*>(&java_multiple_files_)) + sizeof(optimize_for_)); // @@protoc_insertion_point(copy_constructor:google.protobuf.FileOptions) } void FileOptions::SharedCtor() { - _cached_size_ = 0; java_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); java_outer_classname_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); go_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -7886,9 +7663,11 @@ void FileOptions::SharedCtor() { swift_prefix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); php_class_prefix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); php_namespace_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - ::memset(&cc_enable_arenas_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&deprecated_) - - reinterpret_cast<char*>(&cc_enable_arenas_)) + sizeof(deprecated_)); + php_metadata_namespace_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ruby_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ::memset(&java_multiple_files_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&cc_enable_arenas_) - + reinterpret_cast<char*>(&java_multiple_files_)) + sizeof(cc_enable_arenas_)); optimize_for_ = 1; } @@ -7907,18 +7686,18 @@ void FileOptions::SharedDtor() { swift_prefix_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); php_class_prefix_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); php_namespace_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + php_metadata_namespace_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + ruby_package_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void FileOptions::ArenaDtor(void* object) { FileOptions* _this = reinterpret_cast< FileOptions* >(object); (void)_this; } -void FileOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void FileOptions::RegisterArenaDtor(::google::protobuf::Arena*) { } void FileOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* FileOptions::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -7926,7 +7705,7 @@ const ::google::protobuf::Descriptor* FileOptions::descriptor() { } const FileOptions& FileOptions::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base); return *internal_default_instance(); } @@ -7942,45 +7721,47 @@ void FileOptions::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 255u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!java_package_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - java_package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + java_package_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(!java_outer_classname_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - java_outer_classname_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + java_outer_classname_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { - GOOGLE_DCHECK(!go_package_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - go_package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + go_package_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { - GOOGLE_DCHECK(!objc_class_prefix_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - objc_class_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + objc_class_prefix_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000010u) { - GOOGLE_DCHECK(!csharp_namespace_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - csharp_namespace_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + csharp_namespace_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000020u) { - GOOGLE_DCHECK(!swift_prefix_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - swift_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + swift_prefix_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000040u) { - GOOGLE_DCHECK(!php_class_prefix_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - php_class_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + php_class_prefix_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000080u) { - GOOGLE_DCHECK(!php_namespace_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - php_namespace_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + php_namespace_.ClearNonDefaultToEmpty(); } } - if (cached_has_bits & 65280u) { - ::memset(&cc_enable_arenas_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&php_generic_services_) - - reinterpret_cast<char*>(&cc_enable_arenas_)) + sizeof(php_generic_services_)); + if (cached_has_bits & 768u) { + if (cached_has_bits & 0x00000100u) { + php_metadata_namespace_.ClearNonDefaultToEmpty(); + } + if (cached_has_bits & 0x00000200u) { + ruby_package_.ClearNonDefaultToEmpty(); + } } - if (cached_has_bits & 196608u) { - deprecated_ = false; + if (cached_has_bits & 64512u) { + ::memset(&java_multiple_files_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&py_generic_services_) - + reinterpret_cast<char*>(&java_multiple_files_)) + sizeof(py_generic_services_)); + } + if (cached_has_bits & 983040u) { + ::memset(&php_generic_services_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&cc_enable_arenas_) - + reinterpret_cast<char*>(&php_generic_services_)) + sizeof(cc_enable_arenas_)); optimize_for_ = 1; } _has_bits_.Clear(); @@ -7993,7 +7774,7 @@ bool FileOptions::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FileOptions) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -8271,6 +8052,38 @@ bool FileOptions::MergePartialFromCodedStream( break; } + // optional string php_metadata_namespace = 44; + case 44: { + if (static_cast< ::google::protobuf::uint8>(tag) == + static_cast< ::google::protobuf::uint8>(98u /* 354 & 0xFF */)) { + DO_(::google::protobuf::internal::WireFormatLite::ReadString( + input, this->mutable_php_metadata_namespace())); + ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + this->php_metadata_namespace().data(), static_cast<int>(this->php_metadata_namespace().length()), + ::google::protobuf::internal::WireFormat::PARSE, + "google.protobuf.FileOptions.php_metadata_namespace"); + } else { + goto handle_unusual; + } + break; + } + + // optional string ruby_package = 45; + case 45: { + if (static_cast< ::google::protobuf::uint8>(tag) == + static_cast< ::google::protobuf::uint8>(106u /* 362 & 0xFF */)) { + DO_(::google::protobuf::internal::WireFormatLite::ReadString( + input, this->mutable_ruby_package())); + ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + this->ruby_package().data(), static_cast<int>(this->ruby_package().length()), + ::google::protobuf::internal::WireFormat::PARSE, + "google.protobuf.FileOptions.ruby_package"); + } else { + goto handle_unusual; + } + break; + } + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; case 999: { if (static_cast< ::google::protobuf::uint8>(tag) == @@ -8337,13 +8150,13 @@ void FileOptions::SerializeWithCachedSizes( } // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED]; - if (cached_has_bits & 0x00020000u) { + if (cached_has_bits & 0x00080000u) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 9, this->optimize_for(), output); } // optional bool java_multiple_files = 10 [default = false]; - if (cached_has_bits & 0x00000200u) { + if (cached_has_bits & 0x00000400u) { ::google::protobuf::internal::WireFormatLite::WriteBool(10, this->java_multiple_files(), output); } @@ -8358,37 +8171,37 @@ void FileOptions::SerializeWithCachedSizes( } // optional bool cc_generic_services = 16 [default = false]; - if (cached_has_bits & 0x00001000u) { + if (cached_has_bits & 0x00002000u) { ::google::protobuf::internal::WireFormatLite::WriteBool(16, this->cc_generic_services(), output); } // optional bool java_generic_services = 17 [default = false]; - if (cached_has_bits & 0x00002000u) { + if (cached_has_bits & 0x00004000u) { ::google::protobuf::internal::WireFormatLite::WriteBool(17, this->java_generic_services(), output); } // optional bool py_generic_services = 18 [default = false]; - if (cached_has_bits & 0x00004000u) { + if (cached_has_bits & 0x00008000u) { ::google::protobuf::internal::WireFormatLite::WriteBool(18, this->py_generic_services(), output); } // optional bool java_generate_equals_and_hash = 20 [deprecated = true]; - if (cached_has_bits & 0x00000400u) { + if (cached_has_bits & 0x00000800u) { ::google::protobuf::internal::WireFormatLite::WriteBool(20, this->java_generate_equals_and_hash(), output); } // optional bool deprecated = 23 [default = false]; - if (cached_has_bits & 0x00010000u) { + if (cached_has_bits & 0x00020000u) { ::google::protobuf::internal::WireFormatLite::WriteBool(23, this->deprecated(), output); } // optional bool java_string_check_utf8 = 27 [default = false]; - if (cached_has_bits & 0x00000800u) { + if (cached_has_bits & 0x00001000u) { ::google::protobuf::internal::WireFormatLite::WriteBool(27, this->java_string_check_utf8(), output); } // optional bool cc_enable_arenas = 31 [default = false]; - if (cached_has_bits & 0x00000100u) { + if (cached_has_bits & 0x00040000u) { ::google::protobuf::internal::WireFormatLite::WriteBool(31, this->cc_enable_arenas(), output); } @@ -8443,10 +8256,30 @@ void FileOptions::SerializeWithCachedSizes( } // optional bool php_generic_services = 42 [default = false]; - if (cached_has_bits & 0x00008000u) { + if (cached_has_bits & 0x00010000u) { ::google::protobuf::internal::WireFormatLite::WriteBool(42, this->php_generic_services(), output); } + // optional string php_metadata_namespace = 44; + if (cached_has_bits & 0x00000100u) { + ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + this->php_metadata_namespace().data(), static_cast<int>(this->php_metadata_namespace().length()), + ::google::protobuf::internal::WireFormat::SERIALIZE, + "google.protobuf.FileOptions.php_metadata_namespace"); + ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + 44, this->php_metadata_namespace(), output); + } + + // optional string ruby_package = 45; + if (cached_has_bits & 0x00000200u) { + ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + this->ruby_package().data(), static_cast<int>(this->ruby_package().length()), + ::google::protobuf::internal::WireFormat::SERIALIZE, + "google.protobuf.FileOptions.ruby_package"); + ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + 45, this->ruby_package(), output); + } + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) { @@ -8498,13 +8331,13 @@ void FileOptions::SerializeWithCachedSizes( } // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED]; - if (cached_has_bits & 0x00020000u) { + if (cached_has_bits & 0x00080000u) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 9, this->optimize_for(), target); } // optional bool java_multiple_files = 10 [default = false]; - if (cached_has_bits & 0x00000200u) { + if (cached_has_bits & 0x00000400u) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(10, this->java_multiple_files(), target); } @@ -8520,37 +8353,37 @@ void FileOptions::SerializeWithCachedSizes( } // optional bool cc_generic_services = 16 [default = false]; - if (cached_has_bits & 0x00001000u) { + if (cached_has_bits & 0x00002000u) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(16, this->cc_generic_services(), target); } // optional bool java_generic_services = 17 [default = false]; - if (cached_has_bits & 0x00002000u) { + if (cached_has_bits & 0x00004000u) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(17, this->java_generic_services(), target); } // optional bool py_generic_services = 18 [default = false]; - if (cached_has_bits & 0x00004000u) { + if (cached_has_bits & 0x00008000u) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(18, this->py_generic_services(), target); } // optional bool java_generate_equals_and_hash = 20 [deprecated = true]; - if (cached_has_bits & 0x00000400u) { + if (cached_has_bits & 0x00000800u) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(20, this->java_generate_equals_and_hash(), target); } // optional bool deprecated = 23 [default = false]; - if (cached_has_bits & 0x00010000u) { + if (cached_has_bits & 0x00020000u) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(23, this->deprecated(), target); } // optional bool java_string_check_utf8 = 27 [default = false]; - if (cached_has_bits & 0x00000800u) { + if (cached_has_bits & 0x00001000u) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(27, this->java_string_check_utf8(), target); } // optional bool cc_enable_arenas = 31 [default = false]; - if (cached_has_bits & 0x00000100u) { + if (cached_has_bits & 0x00040000u) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(31, this->cc_enable_arenas(), target); } @@ -8610,10 +8443,32 @@ void FileOptions::SerializeWithCachedSizes( } // optional bool php_generic_services = 42 [default = false]; - if (cached_has_bits & 0x00008000u) { + if (cached_has_bits & 0x00010000u) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(42, this->php_generic_services(), target); } + // optional string php_metadata_namespace = 44; + if (cached_has_bits & 0x00000100u) { + ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + this->php_metadata_namespace().data(), static_cast<int>(this->php_metadata_namespace().length()), + ::google::protobuf::internal::WireFormat::SERIALIZE, + "google.protobuf.FileOptions.php_metadata_namespace"); + target = + ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + 44, this->php_metadata_namespace(), target); + } + + // optional string ruby_package = 45; + if (cached_has_bits & 0x00000200u) { + ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + this->ruby_package().data(), static_cast<int>(this->ruby_package().length()), + ::google::protobuf::internal::WireFormat::SERIALIZE, + "google.protobuf.FileOptions.ruby_package"); + target = + ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + 45, this->ruby_package(), target); + } + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; for (unsigned int i = 0, n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) { @@ -8715,9 +8570,18 @@ size_t FileOptions::ByteSizeLong() const { } if (_has_bits_[8 / 32] & 65280u) { - // optional bool cc_enable_arenas = 31 [default = false]; - if (has_cc_enable_arenas()) { - total_size += 2 + 1; + // optional string php_metadata_namespace = 44; + if (has_php_metadata_namespace()) { + total_size += 2 + + ::google::protobuf::internal::WireFormatLite::StringSize( + this->php_metadata_namespace()); + } + + // optional string ruby_package = 45; + if (has_ruby_package()) { + total_size += 2 + + ::google::protobuf::internal::WireFormatLite::StringSize( + this->ruby_package()); } // optional bool java_multiple_files = 10 [default = false]; @@ -8750,18 +8614,23 @@ size_t FileOptions::ByteSizeLong() const { total_size += 2 + 1; } + } + if (_has_bits_[16 / 32] & 983040u) { // optional bool php_generic_services = 42 [default = false]; if (has_php_generic_services()) { total_size += 2 + 1; } - } - if (_has_bits_[16 / 32] & 196608u) { // optional bool deprecated = 23 [default = false]; if (has_deprecated()) { total_size += 2 + 1; } + // optional bool cc_enable_arenas = 31 [default = false]; + if (has_cc_enable_arenas()) { + total_size += 2 + 1; + } + // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED]; if (has_optimize_for()) { total_size += 1 + @@ -8770,9 +8639,7 @@ size_t FileOptions::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -8829,36 +8696,42 @@ void FileOptions::MergeFrom(const FileOptions& from) { } if (cached_has_bits & 65280u) { if (cached_has_bits & 0x00000100u) { - cc_enable_arenas_ = from.cc_enable_arenas_; + set_php_metadata_namespace(from.php_metadata_namespace()); } if (cached_has_bits & 0x00000200u) { - java_multiple_files_ = from.java_multiple_files_; + set_ruby_package(from.ruby_package()); } if (cached_has_bits & 0x00000400u) { - java_generate_equals_and_hash_ = from.java_generate_equals_and_hash_; + java_multiple_files_ = from.java_multiple_files_; } if (cached_has_bits & 0x00000800u) { - java_string_check_utf8_ = from.java_string_check_utf8_; + java_generate_equals_and_hash_ = from.java_generate_equals_and_hash_; } if (cached_has_bits & 0x00001000u) { - cc_generic_services_ = from.cc_generic_services_; + java_string_check_utf8_ = from.java_string_check_utf8_; } if (cached_has_bits & 0x00002000u) { - java_generic_services_ = from.java_generic_services_; + cc_generic_services_ = from.cc_generic_services_; } if (cached_has_bits & 0x00004000u) { - py_generic_services_ = from.py_generic_services_; + java_generic_services_ = from.java_generic_services_; } if (cached_has_bits & 0x00008000u) { - php_generic_services_ = from.php_generic_services_; + py_generic_services_ = from.py_generic_services_; } _has_bits_[0] |= cached_has_bits; } - if (cached_has_bits & 196608u) { + if (cached_has_bits & 983040u) { if (cached_has_bits & 0x00010000u) { - deprecated_ = from.deprecated_; + php_generic_services_ = from.php_generic_services_; } if (cached_has_bits & 0x00020000u) { + deprecated_ = from.deprecated_; + } + if (cached_has_bits & 0x00040000u) { + cc_enable_arenas_ = from.cc_enable_arenas_; + } + if (cached_has_bits & 0x00080000u) { optimize_for_ = from.optimize_for_; } _has_bits_[0] |= cached_has_bits; @@ -8910,15 +8783,26 @@ void FileOptions::UnsafeArenaSwap(FileOptions* other) { void FileOptions::InternalSwap(FileOptions* other) { using std::swap; CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_)); - java_package_.Swap(&other->java_package_); - java_outer_classname_.Swap(&other->java_outer_classname_); - go_package_.Swap(&other->go_package_); - objc_class_prefix_.Swap(&other->objc_class_prefix_); - csharp_namespace_.Swap(&other->csharp_namespace_); - swift_prefix_.Swap(&other->swift_prefix_); - php_class_prefix_.Swap(&other->php_class_prefix_); - php_namespace_.Swap(&other->php_namespace_); - swap(cc_enable_arenas_, other->cc_enable_arenas_); + java_package_.Swap(&other->java_package_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + java_outer_classname_.Swap(&other->java_outer_classname_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + go_package_.Swap(&other->go_package_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + objc_class_prefix_.Swap(&other->objc_class_prefix_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + csharp_namespace_.Swap(&other->csharp_namespace_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + swift_prefix_.Swap(&other->swift_prefix_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + php_class_prefix_.Swap(&other->php_class_prefix_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + php_namespace_.Swap(&other->php_namespace_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + php_metadata_namespace_.Swap(&other->php_metadata_namespace_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + ruby_package_.Swap(&other->ruby_package_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(java_multiple_files_, other->java_multiple_files_); swap(java_generate_equals_and_hash_, other->java_generate_equals_and_hash_); swap(java_string_check_utf8_, other->java_string_check_utf8_); @@ -8927,10 +8811,10 @@ void FileOptions::InternalSwap(FileOptions* other) { swap(py_generic_services_, other->py_generic_services_); swap(php_generic_services_, other->php_generic_services_); swap(deprecated_, other->deprecated_); + swap(cc_enable_arenas_, other->cc_enable_arenas_); swap(optimize_for_, other->optimize_for_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); _extensions_.Swap(&other->_extensions_); } @@ -8954,9 +8838,8 @@ const int MessageOptions::kUninterpretedOptionFieldNumber; MessageOptions::MessageOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptions(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.MessageOptions) } @@ -8965,7 +8848,7 @@ MessageOptions::MessageOptions(::google::protobuf::Arena* arena) _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.MessageOptions) @@ -8974,7 +8857,6 @@ MessageOptions::MessageOptions(const MessageOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); @@ -8985,7 +8867,6 @@ MessageOptions::MessageOptions(const MessageOptions& from) } void MessageOptions::SharedCtor() { - _cached_size_ = 0; ::memset(&message_set_wire_format_, 0, static_cast<size_t>( reinterpret_cast<char*>(&map_entry_) - reinterpret_cast<char*>(&message_set_wire_format_)) + sizeof(map_entry_)); @@ -9004,12 +8885,10 @@ void MessageOptions::ArenaDtor(void* object) { MessageOptions* _this = reinterpret_cast< MessageOptions* >(object); (void)_this; } -void MessageOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void MessageOptions::RegisterArenaDtor(::google::protobuf::Arena*) { } void MessageOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* MessageOptions::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -9017,7 +8896,7 @@ const ::google::protobuf::Descriptor* MessageOptions::descriptor() { } const MessageOptions& MessageOptions::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base); return *internal_default_instance(); } @@ -9043,7 +8922,7 @@ bool MessageOptions::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.MessageOptions) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -9281,9 +9160,7 @@ size_t MessageOptions::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -9380,7 +9257,6 @@ void MessageOptions::InternalSwap(MessageOptions* other) { swap(map_entry_, other->map_entry_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); _extensions_.Swap(&other->_extensions_); } @@ -9406,9 +9282,8 @@ const int FieldOptions::kUninterpretedOptionFieldNumber; FieldOptions::FieldOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptions(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FieldOptions) } @@ -9417,7 +9292,7 @@ FieldOptions::FieldOptions(::google::protobuf::Arena* arena) _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.FieldOptions) @@ -9426,7 +9301,6 @@ FieldOptions::FieldOptions(const FieldOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); @@ -9437,7 +9311,6 @@ FieldOptions::FieldOptions(const FieldOptions& from) } void FieldOptions::SharedCtor() { - _cached_size_ = 0; ::memset(&ctype_, 0, static_cast<size_t>( reinterpret_cast<char*>(&jstype_) - reinterpret_cast<char*>(&ctype_)) + sizeof(jstype_)); @@ -9456,12 +9329,10 @@ void FieldOptions::ArenaDtor(void* object) { FieldOptions* _this = reinterpret_cast< FieldOptions* >(object); (void)_this; } -void FieldOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void FieldOptions::RegisterArenaDtor(::google::protobuf::Arena*) { } void FieldOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* FieldOptions::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -9469,7 +9340,7 @@ const ::google::protobuf::Descriptor* FieldOptions::descriptor() { } const FieldOptions& FieldOptions::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base); return *internal_default_instance(); } @@ -9498,7 +9369,7 @@ bool FieldOptions::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FieldOptions) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -9812,9 +9683,7 @@ size_t FieldOptions::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -9919,7 +9788,6 @@ void FieldOptions::InternalSwap(FieldOptions* other) { swap(jstype_, other->jstype_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); _extensions_.Swap(&other->_extensions_); } @@ -9939,9 +9807,8 @@ const int OneofOptions::kUninterpretedOptionFieldNumber; OneofOptions::OneofOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptions(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.OneofOptions) } @@ -9950,7 +9817,7 @@ OneofOptions::OneofOptions(::google::protobuf::Arena* arena) _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.OneofOptions) @@ -9959,7 +9826,6 @@ OneofOptions::OneofOptions(const OneofOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); @@ -9967,7 +9833,6 @@ OneofOptions::OneofOptions(const OneofOptions& from) } void OneofOptions::SharedCtor() { - _cached_size_ = 0; } OneofOptions::~OneofOptions() { @@ -9983,12 +9848,10 @@ void OneofOptions::ArenaDtor(void* object) { OneofOptions* _this = reinterpret_cast< OneofOptions* >(object); (void)_this; } -void OneofOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void OneofOptions::RegisterArenaDtor(::google::protobuf::Arena*) { } void OneofOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* OneofOptions::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -9996,7 +9859,7 @@ const ::google::protobuf::Descriptor* OneofOptions::descriptor() { } const OneofOptions& OneofOptions::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base); return *internal_default_instance(); } @@ -10019,7 +9882,7 @@ bool OneofOptions::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.OneofOptions) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -10137,9 +10000,7 @@ size_t OneofOptions::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -10216,7 +10077,6 @@ void OneofOptions::InternalSwap(OneofOptions* other) { CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_)); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); _extensions_.Swap(&other->_extensions_); } @@ -10238,9 +10098,8 @@ const int EnumOptions::kUninterpretedOptionFieldNumber; EnumOptions::EnumOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptions(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.EnumOptions) } @@ -10249,7 +10108,7 @@ EnumOptions::EnumOptions(::google::protobuf::Arena* arena) _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumOptions) @@ -10258,7 +10117,6 @@ EnumOptions::EnumOptions(const EnumOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); @@ -10269,7 +10127,6 @@ EnumOptions::EnumOptions(const EnumOptions& from) } void EnumOptions::SharedCtor() { - _cached_size_ = 0; ::memset(&allow_alias_, 0, static_cast<size_t>( reinterpret_cast<char*>(&deprecated_) - reinterpret_cast<char*>(&allow_alias_)) + sizeof(deprecated_)); @@ -10288,12 +10145,10 @@ void EnumOptions::ArenaDtor(void* object) { EnumOptions* _this = reinterpret_cast< EnumOptions* >(object); (void)_this; } -void EnumOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void EnumOptions::RegisterArenaDtor(::google::protobuf::Arena*) { } void EnumOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* EnumOptions::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -10301,7 +10156,7 @@ const ::google::protobuf::Descriptor* EnumOptions::descriptor() { } const EnumOptions& EnumOptions::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base); return *internal_default_instance(); } @@ -10327,7 +10182,7 @@ bool EnumOptions::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumOptions) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -10507,9 +10362,7 @@ size_t EnumOptions::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -10598,7 +10451,6 @@ void EnumOptions::InternalSwap(EnumOptions* other) { swap(deprecated_, other->deprecated_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); _extensions_.Swap(&other->_extensions_); } @@ -10619,9 +10471,8 @@ const int EnumValueOptions::kUninterpretedOptionFieldNumber; EnumValueOptions::EnumValueOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptions(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.EnumValueOptions) } @@ -10630,7 +10481,7 @@ EnumValueOptions::EnumValueOptions(::google::protobuf::Arena* arena) _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValueOptions) @@ -10639,7 +10490,6 @@ EnumValueOptions::EnumValueOptions(const EnumValueOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); @@ -10648,7 +10498,6 @@ EnumValueOptions::EnumValueOptions(const EnumValueOptions& from) } void EnumValueOptions::SharedCtor() { - _cached_size_ = 0; deprecated_ = false; } @@ -10665,12 +10514,10 @@ void EnumValueOptions::ArenaDtor(void* object) { EnumValueOptions* _this = reinterpret_cast< EnumValueOptions* >(object); (void)_this; } -void EnumValueOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void EnumValueOptions::RegisterArenaDtor(::google::protobuf::Arena*) { } void EnumValueOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* EnumValueOptions::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -10678,7 +10525,7 @@ const ::google::protobuf::Descriptor* EnumValueOptions::descriptor() { } const EnumValueOptions& EnumValueOptions::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base); return *internal_default_instance(); } @@ -10702,7 +10549,7 @@ bool EnumValueOptions::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumValueOptions) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -10851,9 +10698,7 @@ size_t EnumValueOptions::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -10934,7 +10779,6 @@ void EnumValueOptions::InternalSwap(EnumValueOptions* other) { swap(deprecated_, other->deprecated_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); _extensions_.Swap(&other->_extensions_); } @@ -10955,9 +10799,8 @@ const int ServiceOptions::kUninterpretedOptionFieldNumber; ServiceOptions::ServiceOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptions(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.ServiceOptions) } @@ -10966,7 +10809,7 @@ ServiceOptions::ServiceOptions(::google::protobuf::Arena* arena) _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.ServiceOptions) @@ -10975,7 +10818,6 @@ ServiceOptions::ServiceOptions(const ServiceOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); @@ -10984,7 +10826,6 @@ ServiceOptions::ServiceOptions(const ServiceOptions& from) } void ServiceOptions::SharedCtor() { - _cached_size_ = 0; deprecated_ = false; } @@ -11001,12 +10842,10 @@ void ServiceOptions::ArenaDtor(void* object) { ServiceOptions* _this = reinterpret_cast< ServiceOptions* >(object); (void)_this; } -void ServiceOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void ServiceOptions::RegisterArenaDtor(::google::protobuf::Arena*) { } void ServiceOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* ServiceOptions::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -11014,7 +10853,7 @@ const ::google::protobuf::Descriptor* ServiceOptions::descriptor() { } const ServiceOptions& ServiceOptions::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base); return *internal_default_instance(); } @@ -11038,7 +10877,7 @@ bool ServiceOptions::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.ServiceOptions) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -11187,9 +11026,7 @@ size_t ServiceOptions::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -11270,7 +11107,6 @@ void ServiceOptions::InternalSwap(ServiceOptions* other) { swap(deprecated_, other->deprecated_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); _extensions_.Swap(&other->_extensions_); } @@ -11292,9 +11128,8 @@ const int MethodOptions::kUninterpretedOptionFieldNumber; MethodOptions::MethodOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptions(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.MethodOptions) } @@ -11303,7 +11138,7 @@ MethodOptions::MethodOptions(::google::protobuf::Arena* arena) _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.MethodOptions) @@ -11312,7 +11147,6 @@ MethodOptions::MethodOptions(const MethodOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); @@ -11323,7 +11157,6 @@ MethodOptions::MethodOptions(const MethodOptions& from) } void MethodOptions::SharedCtor() { - _cached_size_ = 0; ::memset(&deprecated_, 0, static_cast<size_t>( reinterpret_cast<char*>(&idempotency_level_) - reinterpret_cast<char*>(&deprecated_)) + sizeof(idempotency_level_)); @@ -11342,12 +11175,10 @@ void MethodOptions::ArenaDtor(void* object) { MethodOptions* _this = reinterpret_cast< MethodOptions* >(object); (void)_this; } -void MethodOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void MethodOptions::RegisterArenaDtor(::google::protobuf::Arena*) { } void MethodOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* MethodOptions::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -11355,7 +11186,7 @@ const ::google::protobuf::Descriptor* MethodOptions::descriptor() { } const MethodOptions& MethodOptions::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base); return *internal_default_instance(); } @@ -11384,7 +11215,7 @@ bool MethodOptions::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.MethodOptions) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -11573,9 +11404,7 @@ size_t MethodOptions::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -11664,7 +11493,6 @@ void MethodOptions::InternalSwap(MethodOptions* other) { swap(idempotency_level_, other->idempotency_level_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); _extensions_.Swap(&other->_extensions_); } @@ -11685,16 +11513,15 @@ const int UninterpretedOption_NamePart::kIsExtensionFieldNumber; UninterpretedOption_NamePart::UninterpretedOption_NamePart() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePart(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption_NamePart.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.UninterpretedOption.NamePart) } UninterpretedOption_NamePart::UninterpretedOption_NamePart(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePart(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption_NamePart.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.UninterpretedOption.NamePart) @@ -11702,8 +11529,7 @@ UninterpretedOption_NamePart::UninterpretedOption_NamePart(::google::protobuf::A UninterpretedOption_NamePart::UninterpretedOption_NamePart(const UninterpretedOption_NamePart& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_part_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_name_part()) { @@ -11715,7 +11541,6 @@ UninterpretedOption_NamePart::UninterpretedOption_NamePart(const UninterpretedOp } void UninterpretedOption_NamePart::SharedCtor() { - _cached_size_ = 0; name_part_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); is_extension_ = false; } @@ -11734,12 +11559,10 @@ void UninterpretedOption_NamePart::ArenaDtor(void* object) { UninterpretedOption_NamePart* _this = reinterpret_cast< UninterpretedOption_NamePart* >(object); (void)_this; } -void UninterpretedOption_NamePart::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void UninterpretedOption_NamePart::RegisterArenaDtor(::google::protobuf::Arena*) { } void UninterpretedOption_NamePart::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* UninterpretedOption_NamePart::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -11747,7 +11570,7 @@ const ::google::protobuf::Descriptor* UninterpretedOption_NamePart::descriptor() } const UninterpretedOption_NamePart& UninterpretedOption_NamePart::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePart(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption_NamePart.base); return *internal_default_instance(); } @@ -11760,8 +11583,7 @@ void UninterpretedOption_NamePart::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_part_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_part_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + name_part_.ClearNonDefaultToEmpty(); } is_extension_ = false; _has_bits_.Clear(); @@ -11774,7 +11596,7 @@ bool UninterpretedOption_NamePart::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.UninterpretedOption.NamePart) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -11929,9 +11751,7 @@ size_t UninterpretedOption_NamePart::ByteSizeLong() const { total_size += RequiredFieldsByteSizeFallback(); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -12009,11 +11829,11 @@ void UninterpretedOption_NamePart::UnsafeArenaSwap(UninterpretedOption_NamePart* } void UninterpretedOption_NamePart::InternalSwap(UninterpretedOption_NamePart* other) { using std::swap; - name_part_.Swap(&other->name_part_); + name_part_.Swap(&other->name_part_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(is_extension_, other->is_extension_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata UninterpretedOption_NamePart::GetMetadata() const { @@ -12038,9 +11858,8 @@ const int UninterpretedOption::kAggregateValueFieldNumber; UninterpretedOption::UninterpretedOption() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.UninterpretedOption) } @@ -12048,7 +11867,7 @@ UninterpretedOption::UninterpretedOption(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), name_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.UninterpretedOption) @@ -12057,7 +11876,6 @@ UninterpretedOption::UninterpretedOption(const UninterpretedOption& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), name_(from.name_) { _internal_metadata_.MergeFrom(from._internal_metadata_); identifier_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -12082,7 +11900,6 @@ UninterpretedOption::UninterpretedOption(const UninterpretedOption& from) } void UninterpretedOption::SharedCtor() { - _cached_size_ = 0; identifier_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); aggregate_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -12107,12 +11924,10 @@ void UninterpretedOption::ArenaDtor(void* object) { UninterpretedOption* _this = reinterpret_cast< UninterpretedOption* >(object); (void)_this; } -void UninterpretedOption::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void UninterpretedOption::RegisterArenaDtor(::google::protobuf::Arena*) { } void UninterpretedOption::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* UninterpretedOption::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -12120,7 +11935,7 @@ const ::google::protobuf::Descriptor* UninterpretedOption::descriptor() { } const UninterpretedOption& UninterpretedOption::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base); return *internal_default_instance(); } @@ -12135,16 +11950,13 @@ void UninterpretedOption::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 7u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!identifier_value_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - identifier_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + identifier_value_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(!string_value_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - string_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + string_value_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { - GOOGLE_DCHECK(!aggregate_value_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - aggregate_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + aggregate_value_.ClearNonDefaultToEmpty(); } } if (cached_has_bits & 56u) { @@ -12162,7 +11974,7 @@ bool UninterpretedOption::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.UninterpretedOption) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -12479,9 +12291,7 @@ size_t UninterpretedOption::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -12573,15 +12383,17 @@ void UninterpretedOption::UnsafeArenaSwap(UninterpretedOption* other) { void UninterpretedOption::InternalSwap(UninterpretedOption* other) { using std::swap; CastToBase(&name_)->InternalSwap(CastToBase(&other->name_)); - identifier_value_.Swap(&other->identifier_value_); - string_value_.Swap(&other->string_value_); - aggregate_value_.Swap(&other->aggregate_value_); + identifier_value_.Swap(&other->identifier_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + string_value_.Swap(&other->string_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + aggregate_value_.Swap(&other->aggregate_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(positive_int_value_, other->positive_int_value_); swap(negative_int_value_, other->negative_int_value_); swap(double_value_, other->double_value_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata UninterpretedOption::GetMetadata() const { @@ -12604,9 +12416,8 @@ const int SourceCodeInfo_Location::kLeadingDetachedCommentsFieldNumber; SourceCodeInfo_Location::SourceCodeInfo_Location() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_Location(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo_Location.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.SourceCodeInfo.Location) } @@ -12616,7 +12427,7 @@ SourceCodeInfo_Location::SourceCodeInfo_Location(::google::protobuf::Arena* aren path_(arena), span_(arena), leading_detached_comments_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_Location(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo_Location.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.SourceCodeInfo.Location) @@ -12625,7 +12436,6 @@ SourceCodeInfo_Location::SourceCodeInfo_Location(const SourceCodeInfo_Location& : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), path_(from.path_), span_(from.span_), leading_detached_comments_(from.leading_detached_comments_) { @@ -12644,7 +12454,6 @@ SourceCodeInfo_Location::SourceCodeInfo_Location(const SourceCodeInfo_Location& } void SourceCodeInfo_Location::SharedCtor() { - _cached_size_ = 0; leading_comments_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); trailing_comments_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } @@ -12664,12 +12473,10 @@ void SourceCodeInfo_Location::ArenaDtor(void* object) { SourceCodeInfo_Location* _this = reinterpret_cast< SourceCodeInfo_Location* >(object); (void)_this; } -void SourceCodeInfo_Location::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void SourceCodeInfo_Location::RegisterArenaDtor(::google::protobuf::Arena*) { } void SourceCodeInfo_Location::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* SourceCodeInfo_Location::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -12677,7 +12484,7 @@ const ::google::protobuf::Descriptor* SourceCodeInfo_Location::descriptor() { } const SourceCodeInfo_Location& SourceCodeInfo_Location::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_Location(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo_Location.base); return *internal_default_instance(); } @@ -12694,12 +12501,10 @@ void SourceCodeInfo_Location::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!leading_comments_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - leading_comments_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + leading_comments_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(!trailing_comments_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - trailing_comments_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + trailing_comments_.ClearNonDefaultToEmpty(); } } _has_bits_.Clear(); @@ -12712,7 +12517,7 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.SourceCodeInfo.Location) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -13029,9 +12834,7 @@ size_t SourceCodeInfo_Location::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -13113,11 +12916,12 @@ void SourceCodeInfo_Location::InternalSwap(SourceCodeInfo_Location* other) { path_.InternalSwap(&other->path_); span_.InternalSwap(&other->span_); leading_detached_comments_.InternalSwap(CastToBase(&other->leading_detached_comments_)); - leading_comments_.Swap(&other->leading_comments_); - trailing_comments_.Swap(&other->trailing_comments_); + leading_comments_.Swap(&other->leading_comments_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + trailing_comments_.Swap(&other->trailing_comments_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata SourceCodeInfo_Location::GetMetadata() const { @@ -13136,9 +12940,8 @@ const int SourceCodeInfo::kLocationFieldNumber; SourceCodeInfo::SourceCodeInfo() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.SourceCodeInfo) } @@ -13146,7 +12949,7 @@ SourceCodeInfo::SourceCodeInfo(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), location_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.SourceCodeInfo) @@ -13155,14 +12958,12 @@ SourceCodeInfo::SourceCodeInfo(const SourceCodeInfo& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), location_(from.location_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.SourceCodeInfo) } void SourceCodeInfo::SharedCtor() { - _cached_size_ = 0; } SourceCodeInfo::~SourceCodeInfo() { @@ -13178,12 +12979,10 @@ void SourceCodeInfo::ArenaDtor(void* object) { SourceCodeInfo* _this = reinterpret_cast< SourceCodeInfo* >(object); (void)_this; } -void SourceCodeInfo::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void SourceCodeInfo::RegisterArenaDtor(::google::protobuf::Arena*) { } void SourceCodeInfo::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* SourceCodeInfo::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -13191,7 +12990,7 @@ const ::google::protobuf::Descriptor* SourceCodeInfo::descriptor() { } const SourceCodeInfo& SourceCodeInfo::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base); return *internal_default_instance(); } @@ -13213,7 +13012,7 @@ bool SourceCodeInfo::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.SourceCodeInfo) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -13315,9 +13114,7 @@ size_t SourceCodeInfo::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -13388,7 +13185,6 @@ void SourceCodeInfo::InternalSwap(SourceCodeInfo* other) { CastToBase(&location_)->InternalSwap(CastToBase(&other->location_)); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata SourceCodeInfo::GetMetadata() const { @@ -13410,9 +13206,8 @@ const int GeneratedCodeInfo_Annotation::kEndFieldNumber; GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_Annotation(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo_Annotation.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.GeneratedCodeInfo.Annotation) } @@ -13420,7 +13215,7 @@ GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(::google::protobuf::A : ::google::protobuf::Message(), _internal_metadata_(arena), path_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_Annotation(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo_Annotation.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.GeneratedCodeInfo.Annotation) @@ -13429,7 +13224,6 @@ GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(const GeneratedCodeIn : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), path_(from.path_) { _internal_metadata_.MergeFrom(from._internal_metadata_); source_file_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -13444,7 +13238,6 @@ GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(const GeneratedCodeIn } void GeneratedCodeInfo_Annotation::SharedCtor() { - _cached_size_ = 0; source_file_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&begin_, 0, static_cast<size_t>( reinterpret_cast<char*>(&end_) - @@ -13465,12 +13258,10 @@ void GeneratedCodeInfo_Annotation::ArenaDtor(void* object) { GeneratedCodeInfo_Annotation* _this = reinterpret_cast< GeneratedCodeInfo_Annotation* >(object); (void)_this; } -void GeneratedCodeInfo_Annotation::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void GeneratedCodeInfo_Annotation::RegisterArenaDtor(::google::protobuf::Arena*) { } void GeneratedCodeInfo_Annotation::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* GeneratedCodeInfo_Annotation::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -13478,7 +13269,7 @@ const ::google::protobuf::Descriptor* GeneratedCodeInfo_Annotation::descriptor() } const GeneratedCodeInfo_Annotation& GeneratedCodeInfo_Annotation::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_Annotation(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo_Annotation.base); return *internal_default_instance(); } @@ -13492,8 +13283,7 @@ void GeneratedCodeInfo_Annotation::Clear() { path_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!source_file_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - source_file_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + source_file_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 6u) { ::memset(&begin_, 0, static_cast<size_t>( @@ -13510,7 +13300,7 @@ bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.GeneratedCodeInfo.Annotation) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -13741,9 +13531,7 @@ size_t GeneratedCodeInfo_Annotation::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -13825,12 +13613,12 @@ void GeneratedCodeInfo_Annotation::UnsafeArenaSwap(GeneratedCodeInfo_Annotation* void GeneratedCodeInfo_Annotation::InternalSwap(GeneratedCodeInfo_Annotation* other) { using std::swap; path_.InternalSwap(&other->path_); - source_file_.Swap(&other->source_file_); + source_file_.Swap(&other->source_file_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(begin_, other->begin_); swap(end_, other->end_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata GeneratedCodeInfo_Annotation::GetMetadata() const { @@ -13849,9 +13637,8 @@ const int GeneratedCodeInfo::kAnnotationFieldNumber; GeneratedCodeInfo::GeneratedCodeInfo() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.GeneratedCodeInfo) } @@ -13859,7 +13646,7 @@ GeneratedCodeInfo::GeneratedCodeInfo(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), annotation_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.GeneratedCodeInfo) @@ -13868,14 +13655,12 @@ GeneratedCodeInfo::GeneratedCodeInfo(const GeneratedCodeInfo& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), annotation_(from.annotation_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.GeneratedCodeInfo) } void GeneratedCodeInfo::SharedCtor() { - _cached_size_ = 0; } GeneratedCodeInfo::~GeneratedCodeInfo() { @@ -13891,12 +13676,10 @@ void GeneratedCodeInfo::ArenaDtor(void* object) { GeneratedCodeInfo* _this = reinterpret_cast< GeneratedCodeInfo* >(object); (void)_this; } -void GeneratedCodeInfo::RegisterArenaDtor(::google::protobuf::Arena* arena) { +void GeneratedCodeInfo::RegisterArenaDtor(::google::protobuf::Arena*) { } void GeneratedCodeInfo::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* GeneratedCodeInfo::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -13904,7 +13687,7 @@ const ::google::protobuf::Descriptor* GeneratedCodeInfo::descriptor() { } const GeneratedCodeInfo& GeneratedCodeInfo::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo.base); return *internal_default_instance(); } @@ -13926,7 +13709,7 @@ bool GeneratedCodeInfo::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.GeneratedCodeInfo) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -14028,9 +13811,7 @@ size_t GeneratedCodeInfo::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -14101,7 +13882,6 @@ void GeneratedCodeInfo::InternalSwap(GeneratedCodeInfo* other) { CastToBase(&annotation_)->InternalSwap(CastToBase(&other->annotation_)); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata GeneratedCodeInfo::GetMetadata() const { @@ -14115,85 +13895,85 @@ void GeneratedCodeInfo::InternalSwap(GeneratedCodeInfo* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileDescriptorSet* Arena::CreateMessage< ::google::protobuf::FileDescriptorSet >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileDescriptorSet* Arena::CreateMaybeMessage< ::google::protobuf::FileDescriptorSet >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::FileDescriptorSet >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileDescriptorProto* Arena::CreateMessage< ::google::protobuf::FileDescriptorProto >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::FileDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::FileDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMessage< ::google::protobuf::DescriptorProto_ExtensionRange >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto_ExtensionRange >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::DescriptorProto_ExtensionRange >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMessage< ::google::protobuf::DescriptorProto_ReservedRange >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto_ReservedRange >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::DescriptorProto_ReservedRange >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto* Arena::CreateMessage< ::google::protobuf::DescriptorProto >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::DescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ExtensionRangeOptions* Arena::CreateMessage< ::google::protobuf::ExtensionRangeOptions >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ExtensionRangeOptions* Arena::CreateMaybeMessage< ::google::protobuf::ExtensionRangeOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::ExtensionRangeOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldDescriptorProto* Arena::CreateMessage< ::google::protobuf::FieldDescriptorProto >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::FieldDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::FieldDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::OneofDescriptorProto* Arena::CreateMessage< ::google::protobuf::OneofDescriptorProto >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::OneofDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::OneofDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::OneofDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMessage< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMaybeMessage< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumDescriptorProto* Arena::CreateMessage< ::google::protobuf::EnumDescriptorProto >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::EnumDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::EnumDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMessage< ::google::protobuf::EnumValueDescriptorProto >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::EnumValueDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::EnumValueDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ServiceDescriptorProto* Arena::CreateMessage< ::google::protobuf::ServiceDescriptorProto >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ServiceDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::ServiceDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::ServiceDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MethodDescriptorProto* Arena::CreateMessage< ::google::protobuf::MethodDescriptorProto >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MethodDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::MethodDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::MethodDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileOptions* Arena::CreateMessage< ::google::protobuf::FileOptions >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileOptions* Arena::CreateMaybeMessage< ::google::protobuf::FileOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::FileOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MessageOptions* Arena::CreateMessage< ::google::protobuf::MessageOptions >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MessageOptions* Arena::CreateMaybeMessage< ::google::protobuf::MessageOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::MessageOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldOptions* Arena::CreateMessage< ::google::protobuf::FieldOptions >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldOptions* Arena::CreateMaybeMessage< ::google::protobuf::FieldOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::FieldOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::OneofOptions* Arena::CreateMessage< ::google::protobuf::OneofOptions >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::OneofOptions* Arena::CreateMaybeMessage< ::google::protobuf::OneofOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::OneofOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumOptions* Arena::CreateMessage< ::google::protobuf::EnumOptions >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumOptions* Arena::CreateMaybeMessage< ::google::protobuf::EnumOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::EnumOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValueOptions* Arena::CreateMessage< ::google::protobuf::EnumValueOptions >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValueOptions* Arena::CreateMaybeMessage< ::google::protobuf::EnumValueOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::EnumValueOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ServiceOptions* Arena::CreateMessage< ::google::protobuf::ServiceOptions >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ServiceOptions* Arena::CreateMaybeMessage< ::google::protobuf::ServiceOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::ServiceOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MethodOptions* Arena::CreateMessage< ::google::protobuf::MethodOptions >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MethodOptions* Arena::CreateMaybeMessage< ::google::protobuf::MethodOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::MethodOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMessage< ::google::protobuf::UninterpretedOption_NamePart >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMaybeMessage< ::google::protobuf::UninterpretedOption_NamePart >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::UninterpretedOption_NamePart >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UninterpretedOption* Arena::CreateMessage< ::google::protobuf::UninterpretedOption >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UninterpretedOption* Arena::CreateMaybeMessage< ::google::protobuf::UninterpretedOption >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::UninterpretedOption >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMessage< ::google::protobuf::SourceCodeInfo_Location >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMaybeMessage< ::google::protobuf::SourceCodeInfo_Location >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::SourceCodeInfo_Location >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceCodeInfo* Arena::CreateMessage< ::google::protobuf::SourceCodeInfo >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceCodeInfo* Arena::CreateMaybeMessage< ::google::protobuf::SourceCodeInfo >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::SourceCodeInfo >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMessage< ::google::protobuf::GeneratedCodeInfo_Annotation >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMaybeMessage< ::google::protobuf::GeneratedCodeInfo_Annotation >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::GeneratedCodeInfo_Annotation >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::GeneratedCodeInfo* Arena::CreateMessage< ::google::protobuf::GeneratedCodeInfo >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::GeneratedCodeInfo* Arena::CreateMaybeMessage< ::google::protobuf::GeneratedCodeInfo >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::GeneratedCodeInfo >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/descriptor.pb.h b/src/google/protobuf/descriptor.pb.h index 4ec0a5b4..5e7a05d5 100644 --- a/src/google/protobuf/descriptor.pb.h +++ b/src/google/protobuf/descriptor.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/descriptor.proto -#ifndef PROTOBUF_google_2fprotobuf_2fdescriptor_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2fdescriptor_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fdescriptor_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2fdescriptor_2eproto #include <string> @@ -24,6 +24,7 @@ #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> +#include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export @@ -31,6 +32,7 @@ #include <google/protobuf/generated_enum_reflection.h> #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto { // Internal implementation detail -- do not use these members. @@ -43,89 +45,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsFileDescriptorSetImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsFileDescriptorSet(); -void LIBPROTOBUF_EXPORT InitDefaultsFileDescriptorProtoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsFileDescriptorProto(); -void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto_ExtensionRangeImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto_ExtensionRange(); -void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto_ReservedRangeImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto_ReservedRange(); -void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProtoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto(); -void LIBPROTOBUF_EXPORT InitDefaultsExtensionRangeOptionsImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsExtensionRangeOptions(); -void LIBPROTOBUF_EXPORT InitDefaultsFieldDescriptorProtoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsFieldDescriptorProto(); -void LIBPROTOBUF_EXPORT InitDefaultsOneofDescriptorProtoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsOneofDescriptorProto(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumDescriptorProto_EnumReservedRange(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumDescriptorProtoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumDescriptorProto(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumValueDescriptorProtoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumValueDescriptorProto(); -void LIBPROTOBUF_EXPORT InitDefaultsServiceDescriptorProtoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsServiceDescriptorProto(); -void LIBPROTOBUF_EXPORT InitDefaultsMethodDescriptorProtoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsMethodDescriptorProto(); -void LIBPROTOBUF_EXPORT InitDefaultsFileOptionsImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsFileOptions(); -void LIBPROTOBUF_EXPORT InitDefaultsMessageOptionsImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsMessageOptions(); -void LIBPROTOBUF_EXPORT InitDefaultsFieldOptionsImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsFieldOptions(); -void LIBPROTOBUF_EXPORT InitDefaultsOneofOptionsImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsOneofOptions(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumOptionsImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumOptions(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumValueOptionsImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumValueOptions(); -void LIBPROTOBUF_EXPORT InitDefaultsServiceOptionsImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsServiceOptions(); -void LIBPROTOBUF_EXPORT InitDefaultsMethodOptionsImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsMethodOptions(); -void LIBPROTOBUF_EXPORT InitDefaultsUninterpretedOption_NamePartImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsUninterpretedOption_NamePart(); -void LIBPROTOBUF_EXPORT InitDefaultsUninterpretedOptionImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsUninterpretedOption(); -void LIBPROTOBUF_EXPORT InitDefaultsSourceCodeInfo_LocationImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsSourceCodeInfo_Location(); -void LIBPROTOBUF_EXPORT InitDefaultsSourceCodeInfoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsSourceCodeInfo(); -void LIBPROTOBUF_EXPORT InitDefaultsGeneratedCodeInfo_AnnotationImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsGeneratedCodeInfo_Annotation(); -void LIBPROTOBUF_EXPORT InitDefaultsGeneratedCodeInfoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsGeneratedCodeInfo(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsFileDescriptorSet(); - InitDefaultsFileDescriptorProto(); - InitDefaultsDescriptorProto_ExtensionRange(); - InitDefaultsDescriptorProto_ReservedRange(); - InitDefaultsDescriptorProto(); - InitDefaultsExtensionRangeOptions(); - InitDefaultsFieldDescriptorProto(); - InitDefaultsOneofDescriptorProto(); - InitDefaultsEnumDescriptorProto_EnumReservedRange(); - InitDefaultsEnumDescriptorProto(); - InitDefaultsEnumValueDescriptorProto(); - InitDefaultsServiceDescriptorProto(); - InitDefaultsMethodDescriptorProto(); - InitDefaultsFileOptions(); - InitDefaultsMessageOptions(); - InitDefaultsFieldOptions(); - InitDefaultsOneofOptions(); - InitDefaultsEnumOptions(); - InitDefaultsEnumValueOptions(); - InitDefaultsServiceOptions(); - InitDefaultsMethodOptions(); - InitDefaultsUninterpretedOption_NamePart(); - InitDefaultsUninterpretedOption(); - InitDefaultsSourceCodeInfo_Location(); - InitDefaultsSourceCodeInfo(); - InitDefaultsGeneratedCodeInfo_Annotation(); - InitDefaultsGeneratedCodeInfo(); -} } // namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto namespace google { namespace protobuf { @@ -214,33 +133,33 @@ LIBPROTOBUF_EXPORT extern UninterpretedOption_NamePartDefaultTypeInternal _Unint } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto* Arena::CreateMessage< ::google::protobuf::DescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMessage< ::google::protobuf::DescriptorProto_ExtensionRange>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMessage< ::google::protobuf::DescriptorProto_ReservedRange>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto* Arena::CreateMessage< ::google::protobuf::EnumDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMessage< ::google::protobuf::EnumDescriptorProto_EnumReservedRange>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumOptions* Arena::CreateMessage< ::google::protobuf::EnumOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMessage< ::google::protobuf::EnumValueDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValueOptions* Arena::CreateMessage< ::google::protobuf::EnumValueOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::ExtensionRangeOptions* Arena::CreateMessage< ::google::protobuf::ExtensionRangeOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldDescriptorProto* Arena::CreateMessage< ::google::protobuf::FieldDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldOptions* Arena::CreateMessage< ::google::protobuf::FieldOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileDescriptorProto* Arena::CreateMessage< ::google::protobuf::FileDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileDescriptorSet* Arena::CreateMessage< ::google::protobuf::FileDescriptorSet>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileOptions* Arena::CreateMessage< ::google::protobuf::FileOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo* Arena::CreateMessage< ::google::protobuf::GeneratedCodeInfo>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMessage< ::google::protobuf::GeneratedCodeInfo_Annotation>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::MessageOptions* Arena::CreateMessage< ::google::protobuf::MessageOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::MethodDescriptorProto* Arena::CreateMessage< ::google::protobuf::MethodDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::MethodOptions* Arena::CreateMessage< ::google::protobuf::MethodOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::OneofDescriptorProto* Arena::CreateMessage< ::google::protobuf::OneofDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::OneofOptions* Arena::CreateMessage< ::google::protobuf::OneofOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::ServiceDescriptorProto* Arena::CreateMessage< ::google::protobuf::ServiceDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::ServiceOptions* Arena::CreateMessage< ::google::protobuf::ServiceOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo* Arena::CreateMessage< ::google::protobuf::SourceCodeInfo>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMessage< ::google::protobuf::SourceCodeInfo_Location>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::UninterpretedOption* Arena::CreateMessage< ::google::protobuf::UninterpretedOption>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMessage< ::google::protobuf::UninterpretedOption_NamePart>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto_ExtensionRange>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto_ReservedRange>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::EnumDescriptorProto>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMaybeMessage<::google::protobuf::EnumDescriptorProto_EnumReservedRange>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumOptions* Arena::CreateMaybeMessage<::google::protobuf::EnumOptions>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::EnumValueDescriptorProto>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValueOptions* Arena::CreateMaybeMessage<::google::protobuf::EnumValueOptions>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::ExtensionRangeOptions* Arena::CreateMaybeMessage<::google::protobuf::ExtensionRangeOptions>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::FieldDescriptorProto>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldOptions* Arena::CreateMaybeMessage<::google::protobuf::FieldOptions>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::FileDescriptorProto>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileDescriptorSet* Arena::CreateMaybeMessage<::google::protobuf::FileDescriptorSet>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileOptions* Arena::CreateMaybeMessage<::google::protobuf::FileOptions>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo* Arena::CreateMaybeMessage<::google::protobuf::GeneratedCodeInfo>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMaybeMessage<::google::protobuf::GeneratedCodeInfo_Annotation>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::MessageOptions* Arena::CreateMaybeMessage<::google::protobuf::MessageOptions>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::MethodDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::MethodDescriptorProto>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::MethodOptions* Arena::CreateMaybeMessage<::google::protobuf::MethodOptions>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::OneofDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::OneofDescriptorProto>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::OneofOptions* Arena::CreateMaybeMessage<::google::protobuf::OneofOptions>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::ServiceDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::ServiceDescriptorProto>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::ServiceOptions* Arena::CreateMaybeMessage<::google::protobuf::ServiceOptions>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo* Arena::CreateMaybeMessage<::google::protobuf::SourceCodeInfo>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMaybeMessage<::google::protobuf::SourceCodeInfo_Location>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::UninterpretedOption* Arena::CreateMaybeMessage<::google::protobuf::UninterpretedOption>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMaybeMessage<::google::protobuf::UninterpretedOption_NamePart>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -416,10 +335,10 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -430,7 +349,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message return reinterpret_cast<const FileDescriptorSet*>( &_FileDescriptorSet_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void UnsafeArenaSwap(FileDescriptorSet* other); @@ -441,32 +360,33 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message // implements Message ---------------------------------------------- - inline FileDescriptorSet* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<FileDescriptorSet>(NULL); + inline FileDescriptorSet* New() const final { + return CreateMaybeMessage<FileDescriptorSet>(NULL); } - FileDescriptorSet* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<FileDescriptorSet>(arena); + FileDescriptorSet* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<FileDescriptorSet>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const FileDescriptorSet& from); void MergeFrom(const FileDescriptorSet& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(FileDescriptorSet* other); protected: explicit FileDescriptorSet(::google::protobuf::Arena* arena); @@ -482,7 +402,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -508,10 +428,9 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto > file_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorSetImpl(); }; // ------------------------------------------------------------------- @@ -548,10 +467,10 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -562,7 +481,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag return reinterpret_cast<const FileDescriptorProto*>( &_FileDescriptorProto_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 1; void UnsafeArenaSwap(FileDescriptorProto* other); @@ -573,32 +492,33 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag // implements Message ---------------------------------------------- - inline FileDescriptorProto* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<FileDescriptorProto>(NULL); + inline FileDescriptorProto* New() const final { + return CreateMaybeMessage<FileDescriptorProto>(NULL); } - FileDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<FileDescriptorProto>(arena); + FileDescriptorProto* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<FileDescriptorProto>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const FileDescriptorProto& from); void MergeFrom(const FileDescriptorProto& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(FileDescriptorProto* other); protected: explicit FileDescriptorProto(::google::protobuf::Arena* arena); @@ -614,7 +534,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -790,6 +710,9 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 8; + private: + const ::google::protobuf::FileOptions& _internal_options() const; + public: const ::google::protobuf::FileOptions& options() const; ::google::protobuf::FileOptions* release_options(); ::google::protobuf::FileOptions* mutable_options(); @@ -802,6 +725,9 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag bool has_source_code_info() const; void clear_source_code_info(); static const int kSourceCodeInfoFieldNumber = 9; + private: + const ::google::protobuf::SourceCodeInfo& _internal_source_code_info() const; + public: const ::google::protobuf::SourceCodeInfo& source_code_info() const; ::google::protobuf::SourceCodeInfo* release_source_code_info(); ::google::protobuf::SourceCodeInfo* mutable_source_code_info(); @@ -828,7 +754,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::std::string> dependency_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto > message_type_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto > enum_type_; @@ -842,7 +768,6 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag ::google::protobuf::FileOptions* options_; ::google::protobuf::SourceCodeInfo* source_code_info_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProtoImpl(); }; // ------------------------------------------------------------------- @@ -879,10 +804,10 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -893,7 +818,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto return reinterpret_cast<const DescriptorProto_ExtensionRange*>( &_DescriptorProto_ExtensionRange_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 2; void UnsafeArenaSwap(DescriptorProto_ExtensionRange* other); @@ -904,32 +829,33 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto // implements Message ---------------------------------------------- - inline DescriptorProto_ExtensionRange* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<DescriptorProto_ExtensionRange>(NULL); + inline DescriptorProto_ExtensionRange* New() const final { + return CreateMaybeMessage<DescriptorProto_ExtensionRange>(NULL); } - DescriptorProto_ExtensionRange* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<DescriptorProto_ExtensionRange>(arena); + DescriptorProto_ExtensionRange* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<DescriptorProto_ExtensionRange>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const DescriptorProto_ExtensionRange& from); void MergeFrom(const DescriptorProto_ExtensionRange& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(DescriptorProto_ExtensionRange* other); protected: explicit DescriptorProto_ExtensionRange(::google::protobuf::Arena* arena); @@ -945,7 +871,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -955,6 +881,9 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 3; + private: + const ::google::protobuf::ExtensionRangeOptions& _internal_options() const; + public: const ::google::protobuf::ExtensionRangeOptions& options() const; ::google::protobuf::ExtensionRangeOptions* release_options(); ::google::protobuf::ExtensionRangeOptions* mutable_options(); @@ -991,12 +920,11 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::ExtensionRangeOptions* options_; ::google::protobuf::int32 start_; ::google::protobuf::int32 end_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRangeImpl(); }; // ------------------------------------------------------------------- @@ -1033,10 +961,10 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -1047,7 +975,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob return reinterpret_cast<const DescriptorProto_ReservedRange*>( &_DescriptorProto_ReservedRange_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 3; void UnsafeArenaSwap(DescriptorProto_ReservedRange* other); @@ -1058,32 +986,33 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob // implements Message ---------------------------------------------- - inline DescriptorProto_ReservedRange* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<DescriptorProto_ReservedRange>(NULL); + inline DescriptorProto_ReservedRange* New() const final { + return CreateMaybeMessage<DescriptorProto_ReservedRange>(NULL); } - DescriptorProto_ReservedRange* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<DescriptorProto_ReservedRange>(arena); + DescriptorProto_ReservedRange* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<DescriptorProto_ReservedRange>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const DescriptorProto_ReservedRange& from); void MergeFrom(const DescriptorProto_ReservedRange& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(DescriptorProto_ReservedRange* other); protected: explicit DescriptorProto_ReservedRange(::google::protobuf::Arena* arena); @@ -1099,7 +1028,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -1131,11 +1060,10 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::int32 start_; ::google::protobuf::int32 end_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRangeImpl(); }; // ------------------------------------------------------------------- @@ -1172,10 +1100,10 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -1186,7 +1114,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* return reinterpret_cast<const DescriptorProto*>( &_DescriptorProto_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 4; void UnsafeArenaSwap(DescriptorProto* other); @@ -1197,32 +1125,33 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* // implements Message ---------------------------------------------- - inline DescriptorProto* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<DescriptorProto>(NULL); + inline DescriptorProto* New() const final { + return CreateMaybeMessage<DescriptorProto>(NULL); } - DescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<DescriptorProto>(arena); + DescriptorProto* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<DescriptorProto>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const DescriptorProto& from); void MergeFrom(const DescriptorProto& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(DescriptorProto* other); protected: explicit DescriptorProto(::google::protobuf::Arena* arena); @@ -1238,7 +1167,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -1381,6 +1310,9 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 7; + private: + const ::google::protobuf::MessageOptions& _internal_options() const; + public: const ::google::protobuf::MessageOptions& options() const; ::google::protobuf::MessageOptions* release_options(); ::google::protobuf::MessageOptions* mutable_options(); @@ -1401,7 +1333,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto > field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto > nested_type_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto > enum_type_; @@ -1413,7 +1345,6 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::MessageOptions* options_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProtoImpl(); }; // ------------------------------------------------------------------- @@ -1450,10 +1381,10 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -1464,7 +1395,7 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess return reinterpret_cast<const ExtensionRangeOptions*>( &_ExtensionRangeOptions_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 5; void UnsafeArenaSwap(ExtensionRangeOptions* other); @@ -1475,32 +1406,33 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess // implements Message ---------------------------------------------- - inline ExtensionRangeOptions* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<ExtensionRangeOptions>(NULL); + inline ExtensionRangeOptions* New() const final { + return CreateMaybeMessage<ExtensionRangeOptions>(NULL); } - ExtensionRangeOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<ExtensionRangeOptions>(arena); + ExtensionRangeOptions* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<ExtensionRangeOptions>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const ExtensionRangeOptions& from); void MergeFrom(const ExtensionRangeOptions& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(ExtensionRangeOptions* other); protected: explicit ExtensionRangeOptions(::google::protobuf::Arena* arena); @@ -1516,7 +1448,7 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -1545,10 +1477,9 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptionsImpl(); }; // ------------------------------------------------------------------- @@ -1585,10 +1516,10 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -1599,7 +1530,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa return reinterpret_cast<const FieldDescriptorProto*>( &_FieldDescriptorProto_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 6; void UnsafeArenaSwap(FieldDescriptorProto* other); @@ -1610,32 +1541,33 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa // implements Message ---------------------------------------------- - inline FieldDescriptorProto* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<FieldDescriptorProto>(NULL); + inline FieldDescriptorProto* New() const final { + return CreateMaybeMessage<FieldDescriptorProto>(NULL); } - FieldDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<FieldDescriptorProto>(arena); + FieldDescriptorProto* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<FieldDescriptorProto>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const FieldDescriptorProto& from); void MergeFrom(const FieldDescriptorProto& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(FieldDescriptorProto* other); protected: explicit FieldDescriptorProto(::google::protobuf::Arena* arena); @@ -1651,7 +1583,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -1867,6 +1799,9 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 8; + private: + const ::google::protobuf::FieldOptions& _internal_options() const; + public: const ::google::protobuf::FieldOptions& options() const; ::google::protobuf::FieldOptions* release_options(); ::google::protobuf::FieldOptions* mutable_options(); @@ -1931,7 +1866,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::internal::ArenaStringPtr extendee_; ::google::protobuf::internal::ArenaStringPtr type_name_; @@ -1943,7 +1878,6 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa int label_; int type_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProtoImpl(); }; // ------------------------------------------------------------------- @@ -1980,10 +1914,10 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -1994,7 +1928,7 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa return reinterpret_cast<const OneofDescriptorProto*>( &_OneofDescriptorProto_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 7; void UnsafeArenaSwap(OneofDescriptorProto* other); @@ -2005,32 +1939,33 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa // implements Message ---------------------------------------------- - inline OneofDescriptorProto* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<OneofDescriptorProto>(NULL); + inline OneofDescriptorProto* New() const final { + return CreateMaybeMessage<OneofDescriptorProto>(NULL); } - OneofDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<OneofDescriptorProto>(arena); + OneofDescriptorProto* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<OneofDescriptorProto>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const OneofDescriptorProto& from); void MergeFrom(const OneofDescriptorProto& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(OneofDescriptorProto* other); protected: explicit OneofDescriptorProto(::google::protobuf::Arena* arena); @@ -2046,7 +1981,7 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -2080,6 +2015,9 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 2; + private: + const ::google::protobuf::OneofOptions& _internal_options() const; + public: const ::google::protobuf::OneofOptions& options() const; ::google::protobuf::OneofOptions* release_options(); ::google::protobuf::OneofOptions* mutable_options(); @@ -2100,11 +2038,10 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::OneofOptions* options_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProtoImpl(); }; // ------------------------------------------------------------------- @@ -2141,10 +2078,10 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -2155,7 +2092,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google return reinterpret_cast<const EnumDescriptorProto_EnumReservedRange*>( &_EnumDescriptorProto_EnumReservedRange_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 8; void UnsafeArenaSwap(EnumDescriptorProto_EnumReservedRange* other); @@ -2166,32 +2103,33 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google // implements Message ---------------------------------------------- - inline EnumDescriptorProto_EnumReservedRange* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<EnumDescriptorProto_EnumReservedRange>(NULL); + inline EnumDescriptorProto_EnumReservedRange* New() const final { + return CreateMaybeMessage<EnumDescriptorProto_EnumReservedRange>(NULL); } - EnumDescriptorProto_EnumReservedRange* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<EnumDescriptorProto_EnumReservedRange>(arena); + EnumDescriptorProto_EnumReservedRange* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<EnumDescriptorProto_EnumReservedRange>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const EnumDescriptorProto_EnumReservedRange& from); void MergeFrom(const EnumDescriptorProto_EnumReservedRange& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(EnumDescriptorProto_EnumReservedRange* other); protected: explicit EnumDescriptorProto_EnumReservedRange(::google::protobuf::Arena* arena); @@ -2207,7 +2145,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -2239,11 +2177,10 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::int32 start_; ::google::protobuf::int32 end_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl(); }; // ------------------------------------------------------------------- @@ -2280,10 +2217,10 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -2294,7 +2231,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag return reinterpret_cast<const EnumDescriptorProto*>( &_EnumDescriptorProto_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 9; void UnsafeArenaSwap(EnumDescriptorProto* other); @@ -2305,32 +2242,33 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag // implements Message ---------------------------------------------- - inline EnumDescriptorProto* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<EnumDescriptorProto>(NULL); + inline EnumDescriptorProto* New() const final { + return CreateMaybeMessage<EnumDescriptorProto>(NULL); } - EnumDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<EnumDescriptorProto>(arena); + EnumDescriptorProto* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<EnumDescriptorProto>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const EnumDescriptorProto& from); void MergeFrom(const EnumDescriptorProto& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(EnumDescriptorProto* other); protected: explicit EnumDescriptorProto(::google::protobuf::Arena* arena); @@ -2346,7 +2284,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -2428,6 +2366,9 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 3; + private: + const ::google::protobuf::EnumOptions& _internal_options() const; + public: const ::google::protobuf::EnumOptions& options() const; ::google::protobuf::EnumOptions* release_options(); ::google::protobuf::EnumOptions* mutable_options(); @@ -2448,14 +2389,13 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto > value_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto_EnumReservedRange > reserved_range_; ::google::protobuf::RepeatedPtrField< ::std::string> reserved_name_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::EnumOptions* options_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProtoImpl(); }; // ------------------------------------------------------------------- @@ -2492,10 +2432,10 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -2506,7 +2446,7 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M return reinterpret_cast<const EnumValueDescriptorProto*>( &_EnumValueDescriptorProto_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 10; void UnsafeArenaSwap(EnumValueDescriptorProto* other); @@ -2517,32 +2457,33 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M // implements Message ---------------------------------------------- - inline EnumValueDescriptorProto* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<EnumValueDescriptorProto>(NULL); + inline EnumValueDescriptorProto* New() const final { + return CreateMaybeMessage<EnumValueDescriptorProto>(NULL); } - EnumValueDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<EnumValueDescriptorProto>(arena); + EnumValueDescriptorProto* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<EnumValueDescriptorProto>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const EnumValueDescriptorProto& from); void MergeFrom(const EnumValueDescriptorProto& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(EnumValueDescriptorProto* other); protected: explicit EnumValueDescriptorProto(::google::protobuf::Arena* arena); @@ -2558,7 +2499,7 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -2592,6 +2533,9 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 3; + private: + const ::google::protobuf::EnumValueOptions& _internal_options() const; + public: const ::google::protobuf::EnumValueOptions& options() const; ::google::protobuf::EnumValueOptions* release_options(); ::google::protobuf::EnumValueOptions* mutable_options(); @@ -2621,12 +2565,11 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::EnumValueOptions* options_; ::google::protobuf::int32 number_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProtoImpl(); }; // ------------------------------------------------------------------- @@ -2663,10 +2606,10 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -2677,7 +2620,7 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes return reinterpret_cast<const ServiceDescriptorProto*>( &_ServiceDescriptorProto_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 11; void UnsafeArenaSwap(ServiceDescriptorProto* other); @@ -2688,32 +2631,33 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes // implements Message ---------------------------------------------- - inline ServiceDescriptorProto* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<ServiceDescriptorProto>(NULL); + inline ServiceDescriptorProto* New() const final { + return CreateMaybeMessage<ServiceDescriptorProto>(NULL); } - ServiceDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<ServiceDescriptorProto>(arena); + ServiceDescriptorProto* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<ServiceDescriptorProto>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const ServiceDescriptorProto& from); void MergeFrom(const ServiceDescriptorProto& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(ServiceDescriptorProto* other); protected: explicit ServiceDescriptorProto(::google::protobuf::Arena* arena); @@ -2729,7 +2673,7 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -2775,6 +2719,9 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 3; + private: + const ::google::protobuf::ServiceOptions& _internal_options() const; + public: const ::google::protobuf::ServiceOptions& options() const; ::google::protobuf::ServiceOptions* release_options(); ::google::protobuf::ServiceOptions* mutable_options(); @@ -2795,12 +2742,11 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto > method_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::ServiceOptions* options_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProtoImpl(); }; // ------------------------------------------------------------------- @@ -2837,10 +2783,10 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -2851,7 +2797,7 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess return reinterpret_cast<const MethodDescriptorProto*>( &_MethodDescriptorProto_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 12; void UnsafeArenaSwap(MethodDescriptorProto* other); @@ -2862,32 +2808,33 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess // implements Message ---------------------------------------------- - inline MethodDescriptorProto* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<MethodDescriptorProto>(NULL); + inline MethodDescriptorProto* New() const final { + return CreateMaybeMessage<MethodDescriptorProto>(NULL); } - MethodDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<MethodDescriptorProto>(arena); + MethodDescriptorProto* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<MethodDescriptorProto>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const MethodDescriptorProto& from); void MergeFrom(const MethodDescriptorProto& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(MethodDescriptorProto* other); protected: explicit MethodDescriptorProto(::google::protobuf::Arena* arena); @@ -2903,7 +2850,7 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -2985,6 +2932,9 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 4; + private: + const ::google::protobuf::MethodOptions& _internal_options() const; + public: const ::google::protobuf::MethodOptions& options() const; ::google::protobuf::MethodOptions* release_options(); ::google::protobuf::MethodOptions* mutable_options(); @@ -3027,7 +2977,7 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::internal::ArenaStringPtr input_type_; ::google::protobuf::internal::ArenaStringPtr output_type_; @@ -3035,7 +2985,6 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess bool client_streaming_; bool server_streaming_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProtoImpl(); }; // ------------------------------------------------------------------- @@ -3072,10 +3021,10 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -3086,7 +3035,7 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p return reinterpret_cast<const FileOptions*>( &_FileOptions_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 13; void UnsafeArenaSwap(FileOptions* other); @@ -3097,32 +3046,33 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p // implements Message ---------------------------------------------- - inline FileOptions* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<FileOptions>(NULL); + inline FileOptions* New() const final { + return CreateMaybeMessage<FileOptions>(NULL); } - FileOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<FileOptions>(arena); + FileOptions* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<FileOptions>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const FileOptions& from); void MergeFrom(const FileOptions& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(FileOptions* other); protected: explicit FileOptions(::google::protobuf::Arena* arena); @@ -3138,7 +3088,7 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -3376,12 +3326,53 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p void unsafe_arena_set_allocated_php_namespace( ::std::string* php_namespace); - // optional bool cc_enable_arenas = 31 [default = false]; - bool has_cc_enable_arenas() const; - void clear_cc_enable_arenas(); - static const int kCcEnableArenasFieldNumber = 31; - bool cc_enable_arenas() const; - void set_cc_enable_arenas(bool value); + // optional string php_metadata_namespace = 44; + bool has_php_metadata_namespace() const; + void clear_php_metadata_namespace(); + static const int kPhpMetadataNamespaceFieldNumber = 44; + const ::std::string& php_metadata_namespace() const; + void set_php_metadata_namespace(const ::std::string& value); + #if LANG_CXX11 + void set_php_metadata_namespace(::std::string&& value); + #endif + void set_php_metadata_namespace(const char* value); + void set_php_metadata_namespace(const char* value, size_t size); + ::std::string* mutable_php_metadata_namespace(); + ::std::string* release_php_metadata_namespace(); + void set_allocated_php_metadata_namespace(::std::string* php_metadata_namespace); + PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + " string fields are deprecated and will be removed in a" + " future release.") + ::std::string* unsafe_arena_release_php_metadata_namespace(); + PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + " string fields are deprecated and will be removed in a" + " future release.") + void unsafe_arena_set_allocated_php_metadata_namespace( + ::std::string* php_metadata_namespace); + + // optional string ruby_package = 45; + bool has_ruby_package() const; + void clear_ruby_package(); + static const int kRubyPackageFieldNumber = 45; + const ::std::string& ruby_package() const; + void set_ruby_package(const ::std::string& value); + #if LANG_CXX11 + void set_ruby_package(::std::string&& value); + #endif + void set_ruby_package(const char* value); + void set_ruby_package(const char* value, size_t size); + ::std::string* mutable_ruby_package(); + ::std::string* release_ruby_package(); + void set_allocated_ruby_package(::std::string* ruby_package); + PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + " string fields are deprecated and will be removed in a" + " future release.") + ::std::string* unsafe_arena_release_ruby_package(); + PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" + " string fields are deprecated and will be removed in a" + " future release.") + void unsafe_arena_set_allocated_ruby_package( + ::std::string* ruby_package); // optional bool java_multiple_files = 10 [default = false]; bool has_java_multiple_files() const; @@ -3439,6 +3430,13 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p bool deprecated() const; void set_deprecated(bool value); + // optional bool cc_enable_arenas = 31 [default = false]; + bool has_cc_enable_arenas() const; + void clear_cc_enable_arenas(); + static const int kCcEnableArenasFieldNumber = 31; + bool cc_enable_arenas() const; + void set_cc_enable_arenas(bool value); + // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED]; bool has_optimize_for() const; void clear_optimize_for(); @@ -3485,6 +3483,10 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p void clear_has_php_class_prefix(); void set_has_php_namespace(); void clear_has_php_namespace(); + void set_has_php_metadata_namespace(); + void clear_has_php_metadata_namespace(); + void set_has_ruby_package(); + void clear_has_ruby_package(); ::google::protobuf::internal::ExtensionSet _extensions_; @@ -3493,7 +3495,7 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; ::google::protobuf::internal::ArenaStringPtr java_package_; ::google::protobuf::internal::ArenaStringPtr java_outer_classname_; @@ -3503,7 +3505,8 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p ::google::protobuf::internal::ArenaStringPtr swift_prefix_; ::google::protobuf::internal::ArenaStringPtr php_class_prefix_; ::google::protobuf::internal::ArenaStringPtr php_namespace_; - bool cc_enable_arenas_; + ::google::protobuf::internal::ArenaStringPtr php_metadata_namespace_; + ::google::protobuf::internal::ArenaStringPtr ruby_package_; bool java_multiple_files_; bool java_generate_equals_and_hash_; bool java_string_check_utf8_; @@ -3512,9 +3515,9 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p bool py_generic_services_; bool php_generic_services_; bool deprecated_; + bool cc_enable_arenas_; int optimize_for_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptionsImpl(); }; // ------------------------------------------------------------------- @@ -3551,10 +3554,10 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -3565,7 +3568,7 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* return reinterpret_cast<const MessageOptions*>( &_MessageOptions_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 14; void UnsafeArenaSwap(MessageOptions* other); @@ -3576,32 +3579,33 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* // implements Message ---------------------------------------------- - inline MessageOptions* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<MessageOptions>(NULL); + inline MessageOptions* New() const final { + return CreateMaybeMessage<MessageOptions>(NULL); } - MessageOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<MessageOptions>(arena); + MessageOptions* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<MessageOptions>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const MessageOptions& from); void MergeFrom(const MessageOptions& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(MessageOptions* other); protected: explicit MessageOptions(::google::protobuf::Arena* arena); @@ -3617,7 +3621,7 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -3682,14 +3686,13 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; bool message_set_wire_format_; bool no_standard_descriptor_accessor_; bool deprecated_; bool map_entry_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptionsImpl(); }; // ------------------------------------------------------------------- @@ -3726,10 +3729,10 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@ return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -3740,7 +3743,7 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@ return reinterpret_cast<const FieldOptions*>( &_FieldOptions_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 15; void UnsafeArenaSwap(FieldOptions* other); @@ -3751,32 +3754,33 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@ // implements Message ---------------------------------------------- - inline FieldOptions* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<FieldOptions>(NULL); + inline FieldOptions* New() const final { + return CreateMaybeMessage<FieldOptions>(NULL); } - FieldOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<FieldOptions>(arena); + FieldOptions* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<FieldOptions>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const FieldOptions& from); void MergeFrom(const FieldOptions& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(FieldOptions* other); protected: explicit FieldOptions(::google::protobuf::Arena* arena); @@ -3792,7 +3796,7 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@ } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -3931,7 +3935,7 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@ typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; int ctype_; bool packed_; @@ -3940,7 +3944,6 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@ bool weak_; int jstype_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptionsImpl(); }; // ------------------------------------------------------------------- @@ -3977,10 +3980,10 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@ return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -3991,7 +3994,7 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@ return reinterpret_cast<const OneofOptions*>( &_OneofOptions_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 16; void UnsafeArenaSwap(OneofOptions* other); @@ -4002,32 +4005,33 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@ // implements Message ---------------------------------------------- - inline OneofOptions* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<OneofOptions>(NULL); + inline OneofOptions* New() const final { + return CreateMaybeMessage<OneofOptions>(NULL); } - OneofOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<OneofOptions>(arena); + OneofOptions* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<OneofOptions>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const OneofOptions& from); void MergeFrom(const OneofOptions& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(OneofOptions* other); protected: explicit OneofOptions(::google::protobuf::Arena* arena); @@ -4043,7 +4047,7 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@ } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -4072,10 +4076,9 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@ typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptionsImpl(); }; // ------------------------------------------------------------------- @@ -4112,10 +4115,10 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -4126,7 +4129,7 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p return reinterpret_cast<const EnumOptions*>( &_EnumOptions_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 17; void UnsafeArenaSwap(EnumOptions* other); @@ -4137,32 +4140,33 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p // implements Message ---------------------------------------------- - inline EnumOptions* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<EnumOptions>(NULL); + inline EnumOptions* New() const final { + return CreateMaybeMessage<EnumOptions>(NULL); } - EnumOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<EnumOptions>(arena); + EnumOptions* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<EnumOptions>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const EnumOptions& from); void MergeFrom(const EnumOptions& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(EnumOptions* other); protected: explicit EnumOptions(::google::protobuf::Arena* arena); @@ -4178,7 +4182,7 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -4225,12 +4229,11 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; bool allow_alias_; bool deprecated_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptionsImpl(); }; // ------------------------------------------------------------------- @@ -4267,10 +4270,10 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message / return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -4281,7 +4284,7 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message / return reinterpret_cast<const EnumValueOptions*>( &_EnumValueOptions_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 18; void UnsafeArenaSwap(EnumValueOptions* other); @@ -4292,32 +4295,33 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message / // implements Message ---------------------------------------------- - inline EnumValueOptions* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<EnumValueOptions>(NULL); + inline EnumValueOptions* New() const final { + return CreateMaybeMessage<EnumValueOptions>(NULL); } - EnumValueOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<EnumValueOptions>(arena); + EnumValueOptions* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<EnumValueOptions>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const EnumValueOptions& from); void MergeFrom(const EnumValueOptions& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(EnumValueOptions* other); protected: explicit EnumValueOptions(::google::protobuf::Arena* arena); @@ -4333,7 +4337,7 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message / } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -4371,11 +4375,10 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message / typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; bool deprecated_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptionsImpl(); }; // ------------------------------------------------------------------- @@ -4412,10 +4415,10 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -4426,7 +4429,7 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* return reinterpret_cast<const ServiceOptions*>( &_ServiceOptions_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 19; void UnsafeArenaSwap(ServiceOptions* other); @@ -4437,32 +4440,33 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* // implements Message ---------------------------------------------- - inline ServiceOptions* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<ServiceOptions>(NULL); + inline ServiceOptions* New() const final { + return CreateMaybeMessage<ServiceOptions>(NULL); } - ServiceOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<ServiceOptions>(arena); + ServiceOptions* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<ServiceOptions>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const ServiceOptions& from); void MergeFrom(const ServiceOptions& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(ServiceOptions* other); protected: explicit ServiceOptions(::google::protobuf::Arena* arena); @@ -4478,7 +4482,7 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -4516,11 +4520,10 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; bool deprecated_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptionsImpl(); }; // ------------------------------------------------------------------- @@ -4557,10 +4560,10 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @ return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -4571,7 +4574,7 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @ return reinterpret_cast<const MethodOptions*>( &_MethodOptions_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 20; void UnsafeArenaSwap(MethodOptions* other); @@ -4582,32 +4585,33 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @ // implements Message ---------------------------------------------- - inline MethodOptions* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<MethodOptions>(NULL); + inline MethodOptions* New() const final { + return CreateMaybeMessage<MethodOptions>(NULL); } - MethodOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<MethodOptions>(arena); + MethodOptions* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<MethodOptions>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const MethodOptions& from); void MergeFrom(const MethodOptions& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(MethodOptions* other); protected: explicit MethodOptions(::google::protobuf::Arena* arena); @@ -4623,7 +4627,7 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @ } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -4698,12 +4702,11 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @ typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; bool deprecated_; int idempotency_level_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptionsImpl(); }; // ------------------------------------------------------------------- @@ -4740,10 +4743,10 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -4754,7 +4757,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu return reinterpret_cast<const UninterpretedOption_NamePart*>( &_UninterpretedOption_NamePart_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 21; void UnsafeArenaSwap(UninterpretedOption_NamePart* other); @@ -4765,32 +4768,33 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu // implements Message ---------------------------------------------- - inline UninterpretedOption_NamePart* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<UninterpretedOption_NamePart>(NULL); + inline UninterpretedOption_NamePart* New() const final { + return CreateMaybeMessage<UninterpretedOption_NamePart>(NULL); } - UninterpretedOption_NamePart* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<UninterpretedOption_NamePart>(arena); + UninterpretedOption_NamePart* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<UninterpretedOption_NamePart>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const UninterpretedOption_NamePart& from); void MergeFrom(const UninterpretedOption_NamePart& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(UninterpretedOption_NamePart* other); protected: explicit UninterpretedOption_NamePart(::google::protobuf::Arena* arena); @@ -4806,7 +4810,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -4858,11 +4862,10 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::internal::ArenaStringPtr name_part_; bool is_extension_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePartImpl(); }; // ------------------------------------------------------------------- @@ -4899,10 +4902,10 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -4913,7 +4916,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag return reinterpret_cast<const UninterpretedOption*>( &_UninterpretedOption_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 22; void UnsafeArenaSwap(UninterpretedOption* other); @@ -4924,32 +4927,33 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag // implements Message ---------------------------------------------- - inline UninterpretedOption* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<UninterpretedOption>(NULL); + inline UninterpretedOption* New() const final { + return CreateMaybeMessage<UninterpretedOption>(NULL); } - UninterpretedOption* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<UninterpretedOption>(arena); + UninterpretedOption* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<UninterpretedOption>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const UninterpretedOption& from); void MergeFrom(const UninterpretedOption& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(UninterpretedOption* other); protected: explicit UninterpretedOption(::google::protobuf::Arena* arena); @@ -4965,7 +4969,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -5098,7 +5102,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart > name_; ::google::protobuf::internal::ArenaStringPtr identifier_value_; ::google::protobuf::internal::ArenaStringPtr string_value_; @@ -5107,7 +5111,6 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag ::google::protobuf::int64 negative_int_value_; double double_value_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOptionImpl(); }; // ------------------------------------------------------------------- @@ -5144,10 +5147,10 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -5158,7 +5161,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me return reinterpret_cast<const SourceCodeInfo_Location*>( &_SourceCodeInfo_Location_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 23; void UnsafeArenaSwap(SourceCodeInfo_Location* other); @@ -5169,32 +5172,33 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me // implements Message ---------------------------------------------- - inline SourceCodeInfo_Location* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<SourceCodeInfo_Location>(NULL); + inline SourceCodeInfo_Location* New() const final { + return CreateMaybeMessage<SourceCodeInfo_Location>(NULL); } - SourceCodeInfo_Location* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<SourceCodeInfo_Location>(arena); + SourceCodeInfo_Location* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<SourceCodeInfo_Location>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const SourceCodeInfo_Location& from); void MergeFrom(const SourceCodeInfo_Location& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(SourceCodeInfo_Location* other); protected: explicit SourceCodeInfo_Location(::google::protobuf::Arena* arena); @@ -5210,7 +5214,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -5322,7 +5326,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedField< ::google::protobuf::int32 > path_; mutable int _path_cached_byte_size_; ::google::protobuf::RepeatedField< ::google::protobuf::int32 > span_; @@ -5331,7 +5335,6 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me ::google::protobuf::internal::ArenaStringPtr leading_comments_; ::google::protobuf::internal::ArenaStringPtr trailing_comments_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_LocationImpl(); }; // ------------------------------------------------------------------- @@ -5368,10 +5371,10 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -5382,7 +5385,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* return reinterpret_cast<const SourceCodeInfo*>( &_SourceCodeInfo_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 24; void UnsafeArenaSwap(SourceCodeInfo* other); @@ -5393,32 +5396,33 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* // implements Message ---------------------------------------------- - inline SourceCodeInfo* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<SourceCodeInfo>(NULL); + inline SourceCodeInfo* New() const final { + return CreateMaybeMessage<SourceCodeInfo>(NULL); } - SourceCodeInfo* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<SourceCodeInfo>(arena); + SourceCodeInfo* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<SourceCodeInfo>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const SourceCodeInfo& from); void MergeFrom(const SourceCodeInfo& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(SourceCodeInfo* other); protected: explicit SourceCodeInfo(::google::protobuf::Arena* arena); @@ -5434,7 +5438,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -5462,10 +5466,9 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceCodeInfo_Location > location_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfoImpl(); }; // ------------------------------------------------------------------- @@ -5502,10 +5505,10 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -5516,7 +5519,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu return reinterpret_cast<const GeneratedCodeInfo_Annotation*>( &_GeneratedCodeInfo_Annotation_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 25; void UnsafeArenaSwap(GeneratedCodeInfo_Annotation* other); @@ -5527,32 +5530,33 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu // implements Message ---------------------------------------------- - inline GeneratedCodeInfo_Annotation* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<GeneratedCodeInfo_Annotation>(NULL); + inline GeneratedCodeInfo_Annotation* New() const final { + return CreateMaybeMessage<GeneratedCodeInfo_Annotation>(NULL); } - GeneratedCodeInfo_Annotation* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<GeneratedCodeInfo_Annotation>(arena); + GeneratedCodeInfo_Annotation* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<GeneratedCodeInfo_Annotation>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const GeneratedCodeInfo_Annotation& from); void MergeFrom(const GeneratedCodeInfo_Annotation& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(GeneratedCodeInfo_Annotation* other); protected: explicit GeneratedCodeInfo_Annotation(::google::protobuf::Arena* arena); @@ -5568,7 +5572,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -5638,14 +5642,13 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedField< ::google::protobuf::int32 > path_; mutable int _path_cached_byte_size_; ::google::protobuf::internal::ArenaStringPtr source_file_; ::google::protobuf::int32 begin_; ::google::protobuf::int32 end_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_AnnotationImpl(); }; // ------------------------------------------------------------------- @@ -5682,10 +5685,10 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -5696,7 +5699,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message return reinterpret_cast<const GeneratedCodeInfo*>( &_GeneratedCodeInfo_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 26; void UnsafeArenaSwap(GeneratedCodeInfo* other); @@ -5707,32 +5710,33 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message // implements Message ---------------------------------------------- - inline GeneratedCodeInfo* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<GeneratedCodeInfo>(NULL); + inline GeneratedCodeInfo* New() const final { + return CreateMaybeMessage<GeneratedCodeInfo>(NULL); } - GeneratedCodeInfo* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<GeneratedCodeInfo>(arena); + GeneratedCodeInfo* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<GeneratedCodeInfo>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const GeneratedCodeInfo& from); void MergeFrom(const GeneratedCodeInfo& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(GeneratedCodeInfo* other); protected: explicit GeneratedCodeInfo(::google::protobuf::Arena* arena); @@ -5748,7 +5752,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -5776,10 +5780,9 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::GeneratedCodeInfo_Annotation > annotation_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfoImpl(); }; // =================================================================== @@ -5878,8 +5881,11 @@ inline ::std::string* FileDescriptorProto::mutable_name() { } inline ::std::string* FileDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.name) + if (!has_name()) { + return NULL; + } clear_has_name(); - return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileDescriptorProto::set_allocated_name(::std::string* name) { if (name != NULL) { @@ -5963,8 +5969,11 @@ inline ::std::string* FileDescriptorProto::mutable_package() { } inline ::std::string* FileDescriptorProto::release_package() { // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.package) + if (!has_package()) { + return NULL; + } clear_has_package(); - return package_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return package_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileDescriptorProto::set_allocated_package(::std::string* package) { if (package != NULL) { @@ -6259,6 +6268,9 @@ inline void FileDescriptorProto::clear_options() { if (options_ != NULL) options_->Clear(); clear_has_options(); } +inline const ::google::protobuf::FileOptions& FileDescriptorProto::_internal_options() const { + return *options_; +} inline const ::google::protobuf::FileOptions& FileDescriptorProto::options() const { const ::google::protobuf::FileOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.options) @@ -6270,7 +6282,7 @@ inline ::google::protobuf::FileOptions* FileDescriptorProto::release_options() { clear_has_options(); ::google::protobuf::FileOptions* temp = options_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } options_ = NULL; return temp; @@ -6285,8 +6297,8 @@ inline ::google::protobuf::FileOptions* FileDescriptorProto::unsafe_arena_releas inline ::google::protobuf::FileOptions* FileDescriptorProto::mutable_options() { set_has_options(); if (options_ == NULL) { - options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::FileOptions >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::FileOptions>(GetArenaNoVirtual()); + options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.options) return options_; @@ -6325,6 +6337,9 @@ inline void FileDescriptorProto::clear_source_code_info() { if (source_code_info_ != NULL) source_code_info_->Clear(); clear_has_source_code_info(); } +inline const ::google::protobuf::SourceCodeInfo& FileDescriptorProto::_internal_source_code_info() const { + return *source_code_info_; +} inline const ::google::protobuf::SourceCodeInfo& FileDescriptorProto::source_code_info() const { const ::google::protobuf::SourceCodeInfo* p = source_code_info_; // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.source_code_info) @@ -6336,7 +6351,7 @@ inline ::google::protobuf::SourceCodeInfo* FileDescriptorProto::release_source_c clear_has_source_code_info(); ::google::protobuf::SourceCodeInfo* temp = source_code_info_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } source_code_info_ = NULL; return temp; @@ -6351,8 +6366,8 @@ inline ::google::protobuf::SourceCodeInfo* FileDescriptorProto::unsafe_arena_rel inline ::google::protobuf::SourceCodeInfo* FileDescriptorProto::mutable_source_code_info() { set_has_source_code_info(); if (source_code_info_ == NULL) { - source_code_info_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::SourceCodeInfo >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::SourceCodeInfo>(GetArenaNoVirtual()); + source_code_info_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.source_code_info) return source_code_info_; @@ -6429,8 +6444,11 @@ inline ::std::string* FileDescriptorProto::mutable_syntax() { } inline ::std::string* FileDescriptorProto::release_syntax() { // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.syntax) + if (!has_syntax()) { + return NULL; + } clear_has_syntax(); - return syntax_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return syntax_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileDescriptorProto::set_allocated_syntax(::std::string* syntax) { if (syntax != NULL) { @@ -6528,6 +6546,9 @@ inline void DescriptorProto_ExtensionRange::clear_options() { if (options_ != NULL) options_->Clear(); clear_has_options(); } +inline const ::google::protobuf::ExtensionRangeOptions& DescriptorProto_ExtensionRange::_internal_options() const { + return *options_; +} inline const ::google::protobuf::ExtensionRangeOptions& DescriptorProto_ExtensionRange::options() const { const ::google::protobuf::ExtensionRangeOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ExtensionRange.options) @@ -6539,7 +6560,7 @@ inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange clear_has_options(); ::google::protobuf::ExtensionRangeOptions* temp = options_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } options_ = NULL; return temp; @@ -6554,8 +6575,8 @@ inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange::mutable_options() { set_has_options(); if (options_ == NULL) { - options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ExtensionRangeOptions >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::ExtensionRangeOptions>(GetArenaNoVirtual()); + options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.ExtensionRange.options) return options_; @@ -6688,8 +6709,11 @@ inline ::std::string* DescriptorProto::mutable_name() { } inline ::std::string* DescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.DescriptorProto.name) + if (!has_name()) { + return NULL; + } clear_has_name(); - return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void DescriptorProto::set_allocated_name(::std::string* name) { if (name != NULL) { @@ -6915,6 +6939,9 @@ inline void DescriptorProto::clear_options() { if (options_ != NULL) options_->Clear(); clear_has_options(); } +inline const ::google::protobuf::MessageOptions& DescriptorProto::_internal_options() const { + return *options_; +} inline const ::google::protobuf::MessageOptions& DescriptorProto::options() const { const ::google::protobuf::MessageOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.options) @@ -6926,7 +6953,7 @@ inline ::google::protobuf::MessageOptions* DescriptorProto::release_options() { clear_has_options(); ::google::protobuf::MessageOptions* temp = options_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } options_ = NULL; return temp; @@ -6941,8 +6968,8 @@ inline ::google::protobuf::MessageOptions* DescriptorProto::unsafe_arena_release inline ::google::protobuf::MessageOptions* DescriptorProto::mutable_options() { set_has_options(); if (options_ == NULL) { - options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::MessageOptions >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::MessageOptions>(GetArenaNoVirtual()); + options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.options) return options_; @@ -7156,8 +7183,11 @@ inline ::std::string* FieldDescriptorProto::mutable_name() { } inline ::std::string* FieldDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.name) + if (!has_name()) { + return NULL; + } clear_has_name(); - return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FieldDescriptorProto::set_allocated_name(::std::string* name) { if (name != NULL) { @@ -7315,8 +7345,11 @@ inline ::std::string* FieldDescriptorProto::mutable_type_name() { } inline ::std::string* FieldDescriptorProto::release_type_name() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.type_name) + if (!has_type_name()) { + return NULL; + } clear_has_type_name(); - return type_name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return type_name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FieldDescriptorProto::set_allocated_type_name(::std::string* type_name) { if (type_name != NULL) { @@ -7400,8 +7433,11 @@ inline ::std::string* FieldDescriptorProto::mutable_extendee() { } inline ::std::string* FieldDescriptorProto::release_extendee() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.extendee) + if (!has_extendee()) { + return NULL; + } clear_has_extendee(); - return extendee_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return extendee_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FieldDescriptorProto::set_allocated_extendee(::std::string* extendee) { if (extendee != NULL) { @@ -7485,8 +7521,11 @@ inline ::std::string* FieldDescriptorProto::mutable_default_value() { } inline ::std::string* FieldDescriptorProto::release_default_value() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.default_value) + if (!has_default_value()) { + return NULL; + } clear_has_default_value(); - return default_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return default_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FieldDescriptorProto::set_allocated_default_value(::std::string* default_value) { if (default_value != NULL) { @@ -7594,8 +7633,11 @@ inline ::std::string* FieldDescriptorProto::mutable_json_name() { } inline ::std::string* FieldDescriptorProto::release_json_name() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.json_name) + if (!has_json_name()) { + return NULL; + } clear_has_json_name(); - return json_name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return json_name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FieldDescriptorProto::set_allocated_json_name(::std::string* json_name) { if (json_name != NULL) { @@ -7641,6 +7683,9 @@ inline void FieldDescriptorProto::clear_options() { if (options_ != NULL) options_->Clear(); clear_has_options(); } +inline const ::google::protobuf::FieldOptions& FieldDescriptorProto::_internal_options() const { + return *options_; +} inline const ::google::protobuf::FieldOptions& FieldDescriptorProto::options() const { const ::google::protobuf::FieldOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.options) @@ -7652,7 +7697,7 @@ inline ::google::protobuf::FieldOptions* FieldDescriptorProto::release_options() clear_has_options(); ::google::protobuf::FieldOptions* temp = options_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } options_ = NULL; return temp; @@ -7667,8 +7712,8 @@ inline ::google::protobuf::FieldOptions* FieldDescriptorProto::unsafe_arena_rele inline ::google::protobuf::FieldOptions* FieldDescriptorProto::mutable_options() { set_has_options(); if (options_ == NULL) { - options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::FieldOptions >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::FieldOptions>(GetArenaNoVirtual()); + options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.options) return options_; @@ -7749,8 +7794,11 @@ inline ::std::string* OneofDescriptorProto::mutable_name() { } inline ::std::string* OneofDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.OneofDescriptorProto.name) + if (!has_name()) { + return NULL; + } clear_has_name(); - return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void OneofDescriptorProto::set_allocated_name(::std::string* name) { if (name != NULL) { @@ -7796,6 +7844,9 @@ inline void OneofDescriptorProto::clear_options() { if (options_ != NULL) options_->Clear(); clear_has_options(); } +inline const ::google::protobuf::OneofOptions& OneofDescriptorProto::_internal_options() const { + return *options_; +} inline const ::google::protobuf::OneofOptions& OneofDescriptorProto::options() const { const ::google::protobuf::OneofOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.OneofDescriptorProto.options) @@ -7807,7 +7858,7 @@ inline ::google::protobuf::OneofOptions* OneofDescriptorProto::release_options() clear_has_options(); ::google::protobuf::OneofOptions* temp = options_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } options_ = NULL; return temp; @@ -7822,8 +7873,8 @@ inline ::google::protobuf::OneofOptions* OneofDescriptorProto::unsafe_arena_rele inline ::google::protobuf::OneofOptions* OneofDescriptorProto::mutable_options() { set_has_options(); if (options_ == NULL) { - options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::OneofOptions >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::OneofOptions>(GetArenaNoVirtual()); + options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.OneofDescriptorProto.options) return options_; @@ -7956,8 +8007,11 @@ inline ::std::string* EnumDescriptorProto::mutable_name() { } inline ::std::string* EnumDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.EnumDescriptorProto.name) + if (!has_name()) { + return NULL; + } clear_has_name(); - return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void EnumDescriptorProto::set_allocated_name(::std::string* name) { if (name != NULL) { @@ -8033,6 +8087,9 @@ inline void EnumDescriptorProto::clear_options() { if (options_ != NULL) options_->Clear(); clear_has_options(); } +inline const ::google::protobuf::EnumOptions& EnumDescriptorProto::_internal_options() const { + return *options_; +} inline const ::google::protobuf::EnumOptions& EnumDescriptorProto::options() const { const ::google::protobuf::EnumOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.options) @@ -8044,7 +8101,7 @@ inline ::google::protobuf::EnumOptions* EnumDescriptorProto::release_options() { clear_has_options(); ::google::protobuf::EnumOptions* temp = options_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } options_ = NULL; return temp; @@ -8059,8 +8116,8 @@ inline ::google::protobuf::EnumOptions* EnumDescriptorProto::unsafe_arena_releas inline ::google::protobuf::EnumOptions* EnumDescriptorProto::mutable_options() { set_has_options(); if (options_ == NULL) { - options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::EnumOptions >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::EnumOptions>(GetArenaNoVirtual()); + options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.options) return options_; @@ -8240,8 +8297,11 @@ inline ::std::string* EnumValueDescriptorProto::mutable_name() { } inline ::std::string* EnumValueDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.EnumValueDescriptorProto.name) + if (!has_name()) { + return NULL; + } clear_has_name(); - return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void EnumValueDescriptorProto::set_allocated_name(::std::string* name) { if (name != NULL) { @@ -8311,6 +8371,9 @@ inline void EnumValueDescriptorProto::clear_options() { if (options_ != NULL) options_->Clear(); clear_has_options(); } +inline const ::google::protobuf::EnumValueOptions& EnumValueDescriptorProto::_internal_options() const { + return *options_; +} inline const ::google::protobuf::EnumValueOptions& EnumValueDescriptorProto::options() const { const ::google::protobuf::EnumValueOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.options) @@ -8322,7 +8385,7 @@ inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::release_o clear_has_options(); ::google::protobuf::EnumValueOptions* temp = options_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } options_ = NULL; return temp; @@ -8337,8 +8400,8 @@ inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::unsafe_ar inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::mutable_options() { set_has_options(); if (options_ == NULL) { - options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::EnumValueOptions >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::EnumValueOptions>(GetArenaNoVirtual()); + options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.EnumValueDescriptorProto.options) return options_; @@ -8419,8 +8482,11 @@ inline ::std::string* ServiceDescriptorProto::mutable_name() { } inline ::std::string* ServiceDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.ServiceDescriptorProto.name) + if (!has_name()) { + return NULL; + } clear_has_name(); - return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void ServiceDescriptorProto::set_allocated_name(::std::string* name) { if (name != NULL) { @@ -8496,6 +8562,9 @@ inline void ServiceDescriptorProto::clear_options() { if (options_ != NULL) options_->Clear(); clear_has_options(); } +inline const ::google::protobuf::ServiceOptions& ServiceDescriptorProto::_internal_options() const { + return *options_; +} inline const ::google::protobuf::ServiceOptions& ServiceDescriptorProto::options() const { const ::google::protobuf::ServiceOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.options) @@ -8507,7 +8576,7 @@ inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::release_optio clear_has_options(); ::google::protobuf::ServiceOptions* temp = options_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } options_ = NULL; return temp; @@ -8522,8 +8591,8 @@ inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::unsafe_arena_ inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::mutable_options() { set_has_options(); if (options_ == NULL) { - options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ServiceOptions >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::ServiceOptions>(GetArenaNoVirtual()); + options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.ServiceDescriptorProto.options) return options_; @@ -8604,8 +8673,11 @@ inline ::std::string* MethodDescriptorProto::mutable_name() { } inline ::std::string* MethodDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.name) + if (!has_name()) { + return NULL; + } clear_has_name(); - return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void MethodDescriptorProto::set_allocated_name(::std::string* name) { if (name != NULL) { @@ -8689,8 +8761,11 @@ inline ::std::string* MethodDescriptorProto::mutable_input_type() { } inline ::std::string* MethodDescriptorProto::release_input_type() { // @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.input_type) + if (!has_input_type()) { + return NULL; + } clear_has_input_type(); - return input_type_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return input_type_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void MethodDescriptorProto::set_allocated_input_type(::std::string* input_type) { if (input_type != NULL) { @@ -8774,8 +8849,11 @@ inline ::std::string* MethodDescriptorProto::mutable_output_type() { } inline ::std::string* MethodDescriptorProto::release_output_type() { // @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.output_type) + if (!has_output_type()) { + return NULL; + } clear_has_output_type(); - return output_type_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return output_type_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void MethodDescriptorProto::set_allocated_output_type(::std::string* output_type) { if (output_type != NULL) { @@ -8821,6 +8899,9 @@ inline void MethodDescriptorProto::clear_options() { if (options_ != NULL) options_->Clear(); clear_has_options(); } +inline const ::google::protobuf::MethodOptions& MethodDescriptorProto::_internal_options() const { + return *options_; +} inline const ::google::protobuf::MethodOptions& MethodDescriptorProto::options() const { const ::google::protobuf::MethodOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.options) @@ -8832,7 +8913,7 @@ inline ::google::protobuf::MethodOptions* MethodDescriptorProto::release_options clear_has_options(); ::google::protobuf::MethodOptions* temp = options_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } options_ = NULL; return temp; @@ -8847,8 +8928,8 @@ inline ::google::protobuf::MethodOptions* MethodDescriptorProto::unsafe_arena_re inline ::google::protobuf::MethodOptions* MethodDescriptorProto::mutable_options() { set_has_options(); if (options_ == NULL) { - options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::MethodOptions >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::MethodOptions>(GetArenaNoVirtual()); + options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.options) return options_; @@ -8977,8 +9058,11 @@ inline ::std::string* FileOptions::mutable_java_package() { } inline ::std::string* FileOptions::release_java_package() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.java_package) + if (!has_java_package()) { + return NULL; + } clear_has_java_package(); - return java_package_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return java_package_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::set_allocated_java_package(::std::string* java_package) { if (java_package != NULL) { @@ -9062,8 +9146,11 @@ inline ::std::string* FileOptions::mutable_java_outer_classname() { } inline ::std::string* FileOptions::release_java_outer_classname() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.java_outer_classname) + if (!has_java_outer_classname()) { + return NULL; + } clear_has_java_outer_classname(); - return java_outer_classname_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return java_outer_classname_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::set_allocated_java_outer_classname(::std::string* java_outer_classname) { if (java_outer_classname != NULL) { @@ -9097,13 +9184,13 @@ inline void FileOptions::unsafe_arena_set_allocated_java_outer_classname( // optional bool java_multiple_files = 10 [default = false]; inline bool FileOptions::has_java_multiple_files() const { - return (_has_bits_[0] & 0x00000200u) != 0; + return (_has_bits_[0] & 0x00000400u) != 0; } inline void FileOptions::set_has_java_multiple_files() { - _has_bits_[0] |= 0x00000200u; + _has_bits_[0] |= 0x00000400u; } inline void FileOptions::clear_has_java_multiple_files() { - _has_bits_[0] &= ~0x00000200u; + _has_bits_[0] &= ~0x00000400u; } inline void FileOptions::clear_java_multiple_files() { java_multiple_files_ = false; @@ -9121,13 +9208,13 @@ inline void FileOptions::set_java_multiple_files(bool value) { // optional bool java_generate_equals_and_hash = 20 [deprecated = true]; inline bool FileOptions::has_java_generate_equals_and_hash() const { - return (_has_bits_[0] & 0x00000400u) != 0; + return (_has_bits_[0] & 0x00000800u) != 0; } inline void FileOptions::set_has_java_generate_equals_and_hash() { - _has_bits_[0] |= 0x00000400u; + _has_bits_[0] |= 0x00000800u; } inline void FileOptions::clear_has_java_generate_equals_and_hash() { - _has_bits_[0] &= ~0x00000400u; + _has_bits_[0] &= ~0x00000800u; } inline void FileOptions::clear_java_generate_equals_and_hash() { java_generate_equals_and_hash_ = false; @@ -9145,13 +9232,13 @@ inline void FileOptions::set_java_generate_equals_and_hash(bool value) { // optional bool java_string_check_utf8 = 27 [default = false]; inline bool FileOptions::has_java_string_check_utf8() const { - return (_has_bits_[0] & 0x00000800u) != 0; + return (_has_bits_[0] & 0x00001000u) != 0; } inline void FileOptions::set_has_java_string_check_utf8() { - _has_bits_[0] |= 0x00000800u; + _has_bits_[0] |= 0x00001000u; } inline void FileOptions::clear_has_java_string_check_utf8() { - _has_bits_[0] &= ~0x00000800u; + _has_bits_[0] &= ~0x00001000u; } inline void FileOptions::clear_java_string_check_utf8() { java_string_check_utf8_ = false; @@ -9169,13 +9256,13 @@ inline void FileOptions::set_java_string_check_utf8(bool value) { // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED]; inline bool FileOptions::has_optimize_for() const { - return (_has_bits_[0] & 0x00020000u) != 0; + return (_has_bits_[0] & 0x00080000u) != 0; } inline void FileOptions::set_has_optimize_for() { - _has_bits_[0] |= 0x00020000u; + _has_bits_[0] |= 0x00080000u; } inline void FileOptions::clear_has_optimize_for() { - _has_bits_[0] &= ~0x00020000u; + _has_bits_[0] &= ~0x00080000u; } inline void FileOptions::clear_optimize_for() { optimize_for_ = 1; @@ -9244,8 +9331,11 @@ inline ::std::string* FileOptions::mutable_go_package() { } inline ::std::string* FileOptions::release_go_package() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.go_package) + if (!has_go_package()) { + return NULL; + } clear_has_go_package(); - return go_package_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return go_package_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::set_allocated_go_package(::std::string* go_package) { if (go_package != NULL) { @@ -9279,13 +9369,13 @@ inline void FileOptions::unsafe_arena_set_allocated_go_package( // optional bool cc_generic_services = 16 [default = false]; inline bool FileOptions::has_cc_generic_services() const { - return (_has_bits_[0] & 0x00001000u) != 0; + return (_has_bits_[0] & 0x00002000u) != 0; } inline void FileOptions::set_has_cc_generic_services() { - _has_bits_[0] |= 0x00001000u; + _has_bits_[0] |= 0x00002000u; } inline void FileOptions::clear_has_cc_generic_services() { - _has_bits_[0] &= ~0x00001000u; + _has_bits_[0] &= ~0x00002000u; } inline void FileOptions::clear_cc_generic_services() { cc_generic_services_ = false; @@ -9303,13 +9393,13 @@ inline void FileOptions::set_cc_generic_services(bool value) { // optional bool java_generic_services = 17 [default = false]; inline bool FileOptions::has_java_generic_services() const { - return (_has_bits_[0] & 0x00002000u) != 0; + return (_has_bits_[0] & 0x00004000u) != 0; } inline void FileOptions::set_has_java_generic_services() { - _has_bits_[0] |= 0x00002000u; + _has_bits_[0] |= 0x00004000u; } inline void FileOptions::clear_has_java_generic_services() { - _has_bits_[0] &= ~0x00002000u; + _has_bits_[0] &= ~0x00004000u; } inline void FileOptions::clear_java_generic_services() { java_generic_services_ = false; @@ -9327,13 +9417,13 @@ inline void FileOptions::set_java_generic_services(bool value) { // optional bool py_generic_services = 18 [default = false]; inline bool FileOptions::has_py_generic_services() const { - return (_has_bits_[0] & 0x00004000u) != 0; + return (_has_bits_[0] & 0x00008000u) != 0; } inline void FileOptions::set_has_py_generic_services() { - _has_bits_[0] |= 0x00004000u; + _has_bits_[0] |= 0x00008000u; } inline void FileOptions::clear_has_py_generic_services() { - _has_bits_[0] &= ~0x00004000u; + _has_bits_[0] &= ~0x00008000u; } inline void FileOptions::clear_py_generic_services() { py_generic_services_ = false; @@ -9351,13 +9441,13 @@ inline void FileOptions::set_py_generic_services(bool value) { // optional bool php_generic_services = 42 [default = false]; inline bool FileOptions::has_php_generic_services() const { - return (_has_bits_[0] & 0x00008000u) != 0; + return (_has_bits_[0] & 0x00010000u) != 0; } inline void FileOptions::set_has_php_generic_services() { - _has_bits_[0] |= 0x00008000u; + _has_bits_[0] |= 0x00010000u; } inline void FileOptions::clear_has_php_generic_services() { - _has_bits_[0] &= ~0x00008000u; + _has_bits_[0] &= ~0x00010000u; } inline void FileOptions::clear_php_generic_services() { php_generic_services_ = false; @@ -9375,13 +9465,13 @@ inline void FileOptions::set_php_generic_services(bool value) { // optional bool deprecated = 23 [default = false]; inline bool FileOptions::has_deprecated() const { - return (_has_bits_[0] & 0x00010000u) != 0; + return (_has_bits_[0] & 0x00020000u) != 0; } inline void FileOptions::set_has_deprecated() { - _has_bits_[0] |= 0x00010000u; + _has_bits_[0] |= 0x00020000u; } inline void FileOptions::clear_has_deprecated() { - _has_bits_[0] &= ~0x00010000u; + _has_bits_[0] &= ~0x00020000u; } inline void FileOptions::clear_deprecated() { deprecated_ = false; @@ -9399,13 +9489,13 @@ inline void FileOptions::set_deprecated(bool value) { // optional bool cc_enable_arenas = 31 [default = false]; inline bool FileOptions::has_cc_enable_arenas() const { - return (_has_bits_[0] & 0x00000100u) != 0; + return (_has_bits_[0] & 0x00040000u) != 0; } inline void FileOptions::set_has_cc_enable_arenas() { - _has_bits_[0] |= 0x00000100u; + _has_bits_[0] |= 0x00040000u; } inline void FileOptions::clear_has_cc_enable_arenas() { - _has_bits_[0] &= ~0x00000100u; + _has_bits_[0] &= ~0x00040000u; } inline void FileOptions::clear_cc_enable_arenas() { cc_enable_arenas_ = false; @@ -9473,8 +9563,11 @@ inline ::std::string* FileOptions::mutable_objc_class_prefix() { } inline ::std::string* FileOptions::release_objc_class_prefix() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.objc_class_prefix) + if (!has_objc_class_prefix()) { + return NULL; + } clear_has_objc_class_prefix(); - return objc_class_prefix_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return objc_class_prefix_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::set_allocated_objc_class_prefix(::std::string* objc_class_prefix) { if (objc_class_prefix != NULL) { @@ -9558,8 +9651,11 @@ inline ::std::string* FileOptions::mutable_csharp_namespace() { } inline ::std::string* FileOptions::release_csharp_namespace() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.csharp_namespace) + if (!has_csharp_namespace()) { + return NULL; + } clear_has_csharp_namespace(); - return csharp_namespace_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return csharp_namespace_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::set_allocated_csharp_namespace(::std::string* csharp_namespace) { if (csharp_namespace != NULL) { @@ -9643,8 +9739,11 @@ inline ::std::string* FileOptions::mutable_swift_prefix() { } inline ::std::string* FileOptions::release_swift_prefix() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.swift_prefix) + if (!has_swift_prefix()) { + return NULL; + } clear_has_swift_prefix(); - return swift_prefix_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return swift_prefix_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::set_allocated_swift_prefix(::std::string* swift_prefix) { if (swift_prefix != NULL) { @@ -9728,8 +9827,11 @@ inline ::std::string* FileOptions::mutable_php_class_prefix() { } inline ::std::string* FileOptions::release_php_class_prefix() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_class_prefix) + if (!has_php_class_prefix()) { + return NULL; + } clear_has_php_class_prefix(); - return php_class_prefix_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return php_class_prefix_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::set_allocated_php_class_prefix(::std::string* php_class_prefix) { if (php_class_prefix != NULL) { @@ -9813,8 +9915,11 @@ inline ::std::string* FileOptions::mutable_php_namespace() { } inline ::std::string* FileOptions::release_php_namespace() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_namespace) + if (!has_php_namespace()) { + return NULL; + } clear_has_php_namespace(); - return php_namespace_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return php_namespace_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::set_allocated_php_namespace(::std::string* php_namespace) { if (php_namespace != NULL) { @@ -9846,6 +9951,182 @@ inline void FileOptions::unsafe_arena_set_allocated_php_namespace( // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.php_namespace) } +// optional string php_metadata_namespace = 44; +inline bool FileOptions::has_php_metadata_namespace() const { + return (_has_bits_[0] & 0x00000100u) != 0; +} +inline void FileOptions::set_has_php_metadata_namespace() { + _has_bits_[0] |= 0x00000100u; +} +inline void FileOptions::clear_has_php_metadata_namespace() { + _has_bits_[0] &= ~0x00000100u; +} +inline void FileOptions::clear_php_metadata_namespace() { + php_metadata_namespace_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + clear_has_php_metadata_namespace(); +} +inline const ::std::string& FileOptions::php_metadata_namespace() const { + // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.php_metadata_namespace) + return php_metadata_namespace_.Get(); +} +inline void FileOptions::set_php_metadata_namespace(const ::std::string& value) { + set_has_php_metadata_namespace(); + php_metadata_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); + // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.php_metadata_namespace) +} +#if LANG_CXX11 +inline void FileOptions::set_php_metadata_namespace(::std::string&& value) { + set_has_php_metadata_namespace(); + php_metadata_namespace_.Set( + &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.php_metadata_namespace) +} +#endif +inline void FileOptions::set_php_metadata_namespace(const char* value) { + GOOGLE_DCHECK(value != NULL); + set_has_php_metadata_namespace(); + php_metadata_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GetArenaNoVirtual()); + // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.php_metadata_namespace) +} +inline void FileOptions::set_php_metadata_namespace(const char* value, + size_t size) { + set_has_php_metadata_namespace(); + php_metadata_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + reinterpret_cast<const char*>(value), size), GetArenaNoVirtual()); + // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.php_metadata_namespace) +} +inline ::std::string* FileOptions::mutable_php_metadata_namespace() { + set_has_php_metadata_namespace(); + // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.php_metadata_namespace) + return php_metadata_namespace_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); +} +inline ::std::string* FileOptions::release_php_metadata_namespace() { + // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_metadata_namespace) + if (!has_php_metadata_namespace()) { + return NULL; + } + clear_has_php_metadata_namespace(); + return php_metadata_namespace_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); +} +inline void FileOptions::set_allocated_php_metadata_namespace(::std::string* php_metadata_namespace) { + if (php_metadata_namespace != NULL) { + set_has_php_metadata_namespace(); + } else { + clear_has_php_metadata_namespace(); + } + php_metadata_namespace_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), php_metadata_namespace, + GetArenaNoVirtual()); + // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.php_metadata_namespace) +} +inline ::std::string* FileOptions::unsafe_arena_release_php_metadata_namespace() { + // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.php_metadata_namespace) + GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); + clear_has_php_metadata_namespace(); + return php_metadata_namespace_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); +} +inline void FileOptions::unsafe_arena_set_allocated_php_metadata_namespace( + ::std::string* php_metadata_namespace) { + GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); + if (php_metadata_namespace != NULL) { + set_has_php_metadata_namespace(); + } else { + clear_has_php_metadata_namespace(); + } + php_metadata_namespace_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + php_metadata_namespace, GetArenaNoVirtual()); + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.php_metadata_namespace) +} + +// optional string ruby_package = 45; +inline bool FileOptions::has_ruby_package() const { + return (_has_bits_[0] & 0x00000200u) != 0; +} +inline void FileOptions::set_has_ruby_package() { + _has_bits_[0] |= 0x00000200u; +} +inline void FileOptions::clear_has_ruby_package() { + _has_bits_[0] &= ~0x00000200u; +} +inline void FileOptions::clear_ruby_package() { + ruby_package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + clear_has_ruby_package(); +} +inline const ::std::string& FileOptions::ruby_package() const { + // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.ruby_package) + return ruby_package_.Get(); +} +inline void FileOptions::set_ruby_package(const ::std::string& value) { + set_has_ruby_package(); + ruby_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); + // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.ruby_package) +} +#if LANG_CXX11 +inline void FileOptions::set_ruby_package(::std::string&& value) { + set_has_ruby_package(); + ruby_package_.Set( + &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual()); + // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.ruby_package) +} +#endif +inline void FileOptions::set_ruby_package(const char* value) { + GOOGLE_DCHECK(value != NULL); + set_has_ruby_package(); + ruby_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), + GetArenaNoVirtual()); + // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.ruby_package) +} +inline void FileOptions::set_ruby_package(const char* value, + size_t size) { + set_has_ruby_package(); + ruby_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( + reinterpret_cast<const char*>(value), size), GetArenaNoVirtual()); + // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.ruby_package) +} +inline ::std::string* FileOptions::mutable_ruby_package() { + set_has_ruby_package(); + // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.ruby_package) + return ruby_package_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); +} +inline ::std::string* FileOptions::release_ruby_package() { + // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.ruby_package) + if (!has_ruby_package()) { + return NULL; + } + clear_has_ruby_package(); + return ruby_package_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); +} +inline void FileOptions::set_allocated_ruby_package(::std::string* ruby_package) { + if (ruby_package != NULL) { + set_has_ruby_package(); + } else { + clear_has_ruby_package(); + } + ruby_package_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ruby_package, + GetArenaNoVirtual()); + // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.ruby_package) +} +inline ::std::string* FileOptions::unsafe_arena_release_ruby_package() { + // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.ruby_package) + GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); + clear_has_ruby_package(); + return ruby_package_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); +} +inline void FileOptions::unsafe_arena_set_allocated_ruby_package( + ::std::string* ruby_package) { + GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); + if (ruby_package != NULL) { + set_has_ruby_package(); + } else { + clear_has_ruby_package(); + } + ruby_package_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + ruby_package, GetArenaNoVirtual()); + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.ruby_package) +} + // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; inline int FileOptions::uninterpreted_option_size() const { return uninterpreted_option_.size(); @@ -10557,8 +10838,11 @@ inline ::std::string* UninterpretedOption_NamePart::mutable_name_part() { } inline ::std::string* UninterpretedOption_NamePart::release_name_part() { // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.NamePart.name_part) + if (!has_name_part()) { + return NULL; + } clear_has_name_part(); - return name_part_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_part_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void UninterpretedOption_NamePart::set_allocated_name_part(::std::string* name_part) { if (name_part != NULL) { @@ -10700,8 +10984,11 @@ inline ::std::string* UninterpretedOption::mutable_identifier_value() { } inline ::std::string* UninterpretedOption::release_identifier_value() { // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.identifier_value) + if (!has_identifier_value()) { + return NULL; + } clear_has_identifier_value(); - return identifier_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return identifier_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void UninterpretedOption::set_allocated_identifier_value(::std::string* identifier_value) { if (identifier_value != NULL) { @@ -10857,8 +11144,11 @@ inline ::std::string* UninterpretedOption::mutable_string_value() { } inline ::std::string* UninterpretedOption::release_string_value() { // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.string_value) + if (!has_string_value()) { + return NULL; + } clear_has_string_value(); - return string_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return string_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void UninterpretedOption::set_allocated_string_value(::std::string* string_value) { if (string_value != NULL) { @@ -10942,8 +11232,11 @@ inline ::std::string* UninterpretedOption::mutable_aggregate_value() { } inline ::std::string* UninterpretedOption::release_aggregate_value() { // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.aggregate_value) + if (!has_aggregate_value()) { + return NULL; + } clear_has_aggregate_value(); - return aggregate_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return aggregate_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void UninterpretedOption::set_allocated_aggregate_value(::std::string* aggregate_value) { if (aggregate_value != NULL) { @@ -11091,8 +11384,11 @@ inline ::std::string* SourceCodeInfo_Location::mutable_leading_comments() { } inline ::std::string* SourceCodeInfo_Location::release_leading_comments() { // @@protoc_insertion_point(field_release:google.protobuf.SourceCodeInfo.Location.leading_comments) + if (!has_leading_comments()) { + return NULL; + } clear_has_leading_comments(); - return leading_comments_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return leading_comments_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void SourceCodeInfo_Location::set_allocated_leading_comments(::std::string* leading_comments) { if (leading_comments != NULL) { @@ -11176,8 +11472,11 @@ inline ::std::string* SourceCodeInfo_Location::mutable_trailing_comments() { } inline ::std::string* SourceCodeInfo_Location::release_trailing_comments() { // @@protoc_insertion_point(field_release:google.protobuf.SourceCodeInfo.Location.trailing_comments) + if (!has_trailing_comments()) { + return NULL; + } clear_has_trailing_comments(); - return trailing_comments_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return trailing_comments_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void SourceCodeInfo_Location::set_allocated_trailing_comments(::std::string* trailing_comments) { if (trailing_comments != NULL) { @@ -11398,8 +11697,11 @@ inline ::std::string* GeneratedCodeInfo_Annotation::mutable_source_file() { } inline ::std::string* GeneratedCodeInfo_Annotation::release_source_file() { // @@protoc_insertion_point(field_release:google.protobuf.GeneratedCodeInfo.Annotation.source_file) + if (!has_source_file()) { + return NULL; + } clear_has_source_file(); - return source_file_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return source_file_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void GeneratedCodeInfo_Annotation::set_allocated_source_file(::std::string* source_file) { if (source_file != NULL) { @@ -11577,32 +11879,32 @@ GeneratedCodeInfo::annotation() const { namespace google { namespace protobuf { -template <> struct is_proto_enum< ::google::protobuf::FieldDescriptorProto_Type> : ::google::protobuf::internal::true_type {}; +template <> struct is_proto_enum< ::google::protobuf::FieldDescriptorProto_Type> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldDescriptorProto_Type>() { return ::google::protobuf::FieldDescriptorProto_Type_descriptor(); } -template <> struct is_proto_enum< ::google::protobuf::FieldDescriptorProto_Label> : ::google::protobuf::internal::true_type {}; +template <> struct is_proto_enum< ::google::protobuf::FieldDescriptorProto_Label> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldDescriptorProto_Label>() { return ::google::protobuf::FieldDescriptorProto_Label_descriptor(); } -template <> struct is_proto_enum< ::google::protobuf::FileOptions_OptimizeMode> : ::google::protobuf::internal::true_type {}; +template <> struct is_proto_enum< ::google::protobuf::FileOptions_OptimizeMode> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FileOptions_OptimizeMode>() { return ::google::protobuf::FileOptions_OptimizeMode_descriptor(); } -template <> struct is_proto_enum< ::google::protobuf::FieldOptions_CType> : ::google::protobuf::internal::true_type {}; +template <> struct is_proto_enum< ::google::protobuf::FieldOptions_CType> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldOptions_CType>() { return ::google::protobuf::FieldOptions_CType_descriptor(); } -template <> struct is_proto_enum< ::google::protobuf::FieldOptions_JSType> : ::google::protobuf::internal::true_type {}; +template <> struct is_proto_enum< ::google::protobuf::FieldOptions_JSType> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldOptions_JSType>() { return ::google::protobuf::FieldOptions_JSType_descriptor(); } -template <> struct is_proto_enum< ::google::protobuf::MethodOptions_IdempotencyLevel> : ::google::protobuf::internal::true_type {}; +template <> struct is_proto_enum< ::google::protobuf::MethodOptions_IdempotencyLevel> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::MethodOptions_IdempotencyLevel>() { return ::google::protobuf::MethodOptions_IdempotencyLevel_descriptor(); @@ -11613,4 +11915,4 @@ inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::MethodOption // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2fdescriptor_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fdescriptor_2eproto diff --git a/src/google/protobuf/descriptor.proto b/src/google/protobuf/descriptor.proto index 8697a50d..ed08fcbc 100644 --- a/src/google/protobuf/descriptor.proto +++ b/src/google/protobuf/descriptor.proto @@ -417,6 +417,17 @@ message FileOptions { // determining the namespace. optional string php_namespace = 41; + + // Use this option to change the namespace of php generated metadata classes. + // Default is empty. When this option is empty, the proto file name will be used + // for determining the namespace. + optional string php_metadata_namespace = 44; + + // Use this option to change the package of ruby generated classes. Default + // is empty. When this option is not set, the package name will be used for + // determining the ruby package. + optional string ruby_package = 45; + // The parser stores options it doesn't recognize here. // See the documentation for the "Options" section above. repeated UninterpretedOption uninterpreted_option = 999; diff --git a/src/google/protobuf/descriptor_database.h b/src/google/protobuf/descriptor_database.h index 28f8af7a..d61f2a6a 100644 --- a/src/google/protobuf/descriptor_database.h +++ b/src/google/protobuf/descriptor_database.h @@ -214,7 +214,7 @@ class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase { // will find it. Proof: // 1) Define the "search key" to be the key we are looking for, the "found // key" to be the key found in step (1), and the "match key" to be the - // key which actually matches the serach key (i.e. the key we're trying + // key which actually matches the search key (i.e. the key we're trying // to find). // 2) The found key must be less than or equal to the search key by // definition. diff --git a/src/google/protobuf/descriptor_database_unittest.cc b/src/google/protobuf/descriptor_database_unittest.cc index 9d710886..083ef8f2 100644 --- a/src/google/protobuf/descriptor_database_unittest.cc +++ b/src/google/protobuf/descriptor_database_unittest.cc @@ -36,13 +36,10 @@ #include <algorithm> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif -#include <google/protobuf/descriptor_database.h> -#include <google/protobuf/descriptor.h> #include <google/protobuf/descriptor.pb.h> +#include <google/protobuf/descriptor.h> +#include <google/protobuf/descriptor_database.h> #include <google/protobuf/text_format.h> #include <google/protobuf/stubs/logging.h> @@ -179,7 +176,7 @@ class DescriptorDatabaseTest EXPECT_FALSE(test_case_->AddToDatabase(file_proto)); } - google::protobuf::scoped_ptr<DescriptorDatabaseTestCase> test_case_; + std::unique_ptr<DescriptorDatabaseTestCase> test_case_; DescriptorDatabase* database_; }; diff --git a/src/google/protobuf/descriptor_unittest.cc b/src/google/protobuf/descriptor_unittest.cc index b0337035..54da095a 100644 --- a/src/google/protobuf/descriptor_unittest.cc +++ b/src/google/protobuf/descriptor_unittest.cc @@ -36,9 +36,6 @@ #include <limits> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <vector> #include <google/protobuf/compiler/importer.h> @@ -2252,7 +2249,7 @@ class MiscTest : public testing::Test { return field != NULL ? field->enum_type() : NULL; } - google::protobuf::scoped_ptr<DescriptorPool> pool_; + std::unique_ptr<DescriptorPool> pool_; }; TEST_F(MiscTest, TypeNames) { @@ -2682,7 +2679,7 @@ class AllowUnknownDependenciesTest const FieldDescriptor* qux_field_; SimpleDescriptorDatabase db_; // used if in FALLBACK_DATABASE mode. - google::protobuf::scoped_ptr<DescriptorPool> pool_; + std::unique_ptr<DescriptorPool> pool_; }; TEST_P(AllowUnknownDependenciesTest, PlaceholderFile) { @@ -3952,8 +3949,22 @@ TEST_F(ValidationErrorTest, EnumReservedRangeOverlap) { " reserved_range { start: 5 end: 15 }" "}", - "foo.proto: Foo: NUMBER: Reserved range 5 to 14" - " overlaps with already-defined range 10 to 19.\n"); + "foo.proto: Foo: NUMBER: Reserved range 5 to 15" + " overlaps with already-defined range 10 to 20.\n"); +} + +TEST_F(ValidationErrorTest, EnumReservedRangeOverlapByOne) { + BuildFileWithErrors( + "name: \"foo.proto\" " + "enum_type {" + " name: \"Foo\"" + " value { name:\"BAR\" number:0 }" + " reserved_range { start: 10 end: 20 }" + " reserved_range { start: 5 end: 10 }" + "}", + + "foo.proto: Foo: NUMBER: Reserved range 5 to 10" + " overlaps with already-defined range 10 to 20.\n"); } TEST_F(ValidationErrorTest, EnumNegativeReservedRangeOverlap) { @@ -3966,8 +3977,8 @@ TEST_F(ValidationErrorTest, EnumNegativeReservedRangeOverlap) { " reserved_range { start: -15 end: -5 }" "}", - "foo.proto: Foo: NUMBER: Reserved range -15 to -6" - " overlaps with already-defined range -20 to -11.\n"); + "foo.proto: Foo: NUMBER: Reserved range -15 to -5" + " overlaps with already-defined range -20 to -10.\n"); } TEST_F(ValidationErrorTest, EnumMixedReservedRangeOverlap) { @@ -3980,8 +3991,22 @@ TEST_F(ValidationErrorTest, EnumMixedReservedRangeOverlap) { " reserved_range { start: -15 end: 5 }" "}", - "foo.proto: Foo: NUMBER: Reserved range -15 to 4" - " overlaps with already-defined range -20 to 9.\n"); + "foo.proto: Foo: NUMBER: Reserved range -15 to 5" + " overlaps with already-defined range -20 to 10.\n"); +} + +TEST_F(ValidationErrorTest, EnumMixedReservedRangeOverlap2) { + BuildFileWithErrors( + "name: \"foo.proto\" " + "enum_type {" + " name: \"Foo\"" + " value { name:\"BAR\" number:20 }" + " reserved_range { start: -20 end: 10 }" + " reserved_range { start: 10 end: 10 }" + "}", + + "foo.proto: Foo: NUMBER: Reserved range 10 to 10" + " overlaps with already-defined range -20 to 10.\n"); } TEST_F(ValidationErrorTest, EnumReservedRangeStartGreaterThanEnd) { @@ -6893,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", @@ -6937,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 @@ -6956,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)); } @@ -6989,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/drop_unknown_fields_test.cc b/src/google/protobuf/drop_unknown_fields_test.cc index f2f2f749..437a04e7 100644 --- a/src/google/protobuf/drop_unknown_fields_test.cc +++ b/src/google/protobuf/drop_unknown_fields_test.cc @@ -29,9 +29,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/unittest_drop_unknown_fields.pb.h> #include <google/protobuf/dynamic_message.h> @@ -94,7 +91,7 @@ TEST(DropUnknownFieldsTest, DynamicMessageDefaultDrop) { foo_with_extra_fields.set_extra_int32_value(2); google::protobuf::DynamicMessageFactory factory; - google::protobuf::scoped_ptr<google::protobuf::Message> foo( + std::unique_ptr<google::protobuf::Message> foo( factory.GetPrototype(Foo::descriptor())->New()); ASSERT_TRUE(foo->ParseFromString(foo_with_extra_fields.SerializeAsString())); EXPECT_TRUE(foo->GetReflection()->GetUnknownFields(*foo).empty()); @@ -114,7 +111,7 @@ TEST(DropUnknownFieldsTest, DynamicMessageDefaultPreserve) { foo_with_extra_fields.set_extra_int32_value(2); google::protobuf::DynamicMessageFactory factory; - google::protobuf::scoped_ptr<google::protobuf::Message> foo( + std::unique_ptr<google::protobuf::Message> foo( factory.GetPrototype(Foo::descriptor())->New()); ASSERT_TRUE(foo->ParseFromString(foo_with_extra_fields.SerializeAsString())); EXPECT_FALSE(foo->GetReflection()->GetUnknownFields(*foo).empty()); diff --git a/src/google/protobuf/duration.pb.cc b/src/google/protobuf/duration.pb.cc index b4d5eb5f..0c67f86e 100644 --- a/src/google/protobuf/duration.pb.cc +++ b/src/google/protobuf/duration.pb.cc @@ -7,7 +7,6 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> -#include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> @@ -19,6 +18,7 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + namespace google { namespace protobuf { class DurationDefaultTypeInternal { @@ -29,14 +29,9 @@ class DurationDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2fduration_2eproto { -void InitDefaultsDurationImpl() { +static void InitDefaultsDuration() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_Duration_default_instance_; new (ptr) ::google::protobuf::Duration(); @@ -45,9 +40,11 @@ void InitDefaultsDurationImpl() { ::google::protobuf::Duration::InitAsDefaultInstance(); } -void InitDefaultsDuration() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDurationImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Duration = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDuration}, {}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_Duration.base); } ::google::protobuf::Metadata file_level_metadata[1]; @@ -69,17 +66,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Duration_default_instance_), }; -void protobuf_AssignDescriptors() { +static void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/duration.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/duration.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } -void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); +static void protobuf_AssignDescriptorsOnce() { + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -88,7 +84,7 @@ void protobuf_RegisterTypes(const ::std::string&) { ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1); } -void AddDescriptorsImpl() { +static void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n\036google/protobuf/duration.proto\022\017google" @@ -105,8 +101,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -129,24 +125,22 @@ const int Duration::kNanosFieldNumber; Duration::Duration() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fduration_2eproto::InitDefaultsDuration(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fduration_2eproto::scc_info_Duration.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Duration) } Duration::Duration(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fduration_2eproto::InitDefaultsDuration(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fduration_2eproto::scc_info_Duration.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Duration) } Duration::Duration(const Duration& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&seconds_, &from.seconds_, static_cast<size_t>(reinterpret_cast<char*>(&nanos_) - @@ -158,7 +152,6 @@ void Duration::SharedCtor() { ::memset(&seconds_, 0, static_cast<size_t>( reinterpret_cast<char*>(&nanos_) - reinterpret_cast<char*>(&seconds_)) + sizeof(nanos_)); - _cached_size_ = 0; } Duration::~Duration() { @@ -177,9 +170,7 @@ void Duration::ArenaDtor(void* object) { void Duration::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Duration::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Duration::descriptor() { ::protobuf_google_2fprotobuf_2fduration_2eproto::protobuf_AssignDescriptorsOnce(); @@ -187,7 +178,7 @@ const ::google::protobuf::Descriptor* Duration::descriptor() { } const Duration& Duration::default_instance() { - ::protobuf_google_2fprotobuf_2fduration_2eproto::InitDefaultsDuration(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fduration_2eproto::scc_info_Duration.base); return *internal_default_instance(); } @@ -210,7 +201,7 @@ bool Duration::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Duration) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -334,9 +325,7 @@ size_t Duration::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -412,7 +401,6 @@ void Duration::InternalSwap(Duration* other) { swap(seconds_, other->seconds_); swap(nanos_, other->nanos_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Duration::GetMetadata() const { @@ -426,7 +414,7 @@ void Duration::InternalSwap(Duration* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Duration* Arena::CreateMessage< ::google::protobuf::Duration >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Duration* Arena::CreateMaybeMessage< ::google::protobuf::Duration >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Duration >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/duration.pb.h b/src/google/protobuf/duration.pb.h index 7fe0748d..3d0889d1 100644 --- a/src/google/protobuf/duration.pb.h +++ b/src/google/protobuf/duration.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/duration.proto -#ifndef PROTOBUF_google_2fprotobuf_2fduration_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2fduration_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto #include <string> @@ -24,12 +24,14 @@ #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> +#include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fduration_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2fduration_2eproto { // Internal implementation detail -- do not use these members. @@ -42,11 +44,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsDurationImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsDuration(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsDuration(); -} } // namespace protobuf_google_2fprotobuf_2fduration_2eproto namespace google { namespace protobuf { @@ -57,7 +54,7 @@ LIBPROTOBUF_EXPORT extern DurationDefaultTypeInternal _Duration_default_instance } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Duration* Arena::CreateMessage< ::google::protobuf::Duration>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Duration* Arena::CreateMaybeMessage<::google::protobuf::Duration>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -91,10 +88,10 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -105,7 +102,7 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot return reinterpret_cast<const Duration*>( &_Duration_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void UnsafeArenaSwap(Duration* other); @@ -116,32 +113,33 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot // implements Message ---------------------------------------------- - inline Duration* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Duration>(NULL); + inline Duration* New() const final { + return CreateMaybeMessage<Duration>(NULL); } - Duration* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Duration>(arena); + Duration* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<Duration>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Duration& from); void MergeFrom(const Duration& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Duration* other); protected: explicit Duration(::google::protobuf::Arena* arena); @@ -157,7 +155,7 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -184,9 +182,8 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot typedef void DestructorSkippable_; ::google::protobuf::int64 seconds_; ::google::protobuf::int32 nanos_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fduration_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fduration_2eproto::InitDefaultsDurationImpl(); }; // =================================================================== @@ -238,4 +235,4 @@ inline void Duration::set_nanos(::google::protobuf::int32 value) { // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2fduration_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto diff --git a/src/google/protobuf/dynamic_message.cc b/src/google/protobuf/dynamic_message.cc index 48d6aad8..ceedf500 100644 --- a/src/google/protobuf/dynamic_message.cc +++ b/src/google/protobuf/dynamic_message.cc @@ -65,9 +65,6 @@ #include <algorithm> #include <google/protobuf/stubs/hash.h> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/stubs/common.h> @@ -232,13 +229,13 @@ class DynamicMessage : public Message { // Warning: The order in which the following pointers are defined is // important (the prototype must be deleted *before* the offsets). - google::protobuf::scoped_array<uint32> offsets; - google::protobuf::scoped_array<uint32> has_bits_indices; - google::protobuf::scoped_ptr<const GeneratedMessageReflection> reflection; - // Don't use a scoped_ptr to hold the prototype: the destructor for + std::unique_ptr<uint32[]> offsets; + std::unique_ptr<uint32[]> has_bits_indices; + std::unique_ptr<const GeneratedMessageReflection> reflection; + // Don't use a unique_ptr to hold the prototype: the destructor for // DynamicMessage needs to know whether it is the prototype, and does so by // looking back at this field. This would assume details about the - // implementation of scoped_ptr. + // implementation of unique_ptr. const DynamicMessage* prototype; int weak_field_map_offset; // The offset for the weak_field_map; diff --git a/src/google/protobuf/dynamic_message.h b/src/google/protobuf/dynamic_message.h index e29b148d..d84cc8af 100644 --- a/src/google/protobuf/dynamic_message.h +++ b/src/google/protobuf/dynamic_message.h @@ -40,9 +40,6 @@ #include <algorithm> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <vector> #include <google/protobuf/message.h> @@ -130,7 +127,7 @@ class LIBPROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory { // public header (for good reason), but dynamic_message.h is, and public // headers may only #include other public headers. struct PrototypeMap; - google::protobuf::scoped_ptr<PrototypeMap> prototypes_; + std::unique_ptr<PrototypeMap> prototypes_; mutable Mutex prototypes_mutex_; friend class DynamicMessage; diff --git a/src/google/protobuf/dynamic_message_unittest.cc b/src/google/protobuf/dynamic_message_unittest.cc index 34f3641b..94446b08 100644 --- a/src/google/protobuf/dynamic_message_unittest.cc +++ b/src/google/protobuf/dynamic_message_unittest.cc @@ -41,16 +41,13 @@ // DynamicMessage. #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif -#include <google/protobuf/dynamic_message.h> -#include <google/protobuf/descriptor.h> -#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/test_util.h> #include <google/protobuf/unittest.pb.h> #include <google/protobuf/unittest_no_field_presence.pb.h> +#include <google/protobuf/descriptor.pb.h> +#include <google/protobuf/descriptor.h> +#include <google/protobuf/dynamic_message.h> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> diff --git a/src/google/protobuf/empty.pb.cc b/src/google/protobuf/empty.pb.cc index ffff80b9..7bc46121 100644 --- a/src/google/protobuf/empty.pb.cc +++ b/src/google/protobuf/empty.pb.cc @@ -7,7 +7,6 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> -#include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> @@ -19,6 +18,7 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + namespace google { namespace protobuf { class EmptyDefaultTypeInternal { @@ -29,14 +29,9 @@ class EmptyDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2fempty_2eproto { -void InitDefaultsEmptyImpl() { +static void InitDefaultsEmpty() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_Empty_default_instance_; new (ptr) ::google::protobuf::Empty(); @@ -45,9 +40,11 @@ void InitDefaultsEmptyImpl() { ::google::protobuf::Empty::InitAsDefaultInstance(); } -void InitDefaultsEmpty() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEmptyImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Empty = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsEmpty}, {}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_Empty.base); } ::google::protobuf::Metadata file_level_metadata[1]; @@ -67,17 +64,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Empty_default_instance_), }; -void protobuf_AssignDescriptors() { +static void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/empty.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/empty.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } -void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); +static void protobuf_AssignDescriptorsOnce() { + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -86,7 +82,7 @@ void protobuf_RegisterTypes(const ::std::string&) { ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1); } -void AddDescriptorsImpl() { +static void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n\033google/protobuf/empty.proto\022\017google.pr" @@ -102,8 +98,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -124,30 +120,27 @@ void Empty::InitAsDefaultInstance() { Empty::Empty() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fempty_2eproto::InitDefaultsEmpty(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fempty_2eproto::scc_info_Empty.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Empty) } Empty::Empty(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fempty_2eproto::InitDefaultsEmpty(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fempty_2eproto::scc_info_Empty.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Empty) } Empty::Empty(const Empty& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.Empty) } void Empty::SharedCtor() { - _cached_size_ = 0; } Empty::~Empty() { @@ -166,9 +159,7 @@ void Empty::ArenaDtor(void* object) { void Empty::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Empty::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Empty::descriptor() { ::protobuf_google_2fprotobuf_2fempty_2eproto::protobuf_AssignDescriptorsOnce(); @@ -176,7 +167,7 @@ const ::google::protobuf::Descriptor* Empty::descriptor() { } const Empty& Empty::default_instance() { - ::protobuf_google_2fprotobuf_2fempty_2eproto::InitDefaultsEmpty(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fempty_2eproto::scc_info_Empty.base); return *internal_default_instance(); } @@ -196,7 +187,7 @@ bool Empty::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Empty) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; handle_unusual: @@ -253,9 +244,7 @@ size_t Empty::ByteSizeLong() const { (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -323,7 +312,6 @@ void Empty::UnsafeArenaSwap(Empty* other) { void Empty::InternalSwap(Empty* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Empty::GetMetadata() const { @@ -337,7 +325,7 @@ void Empty::InternalSwap(Empty* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Empty* Arena::CreateMessage< ::google::protobuf::Empty >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Empty* Arena::CreateMaybeMessage< ::google::protobuf::Empty >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Empty >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/empty.pb.h b/src/google/protobuf/empty.pb.h index 2fef9a43..53857e5f 100644 --- a/src/google/protobuf/empty.pb.h +++ b/src/google/protobuf/empty.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/empty.proto -#ifndef PROTOBUF_google_2fprotobuf_2fempty_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2fempty_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto #include <string> @@ -24,12 +24,14 @@ #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> +#include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fempty_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2fempty_2eproto { // Internal implementation detail -- do not use these members. @@ -42,11 +44,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsEmptyImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsEmpty(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsEmpty(); -} } // namespace protobuf_google_2fprotobuf_2fempty_2eproto namespace google { namespace protobuf { @@ -57,7 +54,7 @@ LIBPROTOBUF_EXPORT extern EmptyDefaultTypeInternal _Empty_default_instance_; } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Empty* Arena::CreateMessage< ::google::protobuf::Empty>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Empty* Arena::CreateMaybeMessage<::google::protobuf::Empty>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -91,10 +88,10 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_ return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -105,7 +102,7 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_ return reinterpret_cast<const Empty*>( &_Empty_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void UnsafeArenaSwap(Empty* other); @@ -116,32 +113,33 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_ // implements Message ---------------------------------------------- - inline Empty* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Empty>(NULL); + inline Empty* New() const final { + return CreateMaybeMessage<Empty>(NULL); } - Empty* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Empty>(arena); + Empty* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<Empty>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Empty& from); void MergeFrom(const Empty& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Empty* other); protected: explicit Empty(::google::protobuf::Arena* arena); @@ -157,7 +155,7 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_ } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -170,9 +168,8 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_ template <typename T> friend class ::google::protobuf::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fempty_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fempty_2eproto::InitDefaultsEmptyImpl(); }; // =================================================================== @@ -196,4 +193,4 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_ // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2fempty_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto diff --git a/src/google/protobuf/extension_set.cc b/src/google/protobuf/extension_set.cc index 8f104800..b587b38f 100644 --- a/src/google/protobuf/extension_set.cc +++ b/src/google/protobuf/extension_set.cc @@ -33,6 +33,7 @@ // Sanjay Ghemawat, Jeff Dean, and others. #include <google/protobuf/stubs/hash.h> +#include <tuple> #include <utility> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/once.h> @@ -179,20 +180,29 @@ void ExtensionSet::RegisterMessageExtension(const MessageLite* containing_type, // Constructors and basic methods. ExtensionSet::ExtensionSet(::google::protobuf::Arena* arena) - : arena_(arena) { - if (arena_ != NULL) { - arena_->OwnDestructor(&extensions_); - } -} - -ExtensionSet::ExtensionSet() : arena_(NULL) {} + : arena_(arena), + flat_capacity_(0), + flat_size_(0), + map_{flat_capacity_ == 0 ? NULL + : ::google::protobuf::Arena::CreateArray<KeyValue>( + arena_, flat_capacity_)} {} + +ExtensionSet::ExtensionSet() + : arena_(NULL), + flat_capacity_(0), + flat_size_(0), + map_{flat_capacity_ == 0 ? NULL + : ::google::protobuf::Arena::CreateArray<KeyValue>( + arena_, flat_capacity_)} {} ExtensionSet::~ExtensionSet() { // Deletes all allocated extensions. if (arena_ == NULL) { - for (ExtensionMap::iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - iter->second.Free(); + ForEach([](int /* number */, Extension& ext) { ext.Free(); }); + if (GOOGLE_PREDICT_FALSE(is_large())) { + delete map_.large; + } else { + delete[] map_.flat; } } } @@ -203,45 +213,43 @@ ExtensionSet::~ExtensionSet() { // vector<const FieldDescriptor*>* output) const bool ExtensionSet::Has(int number) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end()) return false; - GOOGLE_DCHECK(!iter->second.is_repeated); - return !iter->second.is_cleared; + const Extension* ext = FindOrNull(number); + if (ext == NULL) return false; + GOOGLE_DCHECK(!ext->is_repeated); + return !ext->is_cleared; } int ExtensionSet::NumExtensions() const { int result = 0; - for (ExtensionMap::const_iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - if (!iter->second.is_cleared) { + ForEach([&result](int /* number */, const Extension& ext) { + if (!ext.is_cleared) { ++result; } - } + }); return result; } int ExtensionSet::ExtensionSize(int number) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end()) return 0; - return iter->second.GetSize(); + const Extension* ext = FindOrNull(number); + return ext == NULL ? 0 : ext->GetSize(); } FieldType ExtensionSet::ExtensionType(int number) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end()) { + const Extension* ext = FindOrNull(number); + if (ext == NULL) { GOOGLE_LOG(DFATAL) << "Don't lookup extension types if they aren't present (1). "; return 0; } - if (iter->second.is_cleared) { + if (ext->is_cleared) { GOOGLE_LOG(DFATAL) << "Don't lookup extension types if they aren't present (2). "; } - return iter->second.type; + return ext->type; } void ExtensionSet::ClearExtension(int number) { - ExtensionMap::iterator iter = extensions_.find(number); - if (iter == extensions_.end()) return; - iter->second.Clear(); + Extension* ext = FindOrNull(number); + if (ext == NULL) return; + ext->Clear(); } // =================================================================== @@ -267,12 +275,12 @@ enum Cardinality { \ LOWERCASE ExtensionSet::Get##CAMELCASE(int number, \ LOWERCASE default_value) const { \ - ExtensionMap::const_iterator iter = extensions_.find(number); \ - if (iter == extensions_.end() || iter->second.is_cleared) { \ + const Extension* extension = FindOrNull(number); \ + if (extension == NULL || extension->is_cleared) { \ return default_value; \ } else { \ - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, UPPERCASE); \ - return iter->second.LOWERCASE##_value; \ + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, UPPERCASE); \ + return extension->LOWERCASE##_value; \ } \ } \ \ @@ -292,18 +300,18 @@ void ExtensionSet::Set##CAMELCASE(int number, FieldType type, \ } \ \ LOWERCASE ExtensionSet::GetRepeated##CAMELCASE(int number, int index) const { \ - ExtensionMap::const_iterator iter = extensions_.find(number); \ - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; \ - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, UPPERCASE); \ - return iter->second.repeated_##LOWERCASE##_value->Get(index); \ + const Extension* extension = FindOrNull(number); \ + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; \ + GOOGLE_DCHECK_TYPE(*extension, REPEATED, UPPERCASE); \ + return extension->repeated_##LOWERCASE##_value->Get(index); \ } \ \ void ExtensionSet::SetRepeated##CAMELCASE( \ int number, int index, LOWERCASE value) { \ - ExtensionMap::iterator iter = extensions_.find(number); \ - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; \ - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, UPPERCASE); \ - iter->second.repeated_##LOWERCASE##_value->Set(index, value); \ + Extension* extension = FindOrNull(number); \ + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; \ + GOOGLE_DCHECK_TYPE(*extension, REPEATED, UPPERCASE); \ + extension->repeated_##LOWERCASE##_value->Set(index, value); \ } \ \ void ExtensionSet::Add##CAMELCASE(int number, FieldType type, \ @@ -336,13 +344,13 @@ PRIMITIVE_ACCESSORS( BOOL, bool, Bool) const void* ExtensionSet::GetRawRepeatedField(int number, const void* default_value) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end()) { + const Extension* extension = FindOrNull(number); + if (extension == NULL) { return default_value; } // We assume that all the RepeatedField<>* pointers have the same // size and alignment within the anonymous union in Extension. - return iter->second.repeated_int32_value; + return extension->repeated_int32_value; } void* ExtensionSet::MutableRawRepeatedField(int number, FieldType field_type, @@ -393,7 +401,7 @@ void* ExtensionSet::MutableRawRepeatedField(int number, FieldType field_type, break; case WireFormatLite::CPPTYPE_STRING: extension->repeated_string_value = - Arena::CreateMessage<RepeatedPtrField< ::std::string> >(arena_); + Arena::CreateMessage<RepeatedPtrField<::std::string> >(arena_); break; case WireFormatLite::CPPTYPE_MESSAGE: extension->repeated_message_value = @@ -410,11 +418,11 @@ void* ExtensionSet::MutableRawRepeatedField(int number, FieldType field_type, // Compatible version using old call signature. Does not create extensions when // the don't already exist; instead, just GOOGLE_CHECK-fails. void* ExtensionSet::MutableRawRepeatedField(int number) { - ExtensionMap::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter == extensions_.end()) << "Extension not found."; + Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Extension not found."; // We assume that all the RepeatedField<>* pointers have the same // size and alignment within the anonymous union in Extension. - return iter->second.repeated_int32_value; + return extension->repeated_int32_value; } @@ -422,13 +430,13 @@ void* ExtensionSet::MutableRawRepeatedField(int number) { // Enums int ExtensionSet::GetEnum(int number, int default_value) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end() || iter->second.is_cleared) { + const Extension* extension = FindOrNull(number); + if (extension == NULL || extension->is_cleared) { // Not present. Return the default value. return default_value; } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, ENUM); - return iter->second.enum_value; + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, ENUM); + return extension->enum_value; } } @@ -447,17 +455,17 @@ void ExtensionSet::SetEnum(int number, FieldType type, int value, } int ExtensionSet::GetRepeatedEnum(int number, int index) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, ENUM); - return iter->second.repeated_enum_value->Get(index); + const Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_DCHECK_TYPE(*extension, REPEATED, ENUM); + return extension->repeated_enum_value->Get(index); } void ExtensionSet::SetRepeatedEnum(int number, int index, int value) { - ExtensionMap::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, ENUM); - iter->second.repeated_enum_value->Set(index, value); + Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_DCHECK_TYPE(*extension, REPEATED, ENUM); + extension->repeated_enum_value->Set(index, value); } void ExtensionSet::AddEnum(int number, FieldType type, @@ -483,13 +491,13 @@ void ExtensionSet::AddEnum(int number, FieldType type, const string& ExtensionSet::GetString(int number, const string& default_value) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end() || iter->second.is_cleared) { + const Extension* extension = FindOrNull(number); + if (extension == NULL || extension->is_cleared) { // Not present. Return the default value. return default_value; } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, STRING); - return *iter->second.string_value; + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, STRING); + return *extension->string_value; } } @@ -509,17 +517,17 @@ string* ExtensionSet::MutableString(int number, FieldType type, } const string& ExtensionSet::GetRepeatedString(int number, int index) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, STRING); - return iter->second.repeated_string_value->Get(index); + const Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_DCHECK_TYPE(*extension, REPEATED, STRING); + return extension->repeated_string_value->Get(index); } string* ExtensionSet::MutableRepeatedString(int number, int index) { - ExtensionMap::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, STRING); - return iter->second.repeated_string_value->Mutable(index); + Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_DCHECK_TYPE(*extension, REPEATED, STRING); + return extension->repeated_string_value->Mutable(index); } string* ExtensionSet::AddString(int number, FieldType type, @@ -543,16 +551,16 @@ string* ExtensionSet::AddString(int number, FieldType type, const MessageLite& ExtensionSet::GetMessage( int number, const MessageLite& default_value) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end()) { + const Extension* extension = FindOrNull(number); + if (extension == NULL) { // Not present. Return the default value. return default_value; } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE); - if (iter->second.is_lazy) { - return iter->second.lazymessage_value->GetMessage(default_value); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); + if (extension->is_lazy) { + return extension->lazymessage_value->GetMessage(default_value); } else { - return *iter->second.message_value; + return *extension->message_value; } } } @@ -663,55 +671,53 @@ void ExtensionSet::UnsafeArenaSetAllocatedMessage( extension->is_cleared = false; } - MessageLite* ExtensionSet::ReleaseMessage(int number, const MessageLite& prototype) { - ExtensionMap::iterator iter = extensions_.find(number); - if (iter == extensions_.end()) { + Extension* extension = FindOrNull(number); + if (extension == NULL) { // Not present. Return NULL. return NULL; } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); MessageLite* ret = NULL; - if (iter->second.is_lazy) { - ret = iter->second.lazymessage_value->ReleaseMessage(prototype); + if (extension->is_lazy) { + ret = extension->lazymessage_value->ReleaseMessage(prototype); if (arena_ == NULL) { - delete iter->second.lazymessage_value; + delete extension->lazymessage_value; } } else { if (arena_ == NULL) { - ret = iter->second.message_value; + ret = extension->message_value; } else { // ReleaseMessage() always returns a heap-allocated message, and we are // on an arena, so we need to make a copy of this message to return. - ret = (iter->second.message_value)->New(); - ret->CheckTypeAndMergeFrom(*iter->second.message_value); + ret = extension->message_value->New(); + ret->CheckTypeAndMergeFrom(*extension->message_value); } } - extensions_.erase(number); + Erase(number); return ret; } } MessageLite* ExtensionSet::UnsafeArenaReleaseMessage( int number, const MessageLite& prototype) { - ExtensionMap::iterator iter = extensions_.find(number); - if (iter == extensions_.end()) { + Extension* extension = FindOrNull(number); + if (extension == NULL) { // Not present. Return NULL. return NULL; } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); MessageLite* ret = NULL; - if (iter->second.is_lazy) { - ret = - iter->second.lazymessage_value->UnsafeArenaReleaseMessage(prototype); + if (extension->is_lazy) { + ret = extension->lazymessage_value->UnsafeArenaReleaseMessage(prototype); if (arena_ == NULL) { - delete iter->second.lazymessage_value; + delete extension->lazymessage_value; } } else { - ret = iter->second.message_value; + ret = extension->message_value; } - extensions_.erase(number); + Erase(number); return ret; } } @@ -722,17 +728,17 @@ MessageLite* ExtensionSet::UnsafeArenaReleaseMessage( const MessageLite& ExtensionSet::GetRepeatedMessage( int number, int index) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, MESSAGE); - return iter->second.repeated_message_value->Get(index); + const Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_DCHECK_TYPE(*extension, REPEATED, MESSAGE); + return extension->repeated_message_value->Get(index); } MessageLite* ExtensionSet::MutableRepeatedMessage(int number, int index) { - ExtensionMap::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, MESSAGE); - return iter->second.repeated_message_value->Mutable(index); + Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_DCHECK_TYPE(*extension, REPEATED, MESSAGE); + return extension->repeated_message_value->Mutable(index); } MessageLite* ExtensionSet::AddMessage(int number, FieldType type, @@ -752,7 +758,7 @@ MessageLite* ExtensionSet::AddMessage(int number, FieldType type, // RepeatedPtrField<MessageLite> does not know how to Add() since it cannot // allocate an abstract object, so we have to be tricky. MessageLite* result = - reinterpret_cast< ::google::protobuf::internal::RepeatedPtrFieldBase*>( + reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>( extension->repeated_message_value) ->AddFromCleared<GenericTypeHandler<MessageLite> >(); if (result == NULL) { @@ -770,10 +776,8 @@ MessageLite* ExtensionSet::AddMessage(int number, FieldType type, #undef GOOGLE_DCHECK_TYPE void ExtensionSet::RemoveLast(int number) { - ExtensionMap::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - - Extension* extension = &iter->second; + Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; GOOGLE_DCHECK(extension->is_repeated); switch(cpp_type(extension->type)) { @@ -811,20 +815,16 @@ void ExtensionSet::RemoveLast(int number) { } MessageLite* ExtensionSet::ReleaseLast(int number) { - ExtensionMap::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - - Extension* extension = &iter->second; + Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; GOOGLE_DCHECK(extension->is_repeated); GOOGLE_DCHECK(cpp_type(extension->type) == WireFormatLite::CPPTYPE_MESSAGE); return extension->repeated_message_value->ReleaseLast(); } void ExtensionSet::SwapElements(int number, int index1, int index2) { - ExtensionMap::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - - Extension* extension = &iter->second; + Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; GOOGLE_DCHECK(extension->is_repeated); switch(cpp_type(extension->type)) { @@ -864,18 +864,45 @@ void ExtensionSet::SwapElements(int number, int index1, int index2) { // =================================================================== void ExtensionSet::Clear() { - for (ExtensionMap::iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - iter->second.Clear(); + ForEach([](int /* number */, Extension& ext) { ext.Clear(); }); +} + +namespace { +// Computes the size of a std::set_union without constructing the union. +template <typename ItX, typename ItY> +size_t SizeOfUnion(ItX it_xs, ItX end_xs, ItY it_ys, ItY end_ys) { + size_t result = 0; + while (it_xs != end_xs && it_ys != end_ys) { + ++result; + if (it_xs->first < it_ys->first) { + ++it_xs; + } else if (it_xs->first == it_ys->first) { + ++it_xs; + ++it_ys; + } else { + ++it_ys; + } } + result += std::distance(it_xs, end_xs); + result += std::distance(it_ys, end_ys); + return result; } +} // namespace void ExtensionSet::MergeFrom(const ExtensionSet& other) { - for (ExtensionMap::const_iterator iter = other.extensions_.begin(); - iter != other.extensions_.end(); ++iter) { - const Extension& other_extension = iter->second; - InternalExtensionMergeFrom(iter->first, other_extension); + if (GOOGLE_PREDICT_TRUE(!is_large())) { + if (GOOGLE_PREDICT_TRUE(!other.is_large())) { + GrowCapacity(SizeOfUnion(flat_begin(), flat_end(), other.flat_begin(), + other.flat_end())); + } else { + GrowCapacity(SizeOfUnion(flat_begin(), flat_end(), + other.map_.large->begin(), + other.map_.large->end())); + } } + other.ForEach([this](int number, const Extension& ext) { + this->InternalExtensionMergeFrom(number, ext); + }); } void ExtensionSet::InternalExtensionMergeFrom( @@ -929,7 +956,7 @@ void ExtensionSet::InternalExtensionMergeFrom( for (int i = 0; i < other_repeated_message->size(); i++) { const MessageLite& other_message = other_repeated_message->Get(i); MessageLite* target = - reinterpret_cast< ::google::protobuf::internal::RepeatedPtrFieldBase*>( + reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>( extension->repeated_message_value) ->AddFromCleared<GenericTypeHandler<MessageLite> >(); if (target == NULL) { @@ -1020,7 +1047,10 @@ void ExtensionSet::InternalExtensionMergeFrom( void ExtensionSet::Swap(ExtensionSet* x) { if (GetArenaNoVirtual() == x->GetArenaNoVirtual()) { - extensions_.swap(x->extensions_); + using std::swap; + swap(flat_capacity_, x->flat_capacity_); + swap(flat_size_, x->flat_size_); + swap(map_, x->map_); } else { // TODO(cfallin, rohananil): We maybe able to optimize a case where we are // swapping from heap to arena-allocated extension set, by just Own()'ing @@ -1037,19 +1067,17 @@ void ExtensionSet::Swap(ExtensionSet* x) { void ExtensionSet::SwapExtension(ExtensionSet* other, int number) { if (this == other) return; - ExtensionMap::iterator this_iter = extensions_.find(number); - ExtensionMap::iterator other_iter = other->extensions_.find(number); + Extension* this_ext = FindOrNull(number); + Extension* other_ext = other->FindOrNull(number); - if (this_iter == extensions_.end() && - other_iter == other->extensions_.end()) { + if (this_ext == NULL && other_ext == NULL) { return; } - if (this_iter != extensions_.end() && - other_iter != other->extensions_.end()) { + if (this_ext != NULL && other_ext != NULL) { if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { using std::swap; - swap(this_iter->second, other_iter->second); + swap(*this_ext, *other_ext); } else { // TODO(cfallin, rohananil): We could further optimize these cases, // especially avoid creation of ExtensionSet, and move MergeFrom logic @@ -1057,33 +1085,33 @@ void ExtensionSet::SwapExtension(ExtensionSet* other, // We do it this way to reuse the copy-across-arenas logic already // implemented in ExtensionSet's MergeFrom. ExtensionSet temp; - temp.InternalExtensionMergeFrom(number, other_iter->second); - ExtensionMap::iterator temp_iter = temp.extensions_.find(number); - other_iter->second.Clear(); - other->InternalExtensionMergeFrom(number, this_iter->second); - this_iter->second.Clear(); - InternalExtensionMergeFrom(number, temp_iter->second); + temp.InternalExtensionMergeFrom(number, *other_ext); + Extension* temp_ext = temp.FindOrNull(number); + other_ext->Clear(); + other->InternalExtensionMergeFrom(number, *this_ext); + this_ext->Clear(); + InternalExtensionMergeFrom(number, *temp_ext); } return; } - if (this_iter == extensions_.end()) { + if (this_ext == NULL) { if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { - extensions_.insert(std::make_pair(number, other_iter->second)); + *Insert(number).first = *other_ext; } else { - InternalExtensionMergeFrom(number, other_iter->second); + InternalExtensionMergeFrom(number, *other_ext); } - other->extensions_.erase(number); + other->Erase(number); return; } - if (other_iter == other->extensions_.end()) { + if (other_ext == NULL) { if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { - other->extensions_.insert(std::make_pair(number, this_iter->second)); + *other->Insert(number).first = *this_ext; } else { - other->InternalExtensionMergeFrom(number, this_iter->second); + other->InternalExtensionMergeFrom(number, *this_ext); } - extensions_.erase(number); + Erase(number); return; } } @@ -1091,28 +1119,15 @@ void ExtensionSet::SwapExtension(ExtensionSet* other, bool ExtensionSet::IsInitialized() const { // Extensions are never required. However, we need to check that all // embedded messages are initialized. - for (ExtensionMap::const_iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - const Extension& extension = iter->second; - if (cpp_type(extension.type) == WireFormatLite::CPPTYPE_MESSAGE) { - if (extension.is_repeated) { - for (int i = 0; i < extension.repeated_message_value->size(); i++) { - if (!extension.repeated_message_value->Get(i).IsInitialized()) { - return false; - } - } - } else { - if (!extension.is_cleared) { - if (extension.is_lazy) { - if (!extension.lazymessage_value->IsInitialized()) return false; - } else { - if (!extension.message_value->IsInitialized()) return false; - } - } - } + if (GOOGLE_PREDICT_FALSE(is_large())) { + for (const auto& kv : *map_.large) { + if (!kv.second.IsInitialized()) return false; } + return true; + } + for (const KeyValue* it = flat_begin(); it != flat_end(); ++it) { + if (!it->second.IsInitialized()) return false; } - return true; } @@ -1351,22 +1366,27 @@ bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input, void ExtensionSet::SerializeWithCachedSizes( int start_field_number, int end_field_number, io::CodedOutputStream* output) const { - ExtensionMap::const_iterator iter; - for (iter = extensions_.lower_bound(start_field_number); - iter != extensions_.end() && iter->first < end_field_number; - ++iter) { - iter->second.SerializeFieldWithCachedSizes(iter->first, output); + if (GOOGLE_PREDICT_FALSE(is_large())) { + const auto& end = map_.large->end(); + for (auto it = map_.large->lower_bound(start_field_number); + it != end && it->first < end_field_number; ++it) { + it->second.SerializeFieldWithCachedSizes(it->first, output); + } + return; + } + const KeyValue* end = flat_end(); + for (const KeyValue* it = std::lower_bound( + flat_begin(), end, start_field_number, KeyValue::FirstComparator()); + it != end && it->first < end_field_number; ++it) { + it->second.SerializeFieldWithCachedSizes(it->first, output); } } size_t ExtensionSet::ByteSize() const { size_t total_size = 0; - - for (ExtensionMap::const_iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - total_size += iter->second.ByteSize(iter->first); - } - + ForEach([&total_size](int number, const Extension& ext) { + total_size += ext.ByteSize(number); + }); return total_size; } @@ -1376,11 +1396,10 @@ size_t ExtensionSet::ByteSize() const { bool ExtensionSet::MaybeNewExtension(int number, const FieldDescriptor* descriptor, Extension** result) { - std::pair<ExtensionMap::iterator, bool> insert_result = - extensions_.insert(std::make_pair(number, Extension())); - *result = &insert_result.first->second; + bool extension_is_new = false; + std::tie(*result, extension_is_new) = Insert(number); (*result)->descriptor = descriptor; - return insert_result.second; + return extension_is_new; } // =================================================================== @@ -1752,9 +1771,143 @@ void ExtensionSet::Extension::Free() { // Defined in extension_set_heavy.cc. // int ExtensionSet::Extension::SpaceUsedExcludingSelf() const +bool ExtensionSet::Extension::IsInitialized() const { + if (cpp_type(type) == WireFormatLite::CPPTYPE_MESSAGE) { + if (is_repeated) { + for (int i = 0; i < repeated_message_value->size(); i++) { + if (!repeated_message_value->Get(i).IsInitialized()) { + return false; + } + } + } else { + if (!is_cleared) { + if (is_lazy) { + if (!lazymessage_value->IsInitialized()) return false; + } else { + if (!message_value->IsInitialized()) return false; + } + } + } + } + return true; +} + // Dummy key method to avoid weak vtable. void ExtensionSet::LazyMessageExtension::UnusedKeyMethod() {} +const ExtensionSet::Extension* ExtensionSet::FindOrNull(int key) const { + if (GOOGLE_PREDICT_FALSE(is_large())) { + return FindOrNullInLargeMap(key); + } + const KeyValue* end = flat_end(); + const KeyValue* it = + std::lower_bound(flat_begin(), end, key, KeyValue::FirstComparator()); + if (it != end && it->first == key) { + return &it->second; + } + return NULL; +} + +const ExtensionSet::Extension* ExtensionSet::FindOrNullInLargeMap( + int key) const { + assert(is_large()); + LargeMap::const_iterator it = map_.large->find(key); + if (it != map_.large->end()) { + return &it->second; + } + return NULL; +} + +ExtensionSet::Extension* ExtensionSet::FindOrNull(int key) { + if (GOOGLE_PREDICT_FALSE(is_large())) { + return FindOrNullInLargeMap(key); + } + KeyValue* end = flat_end(); + KeyValue* it = + std::lower_bound(flat_begin(), end, key, KeyValue::FirstComparator()); + if (it != end && it->first == key) { + return &it->second; + } + return NULL; +} + +ExtensionSet::Extension* ExtensionSet::FindOrNullInLargeMap(int key) { + assert(is_large()); + LargeMap::iterator it = map_.large->find(key); + if (it != map_.large->end()) { + return &it->second; + } + return NULL; +} + +std::pair<ExtensionSet::Extension*, bool> ExtensionSet::Insert(int key) { + if (GOOGLE_PREDICT_FALSE(is_large())) { + auto maybe = map_.large->insert({key, Extension()}); + return {&maybe.first->second, maybe.second}; + } + KeyValue* end = flat_end(); + KeyValue* it = + std::lower_bound(flat_begin(), end, key, KeyValue::FirstComparator()); + if (it != end && it->first == key) { + return {&it->second, false}; + } + if (flat_size_ < flat_capacity_) { + std::copy_backward(it, end, end + 1); + ++flat_size_; + it->first = key; + it->second = Extension(); + return {&it->second, true}; + } + GrowCapacity(flat_size_ + 1); + return Insert(key); +} + +void ExtensionSet::GrowCapacity(size_t minimum_new_capacity) { + if (GOOGLE_PREDICT_FALSE(is_large())) { + return; // LargeMap does not have a "reserve" method. + } + if (flat_capacity_ >= minimum_new_capacity) { + return; + } + + do { + flat_capacity_ = flat_capacity_ == 0 ? 1 : flat_capacity_ * 4; + } while (flat_capacity_ < minimum_new_capacity); + + const KeyValue* begin = flat_begin(); + const KeyValue* end = flat_end(); + if (flat_capacity_ > kMaximumFlatCapacity) { + // Switch to LargeMap + map_.large = ::google::protobuf::Arena::Create<LargeMap>(arena_); + LargeMap::iterator hint = map_.large->begin(); + for (const KeyValue* it = begin; it != end; ++it) { + hint = map_.large->insert(hint, {it->first, it->second}); + } + flat_size_ = 0; + } else { + map_.flat = ::google::protobuf::Arena::CreateArray<KeyValue>(arena_, flat_capacity_); + std::copy(begin, end, map_.flat); + } + if (arena_ == NULL) delete[] begin; +} + +// static +constexpr uint16 ExtensionSet::kMaximumFlatCapacity; + +void ExtensionSet::Erase(int key) { + if (GOOGLE_PREDICT_FALSE(is_large())) { + map_.large->erase(key); + return; + } + KeyValue* end = flat_end(); + KeyValue* it = + std::lower_bound(flat_begin(), end, key, KeyValue::FirstComparator()); + if (it != end && it->first == key) { + std::copy(it + 1, end, it); + --flat_size_; + } +} + // ================================================================== // Default repeated field instances for iterator-compatible accessors diff --git a/src/google/protobuf/extension_set.h b/src/google/protobuf/extension_set.h index b0f3b8dd..c4796629 100644 --- a/src/google/protobuf/extension_set.h +++ b/src/google/protobuf/extension_set.h @@ -38,16 +38,16 @@ #ifndef GOOGLE_PROTOBUF_EXTENSION_SET_H__ #define GOOGLE_PROTOBUF_EXTENSION_SET_H__ -#include <vector> +#include <algorithm> +#include <cassert> #include <map> -#include <utility> #include <string> - +#include <utility> +#include <vector> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/once.h> - #include <google/protobuf/repeated_field.h> namespace google { @@ -464,7 +464,12 @@ class LIBPROTOBUF_EXPORT ExtensionSet { const MessageLite& prototype) = 0; virtual bool IsInitialized() const = 0; - virtual int ByteSize() const = 0; + + PROTOBUF_RUNTIME_DEPRECATED("Please use ByteSizeLong() instead") + virtual int ByteSize() const { + return internal::ToIntSize(ByteSizeLong()); + } + virtual size_t ByteSizeLong() const = 0; virtual size_t SpaceUsedLong() const = 0; virtual void MergeFrom(const LazyMessageExtension& other) = 0; @@ -567,9 +572,89 @@ class LIBPROTOBUF_EXPORT ExtensionSet { int GetSize() const; void Free(); size_t SpaceUsedExcludingSelfLong() const; + bool IsInitialized() const; }; - typedef std::map<int, Extension> ExtensionMap; + // The Extension struct is small enough to be passed by value, so we use it + // directly as the value type in mappings rather than use pointers. We use + // sorted maps rather than hash-maps because we expect most ExtensionSets will + // only contain a small number of extension. Also, we want AppendToList and + // deterministic serialization to order fields by field number. + + struct KeyValue { + int first; + Extension second; + + struct FirstComparator { + bool operator()(const KeyValue& lhs, const KeyValue& rhs) const { + return lhs.first < rhs.first; + } + bool operator()(const KeyValue& lhs, int key) const { + return lhs.first < key; + } + bool operator()(int key, const KeyValue& rhs) const { + return key < rhs.first; + } + }; + }; + + typedef std::map<int, Extension> LargeMap; + + // Wrapper API that switches between flat-map and LargeMap. + + // Finds a key (if present) in the ExtensionSet. + const Extension* FindOrNull(int key) const; + Extension* FindOrNull(int key); + + // Helper-functions that only inspect the LargeMap. + const Extension* FindOrNullInLargeMap(int key) const; + Extension* FindOrNullInLargeMap(int key); + + // Inserts a new (key, Extension) into the ExtensionSet (and returns true), or + // finds the already-existing Extension for that key (returns false). + // The Extension* will point to the new-or-found Extension. + std::pair<Extension*, bool> Insert(int key); + + // Grows the flat_capacity_. + // If flat_capacity_ > kMaximumFlatCapacity, converts to LargeMap. + void GrowCapacity(size_t minimum_new_capacity); + static constexpr uint16 kMaximumFlatCapacity = 256; + bool is_large() const { return flat_capacity_ > kMaximumFlatCapacity; } + + // Removes a key from the ExtensionSet. + void Erase(int key); + + size_t Size() const { + return GOOGLE_PREDICT_FALSE(is_large()) ? map_.large->size() : flat_size_; + } + + // Similar to std::for_each. + // Each Iterator is decomposed into ->first and ->second fields, so + // that the KeyValueFunctor can be agnostic vis-a-vis KeyValue-vs-std::pair. + template <typename Iterator, typename KeyValueFunctor> + static KeyValueFunctor ForEach(Iterator begin, Iterator end, + KeyValueFunctor func) { + for (Iterator it = begin; it != end; ++it) func(it->first, it->second); + return std::move(func); + } + + // Applies a functor to the <int, Extension&> pairs in sorted order. + template <typename KeyValueFunctor> + KeyValueFunctor ForEach(KeyValueFunctor func) { + if (GOOGLE_PREDICT_FALSE(is_large())) { + return ForEach(map_.large->begin(), map_.large->end(), std::move(func)); + } + return ForEach(flat_begin(), flat_end(), std::move(func)); + } + + // Applies a functor to the <int, const Extension&> pairs in sorted order. + template <typename KeyValueFunctor> + KeyValueFunctor ForEach(KeyValueFunctor func) const { + if (GOOGLE_PREDICT_FALSE(is_large())) { + return ForEach(map_.large->begin(), map_.large->end(), std::move(func)); + } + return ForEach(flat_begin(), flat_end(), std::move(func)); + } // Merges existing Extension from other_extension void InternalExtensionMergeFrom(int number, const Extension& other_extension); @@ -633,14 +718,38 @@ class LIBPROTOBUF_EXPORT ExtensionSet { static inline size_t RepeatedMessage_SpaceUsedExcludingSelfLong( RepeatedPtrFieldBase* field); - // The Extension struct is small enough to be passed by value, so we use it - // directly as the value type in the map rather than use pointers. We use - // a map rather than hash_map here because we expect most ExtensionSets will - // only contain a small number of extensions whereas hash_map is optimized - // for 100 elements or more. Also, we want AppendToList() to order fields - // by field number. - ExtensionMap extensions_; + KeyValue* flat_begin() { + assert(!is_large()); + return map_.flat; + } + const KeyValue* flat_begin() const { + assert(!is_large()); + return map_.flat; + } + KeyValue* flat_end() { + assert(!is_large()); + return map_.flat + flat_size_; + } + const KeyValue* flat_end() const { + assert(!is_large()); + return map_.flat + flat_size_; + } + ::google::protobuf::Arena* arena_; + + // Manual memory-management: + // map_.flat is an allocated array of flat_capacity_ elements. + // [map_.flat, map_.flat + flat_size_) is the currently-in-use prefix. + uint16 flat_capacity_; + uint16 flat_size_; + union AllocatedData { + KeyValue* flat; + + // If flat_capacity_ > kMaximumFlatCapacity, switch to LargeMap, + // which guarantees O(n lg n) CPU but larger constant factors. + LargeMap* large; + } map_; + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionSet); }; @@ -1127,7 +1236,7 @@ LIBPROTOBUF_EXPORT extern ProtobufOnceType repeated_message_generic_type_traits_ // message-type repeated field extensions. class LIBPROTOBUF_EXPORT RepeatedMessageGenericTypeTraits { public: - typedef RepeatedPtrField< ::google::protobuf::MessageLite*> RepeatedFieldType; + typedef RepeatedPtrField<::google::protobuf::MessageLite*> RepeatedFieldType; private: template<typename Type> friend class RepeatedMessageTypeTraits; static void InitializeDefaultRepeatedFields(); diff --git a/src/google/protobuf/extension_set_heavy.cc b/src/google/protobuf/extension_set_heavy.cc index 432c0fd7..a3c84167 100644 --- a/src/google/protobuf/extension_set_heavy.cc +++ b/src/google/protobuf/extension_set_heavy.cc @@ -35,9 +35,10 @@ // Contains methods defined in extension_set.h which cannot be part of the // lite library because they use descriptors or reflection. +#include <google/protobuf/stubs/casts.h> +#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> -#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/message.h> @@ -95,16 +96,14 @@ class DescriptorPoolExtensionFinder : public ExtensionFinder { }; void ExtensionSet::AppendToList( - const Descriptor* containing_type, - const DescriptorPool* pool, + const Descriptor* containing_type, const DescriptorPool* pool, std::vector<const FieldDescriptor*>* output) const { - for (ExtensionMap::const_iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { + ForEach([containing_type, pool, &output](int number, const Extension& ext) { bool has = false; - if (iter->second.is_repeated) { - has = iter->second.GetSize() > 0; + if (ext.is_repeated) { + has = ext.GetSize() > 0; } else { - has = !iter->second.is_cleared; + has = !ext.is_cleared; } if (has) { @@ -113,14 +112,13 @@ void ExtensionSet::AppendToList( // initialized, so they might not even be constructed until // AppendToList() is called. - if (iter->second.descriptor == NULL) { - output->push_back(pool->FindExtensionByNumber( - containing_type, iter->first)); + if (ext.descriptor == NULL) { + output->push_back(pool->FindExtensionByNumber(containing_type, number)); } else { - output->push_back(iter->second.descriptor); + output->push_back(ext.descriptor); } } - } + }); } inline FieldDescriptor::Type real_type(FieldType type) { @@ -147,17 +145,17 @@ inline WireFormatLite::FieldType field_type(FieldType type) { const MessageLite& ExtensionSet::GetMessage(int number, const Descriptor* message_type, MessageFactory* factory) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end() || iter->second.is_cleared) { + const Extension* extension = FindOrNull(number); + if (extension == NULL || extension->is_cleared) { // Not present. Return the default value. return *factory->GetPrototype(message_type); } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE); - if (iter->second.is_lazy) { - return iter->second.lazymessage_value->GetMessage( + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); + if (extension->is_lazy) { + return extension->lazymessage_value->GetMessage( *factory->GetPrototype(message_type)); } else { - return *iter->second.message_value; + return *extension->message_value; } } } @@ -190,51 +188,51 @@ MessageLite* ExtensionSet::MutableMessage(const FieldDescriptor* descriptor, MessageLite* ExtensionSet::ReleaseMessage(const FieldDescriptor* descriptor, MessageFactory* factory) { - ExtensionMap::iterator iter = extensions_.find(descriptor->number()); - if (iter == extensions_.end()) { + Extension* extension = FindOrNull(descriptor->number()); + if (extension == NULL) { // Not present. Return NULL. return NULL; } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); MessageLite* ret = NULL; - if (iter->second.is_lazy) { - ret = iter->second.lazymessage_value->ReleaseMessage( + if (extension->is_lazy) { + ret = extension->lazymessage_value->ReleaseMessage( *factory->GetPrototype(descriptor->message_type())); if (arena_ == NULL) { - delete iter->second.lazymessage_value; + delete extension->lazymessage_value; } } else { if (arena_ != NULL) { - ret = (iter->second.message_value)->New(); - ret->CheckTypeAndMergeFrom(*(iter->second.message_value)); + ret = extension->message_value->New(); + ret->CheckTypeAndMergeFrom(*extension->message_value); } else { - ret = iter->second.message_value; + ret = extension->message_value; } } - extensions_.erase(descriptor->number()); + Erase(descriptor->number()); return ret; } } MessageLite* ExtensionSet::UnsafeArenaReleaseMessage( const FieldDescriptor* descriptor, MessageFactory* factory) { - ExtensionMap::iterator iter = extensions_.find(descriptor->number()); - if (iter == extensions_.end()) { + Extension* extension = FindOrNull(descriptor->number()); + if (extension == NULL) { // Not present. Return NULL. return NULL; } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); MessageLite* ret = NULL; - if (iter->second.is_lazy) { - ret = iter->second.lazymessage_value->UnsafeArenaReleaseMessage( + if (extension->is_lazy) { + ret = extension->lazymessage_value->UnsafeArenaReleaseMessage( *factory->GetPrototype(descriptor->message_type())); if (arena_ == NULL) { - delete iter->second.lazymessage_value; + delete extension->lazymessage_value; } } else { - ret = iter->second.message_value; + ret = extension->message_value; } - extensions_.erase(descriptor->number()); + Erase(descriptor->number()); return ret; } } @@ -260,7 +258,7 @@ MessageLite* ExtensionSet::AddMessage(const FieldDescriptor* descriptor, // RepeatedPtrField<Message> does not know how to Add() since it cannot // allocate an abstract object, so we have to be tricky. MessageLite* result = - reinterpret_cast< ::google::protobuf::internal::RepeatedPtrFieldBase*>( + reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>( extension->repeated_message_value) ->AddFromCleared<GenericTypeHandler<MessageLite> >(); if (result == NULL) { @@ -349,14 +347,10 @@ int ExtensionSet::SpaceUsedExcludingSelf() const { } size_t ExtensionSet::SpaceUsedExcludingSelfLong() const { - size_t total_size = - extensions_.size() * sizeof(ExtensionMap::value_type); - for (ExtensionMap::const_iterator iter = extensions_.begin(), - end = extensions_.end(); - iter != end; - ++iter) { - total_size += iter->second.SpaceUsedExcludingSelfLong(); - } + size_t total_size = Size() * sizeof(KeyValue); + ForEach([&total_size](int /* number */, const Extension& ext) { + total_size += ext.SpaceUsedExcludingSelfLong(); + }); return total_size; } @@ -394,7 +388,7 @@ size_t ExtensionSet::Extension::SpaceUsedExcludingSelfLong() const { total_size += sizeof(*repeated_message_value) + RepeatedMessage_SpaceUsedExcludingSelfLong( - reinterpret_cast< ::google::protobuf::internal::RepeatedPtrFieldBase*>( + reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>( repeated_message_value)); break; } @@ -438,25 +432,33 @@ uint8* ExtensionSet::SerializeMessageSetWithCachedSizesToArray( } uint8* ExtensionSet::InternalSerializeWithCachedSizesToArray( - int start_field_number, int end_field_number, - bool deterministic, uint8* target) const { - ExtensionMap::const_iterator iter; - for (iter = extensions_.lower_bound(start_field_number); - iter != extensions_.end() && iter->first < end_field_number; - ++iter) { - target = iter->second.InternalSerializeFieldWithCachedSizesToArray( - iter->first, deterministic, target); + int start_field_number, int end_field_number, bool deterministic, + uint8* target) const { + if (GOOGLE_PREDICT_FALSE(is_large())) { + const auto& end = map_.large->end(); + for (auto it = map_.large->lower_bound(start_field_number); + it != end && it->first < end_field_number; ++it) { + target = it->second.InternalSerializeFieldWithCachedSizesToArray( + it->first, deterministic, target); + } + return target; + } + const KeyValue* end = flat_end(); + for (const KeyValue* it = std::lower_bound( + flat_begin(), end, start_field_number, KeyValue::FirstComparator()); + it != end && it->first < end_field_number; ++it) { + target = it->second.InternalSerializeFieldWithCachedSizesToArray( + it->first, deterministic, target); } return target; } uint8* ExtensionSet::InternalSerializeMessageSetWithCachedSizesToArray( bool deterministic, uint8* target) const { - ExtensionMap::const_iterator iter; - for (iter = extensions_.begin(); iter != extensions_.end(); ++iter) { - target = iter->second.InternalSerializeMessageSetItemWithCachedSizesToArray( - iter->first, deterministic, target); - } + ForEach([deterministic, &target](int number, const Extension& ext) { + target = ext.InternalSerializeMessageSetItemWithCachedSizesToArray( + number, deterministic, target); + }); return target; } @@ -783,9 +785,9 @@ size_t ExtensionSet::Extension::MessageSetItemByteSize(int number) const { // message size_t message_size = 0; if (is_lazy) { - message_size = lazymessage_value->ByteSize(); + message_size = lazymessage_value->ByteSizeLong(); } else { - message_size = message_value->ByteSize(); + message_size = message_value->ByteSizeLong(); } our_size += io::CodedOutputStream::VarintSize32(message_size); @@ -796,20 +798,16 @@ size_t ExtensionSet::Extension::MessageSetItemByteSize(int number) const { void ExtensionSet::SerializeMessageSetWithCachedSizes( io::CodedOutputStream* output) const { - for (ExtensionMap::const_iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - iter->second.SerializeMessageSetItemWithCachedSizes(iter->first, output); - } + ForEach([output](int number, const Extension& ext) { + ext.SerializeMessageSetItemWithCachedSizes(number, output); + }); } size_t ExtensionSet::MessageSetByteSize() const { size_t total_size = 0; - - for (ExtensionMap::const_iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - total_size += iter->second.MessageSetItemByteSize(iter->first); - } - + ForEach([&total_size](int number, const Extension& ext) { + total_size += ext.MessageSetItemByteSize(number); + }); return total_size; } diff --git a/src/google/protobuf/extension_set_unittest.cc b/src/google/protobuf/extension_set_unittest.cc index b8b6e428..bc65d295 100644 --- a/src/google/protobuf/extension_set_unittest.cc +++ b/src/google/protobuf/extension_set_unittest.cc @@ -32,19 +32,20 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. +#include <google/protobuf/stubs/casts.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/extension_set.h> +#include <google/protobuf/test_util.h> #include <google/protobuf/unittest.pb.h> #include <google/protobuf/unittest_mset.pb.h> -#include <google/protobuf/test_util.h> +#include <google/protobuf/io/coded_stream.h> +#include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/arena.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/dynamic_message.h> +#include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format.h> -#include <google/protobuf/io/coded_stream.h> -#include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> @@ -285,7 +286,7 @@ TEST(ExtensionSetTest, CopyFrom) { TestUtil::ExpectAllExtensionsSet(message2); } -TEST(ExtensioSetTest, CopyFromPacked) { +TEST(ExtensionSetTest, CopyFromPacked) { unittest::TestPackedExtensions message1, message2; TestUtil::SetPackedExtensions(&message1); @@ -444,7 +445,7 @@ TEST(ExtensionSetTest, ArenaSetAllocatedMessageAndRelease) { TEST(ExtensionSetTest, SwapExtensionBothFullWithArena) { ::google::protobuf::Arena arena1; - google::protobuf::scoped_ptr<google::protobuf::Arena> arena2(new ::google::protobuf::Arena()); + std::unique_ptr<google::protobuf::Arena> arena2(new ::google::protobuf::Arena()); unittest::TestAllExtensions* message1 = Arena::CreateMessage<unittest::TestAllExtensions>(&arena1); @@ -601,6 +602,26 @@ TEST(ExtensionSetTest, PackedSerializationToStream) { TestUtil::ExpectPackedFieldsSet(destination); } +TEST(ExtensionSetTest, NestedExtensionGroup) { + // Serialize as TestGroup and parse as TestGroupExtension. + unittest::TestGroup source; + unittest::TestGroupExtension destination; + string data; + + source.mutable_optionalgroup()->set_a(117); + source.set_optional_foreign_enum(unittest::FOREIGN_BAZ); + source.SerializeToString(&data); + EXPECT_TRUE(destination.ParseFromString(data)); + EXPECT_TRUE(destination.GetExtension( + unittest::TestNestedExtension::optionalgroup_extension).has_a()); + EXPECT_EQ(117, destination.GetExtension( + unittest::TestNestedExtension::optionalgroup_extension).a()); + EXPECT_TRUE(destination.HasExtension( + unittest::TestNestedExtension::optional_foreign_enum_extension)); + EXPECT_EQ(unittest::FOREIGN_BAZ, destination.GetExtension( + unittest::TestNestedExtension::optional_foreign_enum_extension)); +} + TEST(ExtensionSetTest, Parsing) { // Serialize as TestAllTypes and parse as TestAllExtensions. unittest::TestAllTypes source; @@ -998,8 +1019,8 @@ TEST(ExtensionSetTest, RepeatedFields) { ASSERT_EQ(110, SumAllExtensions<double>( message, unittest::repeated_double_extension, 0)); - RepeatedPtrField< ::std::string>::iterator string_iter; - RepeatedPtrField< ::std::string>::iterator string_end; + RepeatedPtrField<::std::string>::iterator string_iter; + RepeatedPtrField<::std::string>::iterator string_end; for (string_iter = message.MutableRepeatedExtension( unittest::repeated_string_extension)->begin(), string_end = message.MutableRepeatedExtension( @@ -1007,8 +1028,8 @@ TEST(ExtensionSetTest, RepeatedFields) { string_iter != string_end; ++string_iter) { *string_iter += "test"; } - RepeatedPtrField< ::std::string>::const_iterator string_const_iter; - RepeatedPtrField< ::std::string>::const_iterator string_const_end; + RepeatedPtrField<::std::string>::const_iterator string_const_iter; + RepeatedPtrField<::std::string>::const_iterator string_const_end; for (string_const_iter = message.GetRepeatedExtension( unittest::repeated_string_extension).begin(), string_const_end = message.GetRepeatedExtension( diff --git a/src/google/protobuf/field_mask.pb.cc b/src/google/protobuf/field_mask.pb.cc index abee4fe7..2ce061d9 100644 --- a/src/google/protobuf/field_mask.pb.cc +++ b/src/google/protobuf/field_mask.pb.cc @@ -7,7 +7,6 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> -#include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> @@ -19,6 +18,7 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + namespace google { namespace protobuf { class FieldMaskDefaultTypeInternal { @@ -29,14 +29,9 @@ class FieldMaskDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto { -void InitDefaultsFieldMaskImpl() { +static void InitDefaultsFieldMask() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_FieldMask_default_instance_; new (ptr) ::google::protobuf::FieldMask(); @@ -45,9 +40,11 @@ void InitDefaultsFieldMaskImpl() { ::google::protobuf::FieldMask::InitAsDefaultInstance(); } -void InitDefaultsFieldMask() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFieldMaskImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_FieldMask = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsFieldMask}, {}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_FieldMask.base); } ::google::protobuf::Metadata file_level_metadata[1]; @@ -68,17 +65,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_FieldMask_default_instance_), }; -void protobuf_AssignDescriptors() { +static void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/field_mask.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/field_mask.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } -void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); +static void protobuf_AssignDescriptorsOnce() { + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -87,7 +83,7 @@ void protobuf_RegisterTypes(const ::std::string&) { ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1); } -void AddDescriptorsImpl() { +static void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n google/protobuf/field_mask.proto\022\017goog" @@ -104,8 +100,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -127,23 +123,20 @@ const int FieldMask::kPathsFieldNumber; FieldMask::FieldMask() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::InitDefaultsFieldMask(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::scc_info_FieldMask.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FieldMask) } FieldMask::FieldMask(const FieldMask& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - paths_(from.paths_), - _cached_size_(0) { + paths_(from.paths_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.FieldMask) } void FieldMask::SharedCtor() { - _cached_size_ = 0; } FieldMask::~FieldMask() { @@ -155,9 +148,7 @@ void FieldMask::SharedDtor() { } void FieldMask::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* FieldMask::descriptor() { ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::protobuf_AssignDescriptorsOnce(); @@ -165,7 +156,7 @@ const ::google::protobuf::Descriptor* FieldMask::descriptor() { } const FieldMask& FieldMask::default_instance() { - ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::InitDefaultsFieldMask(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::scc_info_FieldMask.base); return *internal_default_instance(); } @@ -186,7 +177,7 @@ bool FieldMask::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FieldMask) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -293,9 +284,7 @@ size_t FieldMask::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -350,7 +339,6 @@ void FieldMask::InternalSwap(FieldMask* other) { using std::swap; paths_.InternalSwap(CastToBase(&other->paths_)); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata FieldMask::GetMetadata() const { @@ -364,7 +352,7 @@ void FieldMask::InternalSwap(FieldMask* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldMask* Arena::Create< ::google::protobuf::FieldMask >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldMask* Arena::CreateMaybeMessage< ::google::protobuf::FieldMask >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::FieldMask >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/field_mask.pb.h b/src/google/protobuf/field_mask.pb.h index 2d75967e..144b41fa 100644 --- a/src/google/protobuf/field_mask.pb.h +++ b/src/google/protobuf/field_mask.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/field_mask.proto -#ifndef PROTOBUF_google_2fprotobuf_2ffield_5fmask_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2ffield_5fmask_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto #include <string> @@ -24,12 +24,14 @@ #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> +#include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ffield_5fmask_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto { // Internal implementation detail -- do not use these members. @@ -42,11 +44,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsFieldMaskImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsFieldMask(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsFieldMask(); -} } // namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto namespace google { namespace protobuf { @@ -57,7 +54,7 @@ LIBPROTOBUF_EXPORT extern FieldMaskDefaultTypeInternal _FieldMask_default_instan } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldMask* Arena::Create< ::google::protobuf::FieldMask>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldMask* Arena::CreateMaybeMessage<::google::protobuf::FieldMask>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -99,7 +96,7 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro return reinterpret_cast<const FieldMask*>( &_FieldMask_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void Swap(FieldMask* other); @@ -109,32 +106,33 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro // implements Message ---------------------------------------------- - inline FieldMask* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<FieldMask>(NULL); + inline FieldMask* New() const final { + return CreateMaybeMessage<FieldMask>(NULL); } - FieldMask* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<FieldMask>(arena); + FieldMask* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<FieldMask>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const FieldMask& from); void MergeFrom(const FieldMask& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(FieldMask* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -145,7 +143,7 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -178,9 +176,8 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::RepeatedPtrField< ::std::string> paths_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::InitDefaultsFieldMaskImpl(); }; // =================================================================== @@ -273,4 +270,4 @@ FieldMask::mutable_paths() { // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2ffield_5fmask_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto diff --git a/src/google/protobuf/field_mask.proto b/src/google/protobuf/field_mask.proto index eb96ba00..76e09f39 100644 --- a/src/google/protobuf/field_mask.proto +++ b/src/google/protobuf/field_mask.proto @@ -243,8 +243,8 @@ option go_package = "google.golang.org/genproto/protobuf/field_mask;field_mask"; // // ## Field Mask Verification // -// The implementation of the all the API methods, which have any FieldMask type -// field in the request, should verify the included field paths, and return +// The implementation of any API method which has a FieldMask type field in the +// request should verify the included field paths, and return an // `INVALID_ARGUMENT` error if any path is duplicated or unmappable. message FieldMask { // The set of field mask paths. diff --git a/src/google/protobuf/generated_enum_util.h b/src/google/protobuf/generated_enum_util.h index 4f5ded5b..96b03cc9 100644 --- a/src/google/protobuf/generated_enum_util.h +++ b/src/google/protobuf/generated_enum_util.h @@ -31,14 +31,14 @@ #ifndef GOOGLE_PROTOBUF_GENERATED_ENUM_UTIL_H__ #define GOOGLE_PROTOBUF_GENERATED_ENUM_UTIL_H__ -#include <google/protobuf/stubs/type_traits.h> +#include <type_traits> namespace google { namespace protobuf { // This type trait can be used to cause templates to only match proto2 enum // types. -template <typename T> struct is_proto_enum : ::google::protobuf::internal::false_type {}; +template <typename T> struct is_proto_enum : ::std::false_type {}; } // namespace protobuf diff --git a/src/google/protobuf/generated_message_reflection.cc b/src/google/protobuf/generated_message_reflection.cc index b0c975b4..247f772c 100644 --- a/src/google/protobuf/generated_message_reflection.cc +++ b/src/google/protobuf/generated_message_reflection.cc @@ -42,6 +42,7 @@ #include <google/protobuf/extension_set.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/generated_message_util.h> +#include <google/protobuf/inlined_string_field.h> #include <google/protobuf/map_field.h> #include <google/protobuf/repeated_field.h> #include <google/protobuf/wire_format.h> @@ -290,6 +291,13 @@ size_t GeneratedMessageReflection::SpaceUsedLong(const Message& message) const { switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: { + if (IsInlined(field)) { + const string* ptr = + &GetField<InlinedStringField>(message, field).GetNoArena(); + total_size += StringSpaceUsedExcludingSelfLong(*ptr); + break; + } + // Initially, the string points to the default value stored in // the prototype. Only count the string if it has been changed // from the default value. @@ -424,15 +432,25 @@ void GeneratedMessageReflection::SwapField( { Arena* arena1 = GetArena(message1); Arena* arena2 = GetArena(message2); + + if (IsInlined(field)) { + InlinedStringField* string1 = + MutableRaw<InlinedStringField>(message1, field); + InlinedStringField* string2 = + MutableRaw<InlinedStringField>(message2, field); + string1->Swap(string2); + break; + } + ArenaStringPtr* string1 = MutableRaw<ArenaStringPtr>(message1, field); ArenaStringPtr* string2 = MutableRaw<ArenaStringPtr>(message2, field); + const string* default_ptr = + &DefaultRaw<ArenaStringPtr>(field).Get(); if (arena1 == arena2) { - string1->Swap(string2); + string1->Swap(string2, default_ptr, arena1); } else { - const string* default_ptr = - &DefaultRaw<ArenaStringPtr>(field).Get(); const string temp = string1->Get(); string1->Set(default_ptr, string2->Get(), arena1); string2->Set(default_ptr, temp, arena2); @@ -738,7 +756,15 @@ int GeneratedMessageReflection::FieldSize(const Message& message, case FieldDescriptor::CPPTYPE_STRING: case FieldDescriptor::CPPTYPE_MESSAGE: if (IsMapFieldInApi(field)) { - return GetRaw<MapFieldBase>(message, field).GetRepeatedField().size(); + const internal::MapFieldBase& map = + GetRaw<MapFieldBase>(message, field); + if (map.IsRepeatedFieldValid()) { + return map.GetRepeatedField().size(); + } else { + // No need to materialize the repeated field if it is out of sync: + // its size will be the same as the map's size. + return map.size(); + } } else { return GetRaw<RepeatedPtrFieldBase>(message, field).size(); } @@ -789,6 +815,14 @@ void GeneratedMessageReflection::ClearField( switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: { + if (IsInlined(field)) { + const string* default_ptr = + &DefaultRaw<InlinedStringField>(field).GetNoArena(); + MutableRaw<InlinedStringField>(message, field)->SetNoArena( + default_ptr, *default_ptr); + break; + } + const string* default_ptr = &DefaultRaw<ArenaStringPtr>(field).Get(); MutableRaw<ArenaStringPtr>(message, field)->SetAllocated( @@ -1121,6 +1155,10 @@ string GeneratedMessageReflection::GetString( switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: { + if (IsInlined(field)) { + return GetField<InlinedStringField>(message, field).GetNoArena(); + } + return GetField<ArenaStringPtr>(message, field).Get(); } } @@ -1138,6 +1176,10 @@ const string& GeneratedMessageReflection::GetStringReference( switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: { + if (IsInlined(field)) { + return GetField<InlinedStringField>(message, field).GetNoArena(); + } + return GetField<ArenaStringPtr>(message, field).Get(); } } @@ -1156,6 +1198,12 @@ void GeneratedMessageReflection::SetString( switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: { + if (IsInlined(field)) { + MutableField<InlinedStringField>(message, field)->SetNoArena( + NULL, value); + break; + } + const string* default_ptr = &DefaultRaw<ArenaStringPtr>(field).Get(); if (field->containing_oneof() && !HasOneofField(*message, field)) { ClearOneof(message, field->containing_oneof()); @@ -1868,6 +1916,10 @@ const Type& GeneratedMessageReflection::GetRaw( return GetConstRefAtOffset<Type>(message, schema_.GetFieldOffset(field)); } +bool GeneratedMessageReflection::IsInlined(const FieldDescriptor* field) const { + return schema_.IsFieldInlined(field); +} + template <typename Type> Type* GeneratedMessageReflection::MutableRaw(Message* message, const FieldDescriptor* field) const { @@ -1963,6 +2015,10 @@ inline bool GeneratedMessageReflection::HasBit( case FieldDescriptor::CPPTYPE_STRING: switch (field->options().ctype()) { default: { + if (IsInlined(field)) { + return !GetField<InlinedStringField>(message, field) + .GetNoArena().empty(); + } return GetField<ArenaStringPtr>(message, field).Get().size() > 0; } } @@ -2307,7 +2363,6 @@ struct MetadataOwner { void AssignDescriptors( const string& filename, const MigrationSchema* schemas, const Message* const* default_instances_, const uint32* offsets, - MessageFactory* factory, // update the following descriptor arrays. Metadata* file_level_metadata, const EnumDescriptor** file_level_enum_descriptors, @@ -2316,7 +2371,7 @@ void AssignDescriptors( ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(filename); GOOGLE_CHECK(file != NULL); - if (!factory) factory = MessageFactory::generated_factory(); + MessageFactory* factory = MessageFactory::generated_factory(); AssignDescriptorsHelper<MigrationSchema> helper(factory, file_level_metadata, file_level_enum_descriptors, schemas, diff --git a/src/google/protobuf/generated_message_reflection.h b/src/google/protobuf/generated_message_reflection.h index 3c6701cf..31f249b6 100644 --- a/src/google/protobuf/generated_message_reflection.h +++ b/src/google/protobuf/generated_message_reflection.h @@ -94,7 +94,7 @@ class WeakFieldMap; // weak_field_map.h // For each oneof or weak field, the offset is relative to the // default_instance. These can be computed at compile time // using the -// GOOGLE_PROTOBUF_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET() +// PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET() // macro. For each none oneof field, the offset is related to // the start of the message object. These can be computed at // compile time using the @@ -134,7 +134,7 @@ struct ReflectionSchema { // efficient when we know statically that it is not a oneof field. uint32 GetFieldOffsetNonOneof(const FieldDescriptor* field) const { GOOGLE_DCHECK(!field->containing_oneof()); - return offsets_[field->index()]; + return OffsetValue(offsets_[field->index()], field->type()); } // Offset of any field. @@ -143,12 +143,23 @@ struct ReflectionSchema { size_t offset = static_cast<size_t>(field->containing_type()->field_count() + field->containing_oneof()->index()); - return offsets_[offset]; + return OffsetValue(offsets_[offset], field->type()); } else { return GetFieldOffsetNonOneof(field); } } + bool IsFieldInlined(const FieldDescriptor* field) const { + if (field->containing_oneof()) { + size_t offset = + static_cast<size_t>(field->containing_type()->field_count() + + field->containing_oneof()->index()); + return Inlined(offsets_[offset], field->type()); + } else { + return Inlined(offsets_[field->index()], field->type()); + } + } + uint32 GetOneofCaseOffset(const OneofDescriptor* oneof_descriptor) const { return static_cast<uint32>(oneof_case_offset_) + static_cast<uint32>( @@ -198,7 +209,7 @@ struct ReflectionSchema { // of the underlying data depends on the field's type. const void *GetFieldDefault(const FieldDescriptor* field) const { return reinterpret_cast<const uint8*>(default_instance_) + - offsets_[field->index()]; + OffsetValue(offsets_[field->index()], field->type()); } @@ -219,6 +230,27 @@ struct ReflectionSchema { int oneof_case_offset_; int object_size_; int weak_field_map_offset_; + + // We tag offset values to provide additional data about fields (such as + // inlined). + static uint32 OffsetValue(uint32 v, FieldDescriptor::Type type) { + if (type == FieldDescriptor::TYPE_STRING || + type == FieldDescriptor::TYPE_BYTES) { + return v & ~1u; + } else { + return v; + } + } + + static bool Inlined(uint32 v, FieldDescriptor::Type type) { + if (type == FieldDescriptor::TYPE_STRING || + type == FieldDescriptor::TYPE_BYTES) { + return v & 1u; + } else { + // Non string/byte fields are not inlined. + return false; + } + } }; // Structs that the code generator emits directly to describe a message. @@ -257,7 +289,7 @@ struct MigrationSchema { // of whatever type the individual field would be. Strings and // Messages use RepeatedPtrFields while everything else uses // RepeatedFields. -class LIBPROTOBUF_EXPORT GeneratedMessageReflection PROTOBUF_FINAL : public Reflection { +class GeneratedMessageReflection final : public Reflection { public: // Constructs a GeneratedMessageReflection. // Parameters: @@ -543,6 +575,8 @@ class LIBPROTOBUF_EXPORT GeneratedMessageReflection PROTOBUF_FINAL : public Refl inline InternalMetadataWithArena* MutableInternalMetadataWithArena(Message* message) const; + inline bool IsInlined(const FieldDescriptor* field) const; + inline bool HasBit(const Message& message, const FieldDescriptor* field) const; inline void SetBit(Message* message, @@ -704,7 +738,6 @@ T* DynamicCastToGenerated(Message* from) { LIBPROTOBUF_EXPORT void AssignDescriptors( const string& filename, const MigrationSchema* schemas, const Message* const* default_instances_, const uint32* offsets, - MessageFactory* factory, // update the following descriptor arrays. Metadata* file_level_metadata, const EnumDescriptor** file_level_enum_descriptors, diff --git a/src/google/protobuf/generated_message_reflection_unittest.cc b/src/google/protobuf/generated_message_reflection_unittest.cc index 242cc4a1..61eb6603 100644 --- a/src/google/protobuf/generated_message_reflection_unittest.cc +++ b/src/google/protobuf/generated_message_reflection_unittest.cc @@ -44,9 +44,6 @@ #include <google/protobuf/generated_message_reflection.h> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/test_util.h> #include <google/protobuf/unittest.pb.h> @@ -360,7 +357,7 @@ TEST(GeneratedMessageReflectionTest, ReleaseLast) { ASSERT_EQ(2, message.repeated_foreign_message_size()); const protobuf_unittest::ForeignMessage* expected = message.mutable_repeated_foreign_message(1); - google::protobuf::scoped_ptr<Message> released(message.GetReflection()->ReleaseLast( + std::unique_ptr<Message> released(message.GetReflection()->ReleaseLast( &message, descriptor->FindFieldByName("repeated_foreign_message"))); EXPECT_EQ(expected, released.get()); } @@ -383,7 +380,7 @@ TEST(GeneratedMessageReflectionTest, ReleaseLastExtensions) { unittest::repeated_foreign_message_extension)); const protobuf_unittest::ForeignMessage* expected = message.MutableExtension( unittest::repeated_foreign_message_extension, 1); - google::protobuf::scoped_ptr<Message> released(message.GetReflection()->ReleaseLast( + std::unique_ptr<Message> released(message.GetReflection()->ReleaseLast( &message, descriptor->file()->FindExtensionByName( "repeated_foreign_message_extension"))); EXPECT_EQ(expected, released.get()); @@ -746,6 +743,10 @@ TEST(GeneratedMessageReflectionTest, Oneof) { "change_spiece"); EXPECT_EQ("change_spiece", reflection->GetString( message, descriptor->FindFieldByName("bar_string_piece"))); + + message.clear_foo(); + message.clear_bar(); + TestUtil::ExpectOneofClear(message); } TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageTest) { diff --git a/src/google/protobuf/generated_message_table_driven.cc b/src/google/protobuf/generated_message_table_driven.cc index 29af1ef6..d4450a6c 100644 --- a/src/google/protobuf/generated_message_table_driven.cc +++ b/src/google/protobuf/generated_message_table_driven.cc @@ -30,8 +30,9 @@ #include <google/protobuf/generated_message_table_driven.h> -#include <google/protobuf/stubs/type_traits.h> +#include <type_traits> +#include <google/protobuf/stubs/casts.h> #include <google/protobuf/generated_message_table_driven_lite.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> #include <google/protobuf/metadata.h> diff --git a/src/google/protobuf/generated_message_table_driven.h b/src/google/protobuf/generated_message_table_driven.h index 6f3fe666..10ca3aaa 100644 --- a/src/google/protobuf/generated_message_table_driven.h +++ b/src/google/protobuf/generated_message_table_driven.h @@ -38,9 +38,6 @@ #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/wire_format_lite_inl.h> -#if LANG_CXX11 -#define PROTOBUF_CONSTEXPR constexpr - // We require C++11 and Clang to use constexpr for variables, as GCC 4.8 // requires constexpr to be consistent between declarations of variables // unnecessarily (see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58541). @@ -51,37 +48,28 @@ #define PROTOBUF_CONSTEXPR_VAR #endif // !_clang -#else -#define PROTOBUF_CONSTEXPR -#define PROTOBUF_CONSTEXPR_VAR -#endif - namespace google { namespace protobuf { namespace internal { // Processing-type masks. -static PROTOBUF_CONSTEXPR const unsigned char kOneofMask = 0x40; -static PROTOBUF_CONSTEXPR const unsigned char kRepeatedMask = 0x20; +static constexpr const unsigned char kOneofMask = 0x40; +static constexpr const unsigned char kRepeatedMask = 0x20; // Mask for the raw type: either a WireFormatLite::FieldType or one of the // ProcessingTypes below, without the oneof or repeated flag. -static PROTOBUF_CONSTEXPR const unsigned char kTypeMask = 0x1f; +static constexpr const unsigned char kTypeMask = 0x1f; // Wire type masks. -static PROTOBUF_CONSTEXPR const unsigned char kNotPackedMask = 0x10; -static PROTOBUF_CONSTEXPR const unsigned char kInvalidMask = 0x20; +static constexpr const unsigned char kNotPackedMask = 0x10; +static constexpr const unsigned char kInvalidMask = 0x20; enum ProcessingTypes { - TYPE_STRING_CORD = 19, - TYPE_STRING_STRING_PIECE = 20, - TYPE_BYTES_CORD = 21, - TYPE_BYTES_STRING_PIECE = 22, - TYPE_MAP = 23, + TYPE_STRING_INLINED = 23, + TYPE_BYTES_INLINED = 24, + TYPE_MAP = 25, }; -#if LANG_CXX11 static_assert(TYPE_MAP < kRepeatedMask, "Invalid enum"); -#endif // TODO(ckennelly): Add a static assertion to ensure that these masks do not // conflict with wiretypes. @@ -124,7 +112,6 @@ union AuxillaryParseTableField { const MessageLite* default_message() const { return static_cast<const MessageLite*>(default_message_void); } - const ParseTable* parse_table; }; message_aux messages; // Strings @@ -139,19 +126,14 @@ union AuxillaryParseTableField { }; map_aux maps; -#if LANG_CXX11 AuxillaryParseTableField() = default; -#else - AuxillaryParseTableField() { } -#endif - PROTOBUF_CONSTEXPR AuxillaryParseTableField( - AuxillaryParseTableField::enum_aux e) : enums(e) {} - PROTOBUF_CONSTEXPR AuxillaryParseTableField( - AuxillaryParseTableField::message_aux m) : messages(m) {} - PROTOBUF_CONSTEXPR AuxillaryParseTableField( - AuxillaryParseTableField::string_aux s) : strings(s) {} - PROTOBUF_CONSTEXPR AuxillaryParseTableField( - AuxillaryParseTableField::map_aux m) + constexpr AuxillaryParseTableField(AuxillaryParseTableField::enum_aux e) + : enums(e) {} + constexpr AuxillaryParseTableField(AuxillaryParseTableField::message_aux m) + : messages(m) {} + constexpr AuxillaryParseTableField(AuxillaryParseTableField::string_aux s) + : strings(s) {} + constexpr AuxillaryParseTableField(AuxillaryParseTableField::map_aux m) : maps(m) {} }; @@ -178,18 +160,17 @@ struct ParseTable { bool unknown_field_set; }; -// TODO(jhen): Remove the __NVCC__ check when we get a version of nvcc that -// supports these checks. -#if LANG_CXX11 && !defined(__NVCC__) static_assert(sizeof(ParseTableField) <= 16, "ParseTableField is too large"); // The tables must be composed of POD components to ensure link-time // initialization. static_assert(std::is_pod<ParseTableField>::value, ""); -static_assert(std::is_pod<AuxillaryParseTableField>::value, ""); static_assert(std::is_pod<AuxillaryParseTableField::enum_aux>::value, ""); static_assert(std::is_pod<AuxillaryParseTableField::message_aux>::value, ""); static_assert(std::is_pod<AuxillaryParseTableField::string_aux>::value, ""); static_assert(std::is_pod<ParseTable>::value, ""); + +#ifndef __NVCC__ // This assertion currently fails under NVCC. +static_assert(std::is_pod<AuxillaryParseTableField>::value, ""); #endif // TODO(ckennelly): Consolidate these implementations into a single one, using diff --git a/src/google/protobuf/generated_message_table_driven_lite.cc b/src/google/protobuf/generated_message_table_driven_lite.cc index 90a50505..961329f3 100644 --- a/src/google/protobuf/generated_message_table_driven_lite.cc +++ b/src/google/protobuf/generated_message_table_driven_lite.cc @@ -30,7 +30,7 @@ #include <google/protobuf/generated_message_table_driven_lite.h> -#include <google/protobuf/stubs/type_traits.h> +#include <type_traits> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> #include <google/protobuf/metadata_lite.h> diff --git a/src/google/protobuf/generated_message_table_driven_lite.h b/src/google/protobuf/generated_message_table_driven_lite.h index 4dfbf678..0d90fe33 100644 --- a/src/google/protobuf/generated_message_table_driven_lite.h +++ b/src/google/protobuf/generated_message_table_driven_lite.h @@ -33,14 +33,15 @@ #include <google/protobuf/generated_message_table_driven.h> -#include <google/protobuf/stubs/type_traits.h> - #include <google/protobuf/io/zero_copy_stream_impl_lite.h> #include <google/protobuf/extension_set.h> +#include <google/protobuf/implicit_weak_message.h> +#include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata_lite.h> #include <google/protobuf/repeated_field.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/wire_format_lite_inl.h> +#include <type_traits> namespace google { @@ -50,8 +51,7 @@ namespace internal { enum StringType { StringType_STRING = 0, - StringType_CORD = 1, - StringType_STRING_PIECE = 2 + StringType_INLINED = 3 }; // Logically a superset of StringType, consisting of all field types that @@ -60,7 +60,8 @@ enum ProcessingType { ProcessingType_STRING = 0, ProcessingType_CORD = 1, ProcessingType_STRING_PIECE = 2, - ProcessingType_MESSAGE = 3 + ProcessingType_INLINED = 3, + ProcessingType_MESSAGE = 4, }; enum Cardinality { @@ -99,10 +100,9 @@ inline ExtensionSet* GetExtensionSet(MessageLite* msg, int64 extension_offset) { template <typename Type> inline Type* AddField(MessageLite* msg, int64 offset) { -#if LANG_CXX11 - static_assert(has_trivial_copy<Type>::value, + static_assert(std::is_pod<Type>::value || + std::is_same<Type, InlinedStringField>::value, "Do not assign"); -#endif google::protobuf::RepeatedField<Type>* repeated = Raw<google::protobuf::RepeatedField<Type> >(msg, offset); @@ -119,15 +119,13 @@ inline string* AddField<string>(MessageLite* msg, int64 offset) { template <typename Type> inline void AddField(MessageLite* msg, int64 offset, Type value) { -#if LANG_CXX11 - static_assert(has_trivial_copy<Type>::value, + static_assert(std::is_pod<Type>::value, "Do not assign"); -#endif *AddField<Type>(msg, offset) = value; } inline void SetBit(uint32* has_bits, uint32 has_bit_index) { - GOOGLE_DCHECK(has_bits != NULL); + GOOGLE_DCHECK(has_bits != nullptr); uint32 mask = static_cast<uint32>(1u) << (has_bit_index % 32); has_bits[has_bit_index / 32u] |= mask; @@ -143,10 +141,8 @@ inline Type* MutableField(MessageLite* msg, uint32* has_bits, template <typename Type> inline void SetField(MessageLite* msg, uint32* has_bits, uint32 has_bit_index, int64 offset, Type value) { -#if LANG_CXX11 - static_assert(has_trivial_copy<Type>::value, + static_assert(std::is_pod<Type>::value, "Do not assign"); -#endif *MutableField<Type>(msg, has_bits, has_bit_index, offset) = value; } @@ -175,6 +171,11 @@ inline void ClearOneofField(const ParseTableField& field, Arena* arena, ->Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena); break; + case TYPE_STRING_INLINED: + case TYPE_BYTES_INLINED: + Raw<InlinedStringField>(msg, field.offset)->DestroyNoArena(NULL); + break; + default: // No cleanup needed. break; @@ -207,6 +208,10 @@ inline void ResetOneofField(const ParseTable& table, int field_number, Raw<ArenaStringPtr>(msg, offset) ->UnsafeSetDefault(static_cast<const string*>(default_ptr)); break; + case ProcessingType_INLINED: + new (Raw<InlinedStringField>(msg, offset)) + InlinedStringField(*static_cast<const string*>(default_ptr)); + break; case ProcessingType_MESSAGE: MessageLite** submessage = Raw<MessageLite*>(msg, offset); const MessageLite* prototype = @@ -227,32 +232,65 @@ static inline bool HandleString(io::CodedInputStream* input, MessageLite* msg, size_t size; #endif - string* value; - switch (cardinality) { - case Cardinality_SINGULAR: - // TODO(ckennelly): Is this optimal? - value = - MutableField<ArenaStringPtr>(msg, has_bits, has_bit_index, offset) - ->Mutable(static_cast<const string*>(default_ptr), arena); - break; - case Cardinality_REPEATED: - value = AddField<string>(msg, offset); - break; - case Cardinality_ONEOF: - value = Raw<ArenaStringPtr>(msg, offset) - ->Mutable(static_cast<const string*>(default_ptr), arena); - break; - } - GOOGLE_DCHECK(value != NULL); + switch (ctype) { + case StringType_INLINED: { + InlinedStringField* s; + switch (cardinality) { + case Cardinality_SINGULAR: + // TODO(ckennelly): Is this optimal? + s = MutableField<InlinedStringField>( + msg, has_bits, has_bit_index, offset); + break; + case Cardinality_REPEATED: + s = AddField<InlinedStringField>(msg, offset); + break; + case Cardinality_ONEOF: + s = Raw<InlinedStringField>(msg, offset); + break; + } + GOOGLE_DCHECK(s != nullptr); + ::std::string* value = s->MutableNoArena(NULL); + + if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) { + return false; + } - if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) { - return false; +#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED + sdata = value->data(); + size = value->size(); +#endif + break; } + case StringType_STRING: { + string* value; + switch (cardinality) { + case Cardinality_SINGULAR: + // TODO(ckennelly): Is this optimal? + value = + MutableField<ArenaStringPtr>(msg, has_bits, has_bit_index, offset) + ->Mutable(static_cast<const string*>(default_ptr), arena); + break; + case Cardinality_REPEATED: + value = AddField<string>(msg, offset); + break; + case Cardinality_ONEOF: + value = Raw<ArenaStringPtr>(msg, offset) + ->Mutable(static_cast<const string*>(default_ptr), arena); + break; + } + GOOGLE_DCHECK(value != nullptr); + + if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) { + return false; + } #ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED - sdata = value->data(); - size = value->size(); + sdata = value->data(); + size = value->size(); #endif + break; + } + } #ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED if (validate) { @@ -323,44 +361,6 @@ class RepeatedMessageTypeHandler { } }; -inline bool ReadGroup(int field_number, io::CodedInputStream* input, - MessageLite* value) { - if (GOOGLE_PREDICT_FALSE(!input->IncrementRecursionDepth())) { - return false; - } - - if (GOOGLE_PREDICT_FALSE(!value->MergePartialFromCodedStream(input))) { - return false; - } - - input->DecrementRecursionDepth(); - // Make sure the last thing read was an end tag for this group. - if (GOOGLE_PREDICT_FALSE(!input->LastTagWas(WireFormatLite::MakeTag( - field_number, WireFormatLite::WIRETYPE_END_GROUP)))) { - return false; - } - - return true; -} - -inline bool ReadMessage(io::CodedInputStream* input, MessageLite* value) { - int length; - if (GOOGLE_PREDICT_FALSE(!input->ReadVarintSizeAsInt(&length))) { - return false; - } - - std::pair<io::CodedInputStream::Limit, int> p = - input->IncrementRecursionDepthAndPushLimit(length); - if (GOOGLE_PREDICT_FALSE(p.second < 0 || - !value->MergePartialFromCodedStream(input))) { - return false; - } - - // Make sure that parsing stopped when the limit was hit, not at an endgroup - // tag. - return input->DecrementRecursionDepthAndPopLimit(p.first); -} - class MergePartialFromCodedStreamHelper { public: static MessageLite* Add(RepeatedPtrFieldBase* field, @@ -490,6 +490,23 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, } break; } + case TYPE_BYTES_INLINED: +#ifndef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED + case TYPE_STRING_INLINED: +#endif + { + Arena* const arena = + GetArena<InternalMetadata>(msg, table.arena_offset); + const void* default_ptr = table.aux[field_number].strings.default_ptr; + + if (GOOGLE_PREDICT_FALSE((!HandleString<Cardinality_SINGULAR, false, + StringType_INLINED>( + input, msg, arena, has_bits, presence_index, offset, + default_ptr, NULL)))) { + return false; + } + break; + } case WireFormatLite::TYPE_BYTES | kOneofMask: #ifndef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED case WireFormatLite::TYPE_STRING | kOneofMask: @@ -513,8 +530,10 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, break; } case (WireFormatLite::TYPE_BYTES) | kRepeatedMask: + case TYPE_BYTES_INLINED | kRepeatedMask: #ifndef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED case (WireFormatLite::TYPE_STRING) | kRepeatedMask: + case TYPE_STRING_INLINED | kRepeatedMask: #endif { Arena* const arena = @@ -545,6 +564,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, } break; } + case TYPE_STRING_INLINED | kRepeatedMask: case (WireFormatLite::TYPE_STRING) | kRepeatedMask: { Arena* const arena = GetArena<InternalMetadata>(msg, table.arena_offset); @@ -657,6 +677,10 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, GetArena<InternalMetadata>(msg, table.arena_offset); const MessageLite* prototype = table.aux[field_number].messages.default_message(); + if (prototype == NULL) { + prototype = + ::google::protobuf::internal::ImplicitWeakMessage::default_instance(); + } submsg = prototype->New(arena); *submsg_holder = submsg; } @@ -673,7 +697,10 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, RepeatedPtrFieldBase* field = Raw<RepeatedPtrFieldBase>(msg, offset); const MessageLite* prototype = table.aux[field_number].messages.default_message(); - GOOGLE_DCHECK(prototype != NULL); + if (prototype == NULL) { + prototype = + ::google::protobuf::internal::ImplicitWeakMessage::default_instance(); + } MessageLite* submsg = MergePartialFromCodedStreamHelper::Add(field, prototype); @@ -700,6 +727,22 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, break; } +#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED + case TYPE_STRING_INLINED: { + Arena* const arena = + GetArena<InternalMetadata>(msg, table.arena_offset); + const void* default_ptr = table.aux[field_number].strings.default_ptr; + const char* field_name = table.aux[field_number].strings.field_name; + + if (GOOGLE_PREDICT_FALSE(( + !HandleString<Cardinality_SINGULAR, true, StringType_INLINED>( + input, msg, arena, has_bits, presence_index, offset, + default_ptr, field_name)))) { + return false; + } + break; + } +#endif // GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED case TYPE_MAP: { if (GOOGLE_PREDICT_FALSE(!(*table.aux[field_number].maps.parse_map)( input, Raw<void>(msg, offset)))) { @@ -721,7 +764,8 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, GOOGLE_DCHECK_NE(processing_type, kRepeatedMask); GOOGLE_DCHECK_EQ(0, processing_type & kOneofMask); - + GOOGLE_DCHECK_NE(TYPE_BYTES_INLINED | kRepeatedMask, processing_type); + GOOGLE_DCHECK_NE(TYPE_STRING_INLINED | kRepeatedMask, processing_type); // TODO(ckennelly): Use a computed goto on GCC/LLVM. // diff --git a/src/google/protobuf/generated_message_util.cc b/src/google/protobuf/generated_message_util.cc index 15d84222..dac8ca90 100644 --- a/src/google/protobuf/generated_message_util.cc +++ b/src/google/protobuf/generated_message_util.cc @@ -35,6 +35,9 @@ #include <google/protobuf/generated_message_util.h> #include <limits> +// We're only using this as a standard way for getting the thread id. +// We're not using any thread functionality. +#include <thread> // NOLINT #include <vector> #include <google/protobuf/io/coded_stream_inl.h> @@ -43,6 +46,7 @@ #include <google/protobuf/extension_set.h> #include <google/protobuf/message_lite.h> #include <google/protobuf/metadata_lite.h> +#include <google/protobuf/stubs/mutex.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/repeated_field.h> #include <google/protobuf/wire_format_lite.h> @@ -61,7 +65,7 @@ double NaN() { return std::numeric_limits<double>::quiet_NaN(); } -ExplicitlyConstructed< ::std::string> fixed_address_empty_string; +ExplicitlyConstructed<::std::string> fixed_address_empty_string; GOOGLE_PROTOBUF_DECLARE_ONCE(empty_string_once_init_); void DeleteEmptyString() { fixed_address_empty_string.Destruct(); } @@ -251,6 +255,10 @@ struct PrimitiveTypeHelper<WireFormatLite::TYPE_BYTES> : PrimitiveTypeHelper<WireFormatLite::TYPE_STRING> {}; +template <> +struct PrimitiveTypeHelper<FieldMetadata::kInlinedType> + : PrimitiveTypeHelper<WireFormatLite::TYPE_STRING> {}; + // We want to serialize to both CodedOutputStream and directly into byte arrays // without duplicating the code. In fact we might want extra output channels in // the future. @@ -274,7 +282,7 @@ void WriteLengthTo(uint32 length, O* output) { // Specialization for coded output stream template <int type> -struct OutputHelper< ::google::protobuf::io::CodedOutputStream, type> { +struct OutputHelper<::google::protobuf::io::CodedOutputStream, type> { static void Serialize(const void* ptr, ::google::protobuf::io::CodedOutputStream* output) { PrimitiveTypeHelper<type>::Serialize(ptr, output); @@ -416,6 +424,15 @@ struct SingularFieldHelper<WireFormatLite::TYPE_MESSAGE> { } }; +template <> +struct SingularFieldHelper<FieldMetadata::kInlinedType> { + template <typename O> + static void Serialize(const void* field, const FieldMetadata& md, O* output) { + WriteTagTo(md.tag, output); + SerializeTo<FieldMetadata::kInlinedType>(&Get<::std::string>(field), output); + } +}; + template <int type> struct RepeatedFieldHelper { template <typename O> @@ -488,6 +505,10 @@ struct RepeatedFieldHelper<WireFormatLite::TYPE_MESSAGE> { }; +template <> +struct RepeatedFieldHelper<FieldMetadata::kInlinedType> + : RepeatedFieldHelper<WireFormatLite::TYPE_STRING> {}; + template <int type> struct PackedFieldHelper { template <typename O> @@ -523,6 +544,9 @@ struct PackedFieldHelper<WireFormatLite::TYPE_GROUP> template <> struct PackedFieldHelper<WireFormatLite::TYPE_MESSAGE> : PackedFieldHelper<WireFormatLite::TYPE_STRING> {}; +template <> +struct PackedFieldHelper<FieldMetadata::kInlinedType> + : PackedFieldHelper<WireFormatLite::TYPE_STRING> {}; template <int type> struct OneOfFieldHelper { @@ -533,6 +557,15 @@ struct OneOfFieldHelper { }; +template <> +struct OneOfFieldHelper<FieldMetadata::kInlinedType> { + template <typename O> + static void Serialize(const void* field, const FieldMetadata& md, O* output) { + SingularFieldHelper<FieldMetadata::kInlinedType>::Serialize( + Get<const ::std::string*>(field), md, output); + } +}; + void SerializeNotImplemented(int field) { GOOGLE_LOG(FATAL) << "Not implemented field number " << field; } @@ -573,6 +606,11 @@ bool IsNull<WireFormatLite::TYPE_MESSAGE>(const void* ptr) { } +template <> +bool IsNull<FieldMetadata::kInlinedType>(const void* ptr) { + return static_cast<const ::std::string*>(ptr)->empty(); +} + #define SERIALIZERS_FOR_TYPE(type) \ case SERIALIZE_TABLE_OP(type, FieldMetadata::kPresence): \ if (!IsPresent(base, field_metadata.has_offset)) continue; \ @@ -620,6 +658,7 @@ void SerializeInternal(const uint8* base, SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SFIXED64); SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT32); SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT64); + SERIALIZERS_FOR_TYPE(FieldMetadata::kInlinedType); // Special cases case FieldMetadata::kSpecial: @@ -663,6 +702,7 @@ uint8* SerializeInternalToArray(const uint8* base, SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SFIXED64); SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT32); SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT64); + SERIALIZERS_FOR_TYPE(FieldMetadata::kInlinedType); // Special cases case FieldMetadata::kSpecial: { io::ArrayOutputStream array_stream(array_output.ptr, INT_MAX); @@ -698,9 +738,9 @@ void UnknownFieldSerializerLite(const uint8* ptr, uint32 offset, uint32 tag, ->unknown_fields()); } -MessageLite* DuplicateIfNonNullInternal(MessageLite* message, Arena* arena) { +MessageLite* DuplicateIfNonNullInternal(MessageLite* message) { if (message) { - MessageLite* ret = message->New(arena); + MessageLite* ret = message->New(); ret->CheckTypeAndMergeFrom(*message); return ret; } else { @@ -725,6 +765,49 @@ MessageLite* GetOwnedMessageInternal(Arena* message_arena, } } +namespace { + +void InitSCC_DFS(SCCInfoBase* scc) { + if (scc->visit_status.load(std::memory_order_relaxed) != + SCCInfoBase::kUninitialized) return; + scc->visit_status.store(SCCInfoBase::kRunning, std::memory_order_relaxed); + // Each base is followed by an array of pointers to deps + auto deps = reinterpret_cast<SCCInfoBase* const*>(scc + 1); + for (int i = 0; i < scc->num_deps; i++) { + if (deps[i]) InitSCC_DFS(deps[i]); + } + scc->init_func(); + // Mark done (note we use memory order release here), other threads could + // now see this as initialized and thus the initialization must have happened + // before. + scc->visit_status.store(SCCInfoBase::kInitialized, std::memory_order_release); +} + +} // namespace + +void InitSCCImpl(SCCInfoBase* scc) { + static WrappedMutex mu{GOOGLE_PROTOBUF_LINKER_INITIALIZED}; + // Either the default in case no initialization is running or the id of the + // thread that is currently initializing. + static std::atomic<std::thread::id> runner; + auto me = std::this_thread::get_id(); + // This will only happen because the constructor will call InitSCC while + // constructing the default instance. + if (runner.load(std::memory_order_relaxed) == me) { + // Because we're in the process of constructing the default instance. + // We can be assured that we're already exploring this SCC. + GOOGLE_CHECK_EQ(scc->visit_status.load(std::memory_order_relaxed), + SCCInfoBase::kRunning); + return; + } + InitProtobufDefaults(); + mu.Lock(); + runner.store(me, std::memory_order_relaxed); + InitSCC_DFS(scc); + runner.store(std::thread::id{}, std::memory_order_relaxed); + mu.Unlock(); +} + } // namespace internal } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/generated_message_util.h b/src/google/protobuf/generated_message_util.h index cd74b45e..bdaa561b 100644 --- a/src/google/protobuf/generated_message_util.h +++ b/src/google/protobuf/generated_message_util.h @@ -39,13 +39,14 @@ #define GOOGLE_PROTOBUF_GENERATED_MESSAGE_UTIL_H__ #include <assert.h> +#include <atomic> #include <climits> #include <string> #include <vector> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> -#include <google/protobuf/stubs/once.h> +#include <google/protobuf/stubs/once.h> // Add direct dep on port for pb.cc #include <google/protobuf/has_bits.h> #include <google/protobuf/implicit_weak_message.h> #include <google/protobuf/map_entry_lite.h> @@ -128,7 +129,7 @@ template <class T> bool AllAreInitializedWeak(const ::google::protobuf::RepeatedPtrField<T>& t) { for (int i = t.size(); --i >= 0;) { if (!reinterpret_cast<const ::google::protobuf::internal::RepeatedPtrFieldBase&>(t) - .Get< ::google::protobuf::internal::ImplicitWeakTypeHandler<T> >(i) + .Get<::google::protobuf::internal::ImplicitWeakTypeHandler<T> >(i) .IsInitialized()) { return false; } @@ -164,7 +165,8 @@ struct LIBPROTOBUF_EXPORT FieldMetadata { enum { kCordType = 19, kStringPieceType = 20, - kNumTypes = 20, + kInlinedType = 21, + kNumTypes = 21, kSpecial = kNumTypes * kNumTypeClasses, }; @@ -173,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) { @@ -199,7 +201,7 @@ struct SerializationTable { }; LIBPROTOBUF_EXPORT void SerializeInternal(const uint8* base, const FieldMetadata* table, - int num_fields, ::google::protobuf::io::CodedOutputStream* output); + int32 num_fields, ::google::protobuf::io::CodedOutputStream* output); inline void TableSerialize(const ::google::protobuf::MessageLite& msg, const SerializationTable* table, @@ -217,7 +219,7 @@ inline void TableSerialize(const ::google::protobuf::MessageLite& msg, } uint8* SerializeInternalToArray(const uint8* base, const FieldMetadata* table, - int num_fields, bool is_deterministic, + int32 num_fields, bool is_deterministic, uint8* buffer); inline uint8* TableSerializeToArray(const ::google::protobuf::MessageLite& msg, @@ -290,17 +292,17 @@ void MapFieldSerializer(const uint8* base, uint32 offset, uint32 tag, } } -LIBPROTOBUF_EXPORT MessageLite* DuplicateIfNonNullInternal(MessageLite* message, Arena* arena); +LIBPROTOBUF_EXPORT MessageLite* DuplicateIfNonNullInternal(MessageLite* message); LIBPROTOBUF_EXPORT MessageLite* GetOwnedMessageInternal(Arena* message_arena, MessageLite* submessage, Arena* submessage_arena); template <typename T> -T* DuplicateIfNonNull(T* message, Arena* arena) { +T* DuplicateIfNonNull(T* message) { // The casts must be reinterpret_cast<> because T might be a forward-declared // type that the compiler doesn't know is related to MessageLite. - return reinterpret_cast<T*>(DuplicateIfNonNullInternal( - reinterpret_cast<MessageLite*>(message), arena)); + return reinterpret_cast<T*>( + DuplicateIfNonNullInternal(reinterpret_cast<MessageLite*>(message))); } template <typename T> @@ -313,20 +315,48 @@ T* GetOwnedMessage(Arena* message_arena, T* submessage, submessage_arena)); } -// Returns a message owned by this Arena. This may require Own()ing or -// duplicating the message. -template <typename T> -T* GetOwnedMessage(T* message, Arena* arena) { - GOOGLE_DCHECK(message); - Arena* message_arena = google::protobuf::Arena::GetArena(message); - if (message_arena == arena) { - return message; - } else if (arena != NULL && message_arena == NULL) { - arena->Own(message); - return message; - } else { - return DuplicateIfNonNull(message, arena); - } +// Hide atomic from the public header and allow easy change to regular int +// on platforms where the atomic might have a perf impact. +class LIBPROTOBUF_EXPORT CachedSize { + public: + int Get() const { return size_.load(std::memory_order_relaxed); } + void Set(int size) { size_.store(size, std::memory_order_relaxed); } + private: + std::atomic<int> size_{0}; +}; + +// SCCInfo represents information of a strongly connected component of +// mutual dependent messages. +struct LIBPROTOBUF_EXPORT SCCInfoBase { + // We use 0 for the Initialized state, because test eax,eax, jnz is smaller + // and is subject to macro fusion. + enum { + kInitialized = 0, // final state + kRunning = 1, + kUninitialized = -1, // initial state + }; + std::atomic<int> visit_status; + int num_deps; + void (*init_func)(); + // This is followed by an array of num_deps + // const SCCInfoBase* deps[]; +}; + +template <int N> +struct SCCInfo { + SCCInfoBase base; + // Semantically this is const SCCInfo<T>* which is is a templated type. + // The obvious inheriting from SCCInfoBase mucks with struct initialization. + // Attempts showed the compiler was generating dynamic initialization code. + // Zero length arrays produce warnings with MSVC. + SCCInfoBase* deps[N ? N : 1]; +}; + +LIBPROTOBUF_EXPORT void InitSCCImpl(SCCInfoBase* scc); + +inline void InitSCC(SCCInfoBase* scc) { + auto status = scc->visit_status.load(std::memory_order_acquire); + if (GOOGLE_PREDICT_FALSE(status != SCCInfoBase::kInitialized)) InitSCCImpl(scc); } } // namespace internal diff --git a/src/google/protobuf/implicit_weak_message.cc b/src/google/protobuf/implicit_weak_message.cc index 0dd126be..7a1d4446 100644 --- a/src/google/protobuf/implicit_weak_message.cc +++ b/src/google/protobuf/implicit_weak_message.cc @@ -30,6 +30,7 @@ #include <google/protobuf/implicit_weak_message.h> +#include <google/protobuf/stubs/once.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> #include <google/protobuf/wire_format_lite.h> @@ -37,15 +38,26 @@ namespace google { namespace protobuf { namespace internal { -::google::protobuf::internal::ExplicitlyConstructed<ImplicitWeakMessage> - implicit_weak_message_default_instance; - bool ImplicitWeakMessage::MergePartialFromCodedStream(io::CodedInputStream* input) { io::StringOutputStream string_stream(&data_); io::CodedOutputStream coded_stream(&string_stream, false); return WireFormatLite::SkipMessage(input, &coded_stream); } +::google::protobuf::internal::ExplicitlyConstructed<ImplicitWeakMessage> + implicit_weak_message_default_instance; +GOOGLE_PROTOBUF_DECLARE_ONCE(implicit_weak_message_once_init_); + +void InitImplicitWeakMessageDefaultInstance() { + implicit_weak_message_default_instance.DefaultConstruct(); +} + +const ImplicitWeakMessage* ImplicitWeakMessage::default_instance() { + ::google::protobuf::GoogleOnceInit(&implicit_weak_message_once_init_, + &InitImplicitWeakMessageDefaultInstance); + return &implicit_weak_message_default_instance.get(); +} + } // namespace internal } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/implicit_weak_message.h b/src/google/protobuf/implicit_weak_message.h index a822172e..3279bd17 100644 --- a/src/google/protobuf/implicit_weak_message.h +++ b/src/google/protobuf/implicit_weak_message.h @@ -50,6 +50,8 @@ class LIBPROTOBUF_EXPORT ImplicitWeakMessage : public MessageLite { ImplicitWeakMessage() : arena_(NULL) {} explicit ImplicitWeakMessage(Arena* arena) : arena_(arena) {} + static const ImplicitWeakMessage* default_instance(); + string GetTypeName() const { return ""; } MessageLite* New() const { return new ImplicitWeakMessage; } @@ -91,9 +93,7 @@ class ImplicitWeakTypeHandler { public: typedef ImplicitWeakType Type; typedef ::google::protobuf::MessageLite WeakType; -#if LANG_CXX11 static const bool Moveable = false; -#endif // With implicit weak fields, we need separate NewFromPrototype and // NewFromPrototypeWeak functions. The former is used when we want to create a @@ -128,9 +128,6 @@ class ImplicitWeakTypeHandler { } }; -extern ::google::protobuf::internal::ExplicitlyConstructed<ImplicitWeakMessage> - implicit_weak_message_default_instance; - } // namespace internal } // namespace protobuf diff --git a/src/google/protobuf/inlined_string_field.h b/src/google/protobuf/inlined_string_field.h new file mode 100644 index 00000000..95d4687b --- /dev/null +++ b/src/google/protobuf/inlined_string_field.h @@ -0,0 +1,271 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#ifndef GOOGLE_PROTOBUF_INLINED_STRING_FIELD_H__ +#define GOOGLE_PROTOBUF_INLINED_STRING_FIELD_H__ + +#include <string> + +#include <google/protobuf/stubs/port.h> +#include <google/protobuf/stubs/stringpiece.h> + +namespace google { +namespace protobuf { + +class Arena; + +namespace internal { + +// InlinedStringField wraps a ::std::string instance and exposes an API similar to +// ArenaStringPtr's wrapping of a ::std::string* instance. As ::std::string is never +// allocated on the Arena, we expose only the *NoArena methods of +// ArenaStringPtr. +// +// default_value parameters are taken for consistency with ArenaStringPtr, but +// are not used for most methods. With inlining, these should be removed from +// the generated binary. +class LIBPROTOBUF_EXPORT InlinedStringField { + public: + InlinedStringField() + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + explicit InlinedStringField(const ::std::string& default_value); + + void AssignWithDefault(const ::std::string* default_value, + const InlinedStringField& from) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + + void ClearToEmpty(const ::std::string* default_value, Arena* arena) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + ClearToEmptyNoArena(default_value); + } + void ClearNonDefaultToEmpty() GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + ClearNonDefaultToEmptyNoArena(); + } + void ClearToEmptyNoArena(const ::std::string* default_value) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + ClearNonDefaultToEmptyNoArena(); + } + void ClearNonDefaultToEmptyNoArena() + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + + void ClearToDefault(const ::std::string* default_value, Arena* arena) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + ClearToDefaultNoArena(default_value); + } + void ClearToDefaultNoArena(const ::std::string* default_value) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + + void Destroy(const ::std::string* default_value, Arena* arena) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + DestroyNoArena(default_value); + } + void DestroyNoArena(const ::std::string* default_value) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + + const ::std::string& Get() const GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + return GetNoArena(); + } + const ::std::string& GetNoArena() const GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + + ::std::string* Mutable(const ::std::string* default_value, Arena* arena) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + return MutableNoArena(default_value); + } + ::std::string* MutableNoArena(const ::std::string* default_value) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + + ::std::string* Release(const ::std::string* default_value, Arena* arena) { + return ReleaseNoArena(default_value); + } + ::std::string* ReleaseNonDefault(const ::std::string* default_value, Arena* arena) { + return ReleaseNonDefaultNoArena(default_value); + } + ::std::string* ReleaseNoArena(const ::std::string* default_value) { + return ReleaseNonDefaultNoArena(default_value); + } + ::std::string* ReleaseNonDefaultNoArena(const ::std::string* default_value); + + void Set(const ::std::string* default_value, + StringPiece value, + Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + SetNoArena(default_value, value); + } + void SetLite(const ::std::string* default_value, + StringPiece value, + Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + SetNoArena(default_value, value); + } + void SetNoArena(const ::std::string* default_value, + StringPiece value) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + + void Set(const ::std::string* default_value, + const ::std::string& value, + Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + SetNoArena(default_value, value); + } + void SetLite(const ::std::string* default_value, + const ::std::string& value, + Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + SetNoArena(default_value, value); + } + void SetNoArena(const ::std::string* default_value, + const ::std::string& value) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + +#if LANG_CXX11 + void SetNoArena(const ::std::string* default_value, + ::std::string&& value) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; +#endif + void SetAllocated(const ::std::string* default_value, + ::std::string* value, + Arena* arena) { + SetAllocatedNoArena(default_value, value); + } + void SetAllocatedNoArena(const ::std::string* default_value, + ::std::string* value); + void Swap(InlinedStringField* from) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + ::std::string* UnsafeMutablePointer(); + void UnsafeSetDefault(const ::std::string* default_value); + ::std::string* UnsafeArenaRelease(const ::std::string* default_value, Arena* arena); + void UnsafeArenaSetAllocated( + const ::std::string* default_value, ::std::string* value, Arena* arena); + + bool IsDefault(const ::std::string* default_value) { + return false; + } + private: + ::std::string value_; +}; + +inline InlinedStringField::InlinedStringField() {} + +inline InlinedStringField::InlinedStringField(const ::std::string& default_value) : + value_(default_value) {} + +inline void InlinedStringField::AssignWithDefault( + const ::std::string* default_value, const InlinedStringField& from) { + value_ = from.value_; +} + +inline const ::std::string& InlinedStringField::GetNoArena() const { + return value_; +} + +inline ::std::string* InlinedStringField::MutableNoArena(const ::std::string*) { + return &value_; +} + +inline void InlinedStringField::SetAllocatedNoArena( + const ::std::string* default_value, ::std::string* value) { + if (value == NULL) { + value_.assign(*default_value); + } else { +#if LANG_CXX11 + value_.assign(std::move(*value)); +#else + value_.swap(*value); +#endif + delete value; + } +} + +inline void InlinedStringField::DestroyNoArena(const ::std::string*) { + // This is invoked from the generated message's ArenaDtor, which is used to + // clean up objects not allocated on the Arena. + this->~InlinedStringField(); +} + +inline void InlinedStringField::ClearNonDefaultToEmptyNoArena() { + value_.clear(); +} + +inline void InlinedStringField::ClearToDefaultNoArena( + const ::std::string* default_value) { + value_.assign(*default_value); +} + +inline ::std::string* InlinedStringField::ReleaseNonDefaultNoArena( + const ::std::string* default_value) { + ::std::string* released = new ::std::string(*default_value); + value_.swap(*released); + return released; +} + +inline void InlinedStringField::SetNoArena( + const ::std::string* default_value, StringPiece value) { + value_.assign(value.data(), value.length()); +} + +inline void InlinedStringField::SetNoArena( + const ::std::string* default_value, const ::std::string& value) { + value_.assign(value); +} + +#if LANG_CXX11 +inline void InlinedStringField::SetNoArena( + const ::std::string* default_value, ::std::string&& value) { + value_.assign(std::move(value)); +} +#endif + +inline void InlinedStringField::Swap(InlinedStringField* from) { + value_.swap(from->value_); +} + +inline ::std::string* InlinedStringField::UnsafeMutablePointer() { + return &value_; +} + +inline void InlinedStringField::UnsafeSetDefault( + const ::std::string* default_value) { + value_.assign(*default_value); +} + +inline ::std::string* InlinedStringField::UnsafeArenaRelease( + const ::std::string* default_value, Arena* arena) { + return ReleaseNoArena(default_value); +} + +inline void InlinedStringField::UnsafeArenaSetAllocated( + const ::std::string* default_value, ::std::string* value, Arena* arena) { + if (value == NULL) { + value_.assign(*default_value); + } else { + value_.assign(*value); + } +} + +} // namespace internal +} // namespace protobuf + +} // namespace google +#endif // GOOGLE_PROTOBUF_INLINED_STRING_FIELD_H__ diff --git a/src/google/protobuf/io/coded_stream.cc b/src/google/protobuf/io/coded_stream.cc index d3bc7c6d..0851ff0c 100644 --- a/src/google/protobuf/io/coded_stream.cc +++ b/src/google/protobuf/io/coded_stream.cc @@ -217,8 +217,12 @@ bool CodedInputStream::SkipFallback(int count, int original_buffer_size) { return false; } + if (!input_->Skip(count)) { + total_bytes_read_ = input_->ByteCount(); + return false; + } total_bytes_read_ += count; - return input_->Skip(count); + return true; } bool CodedInputStream::GetDirectBufferPointer(const void** data, int* size) { @@ -615,23 +619,11 @@ bool CodedInputStream::Refresh() { // CodedOutputStream ================================================= -google::protobuf::internal::AtomicWord CodedOutputStream::default_serialization_deterministic_ = 0; +std::atomic<bool> CodedOutputStream::default_serialization_deterministic_{ + false}; CodedOutputStream::CodedOutputStream(ZeroCopyOutputStream* output) - : output_(output), - buffer_(NULL), - buffer_size_(0), - total_bytes_(0), - had_error_(false), - aliasing_enabled_(false), - serialization_deterministic_is_overridden_(false) { - // Eagerly Refresh() so buffer space is immediately available. - Refresh(); - // The Refresh() may have failed. If the client doesn't write any data, - // though, don't consider this an error. If the client does write data, then - // another Refresh() will be attempted and it will set the error once again. - had_error_ = false; -} + : CodedOutputStream(output, true) {} CodedOutputStream::CodedOutputStream(ZeroCopyOutputStream* output, bool do_eager_refresh) @@ -641,7 +633,7 @@ CodedOutputStream::CodedOutputStream(ZeroCopyOutputStream* output, total_bytes_(0), had_error_(false), aliasing_enabled_(false), - serialization_deterministic_is_overridden_(false) { + is_serialization_deterministic_(IsDefaultSerializationDeterministic()) { if (do_eager_refresh) { // Eagerly Refresh() so buffer space is immediately available. Refresh(); diff --git a/src/google/protobuf/io/coded_stream.h b/src/google/protobuf/io/coded_stream.h index ec85147b..0f70ecde 100644 --- a/src/google/protobuf/io/coded_stream.h +++ b/src/google/protobuf/io/coded_stream.h @@ -110,6 +110,7 @@ #define GOOGLE_PROTOBUF_IO_CODED_STREAM_H__ #include <assert.h> +#include <atomic> #include <climits> #include <string> #include <utility> @@ -131,7 +132,6 @@ #define PROTOBUF_LITTLE_ENDIAN 1 #endif #endif -#include <google/protobuf/stubs/atomicops.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/port.h> @@ -829,7 +829,7 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { // canonicalization specification and implement the serializer using // reflection APIs rather than relying on this API. // - // If determinisitc serialization is requested, the serializer will + // If deterministic serialization is requested, the serializer will // sort map entries by keys in lexicographical order or numerical order. // (This is an implementation detail and may subject to change.) // @@ -840,21 +840,18 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { // Otherwise, SetSerializationDeterministic has been called, and the last // value passed to it is all that matters. void SetSerializationDeterministic(bool value) { - serialization_deterministic_is_overridden_ = true; - serialization_deterministic_override_ = value; + is_serialization_deterministic_ = value; } // See above. Also, note that users of this CodedOutputStream may need to // call IsSerializationDeterministic() to serialize in the intended way. This // CodedOutputStream cannot enforce a desire for deterministic serialization // by itself. bool IsSerializationDeterministic() const { - return serialization_deterministic_is_overridden_ ? - serialization_deterministic_override_ : - IsDefaultSerializationDeterministic(); + return is_serialization_deterministic_; } static bool IsDefaultSerializationDeterministic() { - return google::protobuf::internal::NoBarrier_Load(&default_serialization_deterministic_); + return default_serialization_deterministic_.load(std::memory_order_relaxed) != 0; } private: @@ -866,12 +863,8 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { int total_bytes_; // Sum of sizes of all buffers seen so far. bool had_error_; // Whether an error occurred during output. bool aliasing_enabled_; // See EnableAliasing(). - // See SetSerializationDeterministic() regarding these three fields. - bool serialization_deterministic_is_overridden_; - bool serialization_deterministic_override_; - // Conceptually, default_serialization_deterministic_ is an atomic bool. - // TODO(haberman): replace with std::atomic<bool> when we move to C++11. - static google::protobuf::internal::AtomicWord default_serialization_deterministic_; + bool is_serialization_deterministic_; + static std::atomic<bool> default_serialization_deterministic_; // Advance the buffer by a given number of bytes. void Advance(int amount); @@ -898,7 +891,7 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { // thread has done so. friend void ::google::protobuf::internal::MapTestForceDeterministic(); static void SetDefaultSerializationDeterministic() { - google::protobuf::internal::NoBarrier_Store(&default_serialization_deterministic_, 1); + default_serialization_deterministic_.store(true, std::memory_order_relaxed); } }; diff --git a/src/google/protobuf/io/coded_stream_unittest.cc b/src/google/protobuf/io/coded_stream_unittest.cc index 96f91ae9..1c8d3272 100644 --- a/src/google/protobuf/io/coded_stream_unittest.cc +++ b/src/google/protobuf/io/coded_stream_unittest.cc @@ -35,9 +35,6 @@ // This file contains tests and benchmarks. #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <vector> #include <google/protobuf/io/coded_stream.h> @@ -737,7 +734,7 @@ TEST_F(CodedStreamTest, ReadStringImpossiblyLargeFromStringOnStack) { } TEST_F(CodedStreamTest, ReadStringImpossiblyLargeFromStringOnHeap) { - google::protobuf::scoped_array<uint8> buffer(new uint8[8]); + std::unique_ptr<uint8[]> buffer(new uint8[8]); CodedInputStream coded_input(buffer.get(), 8); string str; EXPECT_FALSE(coded_input.ReadString(&str, 1 << 30)); diff --git a/src/google/protobuf/io/printer.cc b/src/google/protobuf/io/printer.cc index 8493268d..de67cef1 100644 --- a/src/google/protobuf/io/printer.cc +++ b/src/google/protobuf/io/printer.cc @@ -350,10 +350,12 @@ void Printer::CopyToBuffer(const char* data, int size) { while (size > buffer_size_) { // Data exceeds space in the buffer. Copy what we can and request a // new buffer. - memcpy(buffer_, data, buffer_size_); - offset_ += buffer_size_; - data += buffer_size_; - size -= buffer_size_; + if (buffer_size_ > 0) { + memcpy(buffer_, data, buffer_size_); + offset_ += buffer_size_; + data += buffer_size_; + size -= buffer_size_; + } void* void_buffer; failed_ = !output_->Next(&void_buffer, &buffer_size_); if (failed_) return; diff --git a/src/google/protobuf/io/zero_copy_stream_impl_lite.h b/src/google/protobuf/io/zero_copy_stream_impl_lite.h index ab0fd5ac..29f63bf0 100644 --- a/src/google/protobuf/io/zero_copy_stream_impl_lite.h +++ b/src/google/protobuf/io/zero_copy_stream_impl_lite.h @@ -45,9 +45,6 @@ #define GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__ #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <string> #include <iosfwd> #include <google/protobuf/io/zero_copy_stream.h> @@ -239,7 +236,7 @@ class LIBPROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream // Data is read into this buffer. It may be NULL if no buffer is currently // in use. Otherwise, it points to an array of size buffer_size_. - google::protobuf::scoped_array<uint8> buffer_; + std::unique_ptr<uint8[]> buffer_; const int buffer_size_; // Number of valid bytes currently in the buffer (i.e. the size last @@ -328,7 +325,7 @@ class LIBPROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStrea // Data is written from this buffer. It may be NULL if no buffer is // currently in use. Otherwise, it points to an array of size buffer_size_. - google::protobuf::scoped_array<uint8> buffer_; + std::unique_ptr<uint8[]> buffer_; const int buffer_size_; // Number of valid bytes currently in the buffer (i.e. the size last diff --git a/src/google/protobuf/io/zero_copy_stream_unittest.cc b/src/google/protobuf/io/zero_copy_stream_unittest.cc index 91792f18..08de8cb1 100644 --- a/src/google/protobuf/io/zero_copy_stream_unittest.cc +++ b/src/google/protobuf/io/zero_copy_stream_unittest.cc @@ -56,9 +56,6 @@ #include <fcntl.h> #include <errno.h> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <sstream> #include <google/protobuf/testing/file.h> @@ -206,7 +203,7 @@ void IoTest::WriteString(ZeroCopyOutputStream* output, const string& str) { } void IoTest::ReadString(ZeroCopyInputStream* input, const string& str) { - google::protobuf::scoped_array<char> buffer(new char[str.size() + 1]); + std::unique_ptr<char[]> buffer(new char[str.size() + 1]); buffer[str.size()] = '\0'; EXPECT_EQ(ReadFromInput(input, buffer.get(), str.size()), str.size()); EXPECT_STREQ(str.c_str(), buffer.get()); diff --git a/src/google/protobuf/lite_arena_unittest.cc b/src/google/protobuf/lite_arena_unittest.cc index dadaffb6..3e88314d 100644 --- a/src/google/protobuf/lite_arena_unittest.cc +++ b/src/google/protobuf/lite_arena_unittest.cc @@ -30,7 +30,6 @@ #include <google/protobuf/arena_test_util.h> #include <google/protobuf/map_lite_test_util.h> -#include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> namespace google { @@ -49,7 +48,7 @@ class LiteArenaTest : public testing::Test { google::protobuf::Arena::CreateArray<char>(arena_.get(), 1); } - google::protobuf::scoped_ptr<Arena> arena_; + std::unique_ptr<Arena> arena_; }; TEST_F(LiteArenaTest, MapNoHeapAllocation) { diff --git a/src/google/protobuf/lite_unittest.cc b/src/google/protobuf/lite_unittest.cc index d6693963..b42a7b14 100644 --- a/src/google/protobuf/lite_unittest.cc +++ b/src/google/protobuf/lite_unittest.cc @@ -621,7 +621,7 @@ TEST(Lite, AllLite28) { google::protobuf::MapLiteTestUtil::SetMapFields(&message1); int size = message1.ByteSize(); data.resize(size); - ::google::protobuf::uint8* start = reinterpret_cast< ::google::protobuf::uint8*>(::google::protobuf::string_as_array(&data)); + ::google::protobuf::uint8* start = reinterpret_cast<::google::protobuf::uint8*>(::google::protobuf::string_as_array(&data)); ::google::protobuf::uint8* end = message1.SerializeWithCachedSizesToArray(start); EXPECT_EQ(size, end - start); EXPECT_TRUE(message2.ParseFromString(data)); @@ -1003,3 +1003,34 @@ TEST(Lite, AllLite45) { EXPECT_EQ(serialized.substr(0, 2), data); EXPECT_EQ(serialized.substr(2), data); } + +// The following two tests check for wire compatibility between packed and +// unpacked repeated fields. There used to be a bug in the generated parsing +// code that caused us to calculate the highest possible tag number without +// taking into account that a repeated field might not be in the packed (or +// unpacked) state we expect. These tests specifically check for that issue by +// making sure we can parse repeated fields when the tag is higher than we would +// expect. +TEST(Lite, AllLite46) { + protobuf_unittest::PackedInt32 packed; + packed.add_repeated_int32(42); + string serialized; + ASSERT_TRUE(packed.SerializeToString(&serialized)); + + protobuf_unittest::NonPackedInt32 non_packed; + ASSERT_TRUE(non_packed.ParseFromString(serialized)); + ASSERT_EQ(1, non_packed.repeated_int32_size()); + EXPECT_EQ(42, non_packed.repeated_int32(0)); +} + +TEST(Lite, AllLite47) { + protobuf_unittest::NonPackedFixed32 non_packed; + non_packed.add_repeated_fixed32(42); + string serialized; + ASSERT_TRUE(non_packed.SerializeToString(&serialized)); + + protobuf_unittest::PackedFixed32 packed; + ASSERT_TRUE(packed.ParseFromString(serialized)); + ASSERT_EQ(1, packed.repeated_fixed32_size()); + EXPECT_EQ(42, packed.repeated_fixed32(0)); +} diff --git a/src/google/protobuf/map.h b/src/google/protobuf/map.h index a75fb786..6463ac2e 100644 --- a/src/google/protobuf/map.h +++ b/src/google/protobuf/map.h @@ -37,6 +37,7 @@ #ifndef GOOGLE_PROTOBUF_MAP_H__ #define GOOGLE_PROTOBUF_MAP_H__ +#include <initializer_list> #include <iterator> #include <limits> // To support Visual Studio 2008 #include <set> @@ -48,10 +49,6 @@ #include <google/protobuf/map_type_handler.h> #include <google/protobuf/stubs/hash.h> -#if LANG_CXX11 -#include <initializer_list> -#endif - namespace google { namespace protobuf { @@ -146,7 +143,6 @@ class Map { insert(other.begin(), other.end()); } -#if LANG_CXX11 Map(Map&& other) noexcept : Map() { if (other.arena_) { *this = other; @@ -164,7 +160,6 @@ class Map { } return *this; } -#endif template <class InputIt> Map(const InputIt& first, const InputIt& last) @@ -1117,11 +1112,9 @@ class Map { } } } -#if LANG_CXX11 void insert(std::initializer_list<value_type> values) { insert(values.begin(), values.end()); } -#endif // Erase and clear size_type erase(const key_type& key) { diff --git a/src/google/protobuf/map_entry_lite.h b/src/google/protobuf/map_entry_lite.h index 1646ce43..85a0bed7 100644 --- a/src/google/protobuf/map_entry_lite.h +++ b/src/google/protobuf/map_entry_lite.h @@ -33,6 +33,7 @@ #include <assert.h> +#include <google/protobuf/stubs/casts.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/map.h> @@ -201,8 +202,7 @@ class MapEntryImpl : public Base { return false; } set_has_key(); - if (!input->ExpectTag(kValueTag)) break; - GOOGLE_FALLTHROUGH_INTENDED; + break; case kValueTag: if (!ValueTypeHandler::Read(input, mutable_value())) { @@ -355,9 +355,9 @@ class MapEntryImpl : public Base { // We could use memcmp here, but we don't bother. The tag is one byte. GOOGLE_COMPILE_ASSERT(kTagSize == 1, tag_size_error); if (size > 0 && *reinterpret_cast<const char*>(data) == kValueTag) { - typename Map::size_type size = map_->size(); + typename Map::size_type map_size = map_->size(); value_ptr_ = &(*map_)[key_]; - if (GOOGLE_PREDICT_TRUE(size != map_->size())) { + if (GOOGLE_PREDICT_TRUE(map_size != map_->size())) { // We created a new key-value pair. Fill in the value. typedef typename MapIf<ValueTypeHandler::kIsEnum, int*, Value*>::type T; @@ -432,7 +432,7 @@ class MapEntryImpl : public Base { Value* value_ptr_; // On the fast path entry_ is not used. And, when entry_ is used, it's set // to mf_->NewEntry(), so in the arena case we must call entry_.release. - google::protobuf::scoped_ptr<MapEntryImpl> entry_; + std::unique_ptr<MapEntryImpl> entry_; }; protected: @@ -604,7 +604,7 @@ template <> struct FromHelper<WireFormatLite::TYPE_STRING> { static ArenaStringPtr From(const string& x) { ArenaStringPtr res; - TaggedPtr< ::std::string> ptr; + TaggedPtr<::std::string> ptr; ptr.Set(const_cast<string*>(&x)); res.UnsafeSetTaggedPointer(ptr); return res; @@ -614,7 +614,7 @@ template <> struct FromHelper<WireFormatLite::TYPE_BYTES> { static ArenaStringPtr From(const string& x) { ArenaStringPtr res; - TaggedPtr< ::std::string> ptr; + TaggedPtr<::std::string> ptr; ptr.Set(const_cast<string*>(&x)); res.UnsafeSetTaggedPointer(ptr); return res; diff --git a/src/google/protobuf/map_field.cc b/src/google/protobuf/map_field.cc index ec4f83e1..ac29c7e9 100644 --- a/src/google/protobuf/map_field.cc +++ b/src/google/protobuf/map_field.cc @@ -43,14 +43,14 @@ MapFieldBase::~MapFieldBase() { const RepeatedPtrFieldBase& MapFieldBase::GetRepeatedField() const { SyncRepeatedFieldWithMap(); - return *reinterpret_cast< ::google::protobuf::internal::RepeatedPtrFieldBase*>( + return *reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>( repeated_field_); } RepeatedPtrFieldBase* MapFieldBase::MutableRepeatedField() { SyncRepeatedFieldWithMap(); SetRepeatedDirty(); - return reinterpret_cast< ::google::protobuf::internal::RepeatedPtrFieldBase*>( + return reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>( repeated_field_); } @@ -72,29 +72,39 @@ size_t MapFieldBase::SpaceUsedExcludingSelfNoLock() const { bool MapFieldBase::IsMapValid() const { // "Acquire" insures the operation after SyncRepeatedFieldWithMap won't get // executed before state_ is checked. - Atomic32 state = google::protobuf::internal::Acquire_Load(&state_); + int state = state_.load(std::memory_order_acquire); return state != STATE_MODIFIED_REPEATED; } -void MapFieldBase::SetMapDirty() { state_ = STATE_MODIFIED_MAP; } +bool MapFieldBase::IsRepeatedFieldValid() const { + int state = state_.load(std::memory_order_acquire); + return state != STATE_MODIFIED_MAP; +} + +void MapFieldBase::SetMapDirty() { + // These are called by (non-const) mutator functions. So by our API it's the + // callers responsibility to have these calls properly ordered. + state_.store(STATE_MODIFIED_MAP, std::memory_order_relaxed); +} -void MapFieldBase::SetRepeatedDirty() { state_ = STATE_MODIFIED_REPEATED; } +void MapFieldBase::SetRepeatedDirty() { + // These are called by (non-const) mutator functions. So by our API it's the + // callers responsibility to have these calls properly ordered. + state_.store(STATE_MODIFIED_REPEATED, std::memory_order_relaxed); +} void* MapFieldBase::MutableRepeatedPtrField() const { return repeated_field_; } void MapFieldBase::SyncRepeatedFieldWithMap() const { - // "Acquire" insures the operation after SyncRepeatedFieldWithMap won't get - // executed before state_ is checked. - Atomic32 state = google::protobuf::internal::Acquire_Load(&state_); - if (state == STATE_MODIFIED_MAP) { + // acquire here matches with release below to ensure that we can only see a + // value of CLEAN after all previous changes have been synced. + if (state_.load(std::memory_order_acquire) == STATE_MODIFIED_MAP) { mutex_.Lock(); // Double check state, because another thread may have seen the same state // and done the synchronization before the current thread. - if (state_ == STATE_MODIFIED_MAP) { + if (state_.load(std::memory_order_relaxed) == STATE_MODIFIED_MAP) { SyncRepeatedFieldWithMapNoLock(); - // "Release" insures state_ can only be changed "after" - // SyncRepeatedFieldWithMapNoLock is finished. - google::protobuf::internal::Release_Store(&state_, CLEAN); + state_.store(CLEAN, std::memory_order_release); } mutex_.Unlock(); } @@ -107,18 +117,15 @@ void MapFieldBase::SyncRepeatedFieldWithMapNoLock() const { } void MapFieldBase::SyncMapWithRepeatedField() const { - // "Acquire" insures the operation after SyncMapWithRepeatedField won't get - // executed before state_ is checked. - Atomic32 state = google::protobuf::internal::Acquire_Load(&state_); - if (state == STATE_MODIFIED_REPEATED) { + // acquire here matches with release below to ensure that we can only see a + // value of CLEAN after all previous changes have been synced. + if (state_.load(std::memory_order_acquire) == STATE_MODIFIED_REPEATED) { mutex_.Lock(); // Double check state, because another thread may have seen the same state // and done the synchronization before the current thread. - if (state_ == STATE_MODIFIED_REPEATED) { + if (state_.load(std::memory_order_relaxed) == STATE_MODIFIED_REPEATED) { SyncMapWithRepeatedFieldNoLock(); - // "Release" insures state_ can only be changed "after" - // SyncRepeatedFieldWithMapNoLock is finished. - google::protobuf::internal::Release_Store(&state_, CLEAN); + state_.store(CLEAN, std::memory_order_release); } mutex_.Unlock(); } diff --git a/src/google/protobuf/map_field.h b/src/google/protobuf/map_field.h index 6c75a6da..494401e1 100644 --- a/src/google/protobuf/map_field.h +++ b/src/google/protobuf/map_field.h @@ -31,7 +31,8 @@ #ifndef GOOGLE_PROTOBUF_MAP_FIELD_H__ #define GOOGLE_PROTOBUF_MAP_FIELD_H__ -#include <google/protobuf/stubs/atomicops.h> +#include <atomic> + #include <google/protobuf/stubs/mutex.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/generated_message_reflection.h> @@ -86,6 +87,8 @@ class LIBPROTOBUF_EXPORT MapFieldBase { virtual bool ContainsMapKey(const MapKey& map_key) const = 0; virtual bool InsertOrLookupMapValue( const MapKey& map_key, MapValueRef* val) = 0; + // Returns whether changes to the map are reflected in the repeated field. + bool IsRepeatedFieldValid() const; // Insures operations after won't get executed before calling this. bool IsMapValid() const; virtual bool DeleteMapValue(const MapKey& map_key) = 0; @@ -140,9 +143,7 @@ class LIBPROTOBUF_EXPORT MapFieldBase { mutable Mutex mutex_; // The thread to synchronize map and repeated field // needs to get lock first; - mutable volatile Atomic32 state_; // 0: STATE_MODIFIED_MAP - // 1: STATE_MODIFIED_REPEATED - // 2: CLEAN + mutable std::atomic<State> state_; private: friend class ContendedMapCleanTest; @@ -814,13 +815,13 @@ struct hash<google::protobuf::MapKey> { case google::protobuf::FieldDescriptor::CPPTYPE_STRING: return hash<string>()(map_key.GetStringValue()); case google::protobuf::FieldDescriptor::CPPTYPE_INT64: - return hash< ::google::protobuf::int64>()(map_key.GetInt64Value()); + return hash<::google::protobuf::int64>()(map_key.GetInt64Value()); case google::protobuf::FieldDescriptor::CPPTYPE_INT32: - return hash< ::google::protobuf::int32>()(map_key.GetInt32Value()); + return hash<::google::protobuf::int32>()(map_key.GetInt32Value()); case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: - return hash< ::google::protobuf::uint64>()(map_key.GetUInt64Value()); + return hash<::google::protobuf::uint64>()(map_key.GetUInt64Value()); case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: - return hash< ::google::protobuf::uint32>()(map_key.GetUInt32Value()); + return hash<::google::protobuf::uint32>()(map_key.GetUInt32Value()); case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: return hash<bool>()(map_key.GetBoolValue()); } diff --git a/src/google/protobuf/map_field_inl.h b/src/google/protobuf/map_field_inl.h index e317b5ed..d0517792 100644 --- a/src/google/protobuf/map_field_inl.h +++ b/src/google/protobuf/map_field_inl.h @@ -32,10 +32,8 @@ #define GOOGLE_PROTOBUF_MAP_FIELD_INL_H__ #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif +#include <google/protobuf/stubs/casts.h> #include <google/protobuf/map.h> #include <google/protobuf/map_field.h> #include <google/protobuf/map_type_handler.h> @@ -254,7 +252,11 @@ void MapField<Derived, Key, T, kKeyFieldType, kValueFieldType, default_enum_value>::Swap(MapField* other) { std::swap(this->MapFieldBase::repeated_field_, other->repeated_field_); impl_.Swap(&other->impl_); - std::swap(this->MapFieldBase::state_, other->state_); + // a relaxed swap of the atomic + auto other_state = other->state_.load(std::memory_order_relaxed); + auto this_state = this->MapFieldBase::state_.load(std::memory_order_relaxed); + other->state_.store(this_state, std::memory_order_relaxed); + this->MapFieldBase::state_.store(other_state, std::memory_order_relaxed); } template <typename Derived, typename Key, typename T, diff --git a/src/google/protobuf/map_field_test.cc b/src/google/protobuf/map_field_test.cc index 4e0e751c..f58d59e5 100644 --- a/src/google/protobuf/map_field_test.cc +++ b/src/google/protobuf/map_field_test.cc @@ -30,9 +30,6 @@ #include <map> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> @@ -71,10 +68,18 @@ class MapFieldBaseStub : public MapFieldBase { RepeatedPtrField<Message>* InternalRepeatedField() { return repeated_field_; } - bool IsMapClean() { return state_ != 0; } - bool IsRepeatedClean() { return state_ != 1; } - void SetMapDirty() { state_ = 0; } - void SetRepeatedDirty() { state_ = 1; } + bool IsMapClean() { + return state_.load(std::memory_order_relaxed) != STATE_MODIFIED_MAP; + } + bool IsRepeatedClean() { + return state_.load(std::memory_order_relaxed) != STATE_MODIFIED_REPEATED; + } + void SetMapDirty() { + state_.store(STATE_MODIFIED_MAP, std::memory_order_relaxed); + } + void SetRepeatedDirty() { + state_.store(STATE_MODIFIED_REPEATED, std::memory_order_relaxed); + } bool ContainsMapKey(const MapKey& map_key) const { return false; } @@ -124,7 +129,7 @@ class MapFieldBasePrimitiveTest : public ::testing::Test { EXPECT_EQ(2, map_->size()); } - google::protobuf::scoped_ptr<MapFieldType> map_field_; + std::unique_ptr<MapFieldType> map_field_; MapFieldBase* map_field_base_; Map<int32, int32>* map_; const Descriptor* map_descriptor_; @@ -291,7 +296,7 @@ class MapFieldStateTest } } - google::protobuf::scoped_ptr<MapFieldType> map_field_; + std::unique_ptr<MapFieldType> map_field_; MapFieldBase* map_field_base_; State state_; }; diff --git a/src/google/protobuf/map_test.cc b/src/google/protobuf/map_test.cc index d59f92d2..829a60ff 100644 --- a/src/google/protobuf/map_test.cc +++ b/src/google/protobuf/map_test.cc @@ -40,9 +40,6 @@ #include <google/protobuf/stubs/hash.h> #include <map> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <set> #include <sstream> #include <vector> @@ -170,7 +167,7 @@ class MapImplTest : public ::testing::Test { EXPECT_EQ(value, const_it_copy->second); } - google::protobuf::scoped_ptr<Map<int32, int32> > map_ptr_; + std::unique_ptr<Map<int32, int32> > map_ptr_; Map<int32, int32>& map_; const Map<int32, int32>& const_map_; }; @@ -676,7 +673,6 @@ TEST_F(MapImplTest, InsertByIterator) { ExpectElements(map1); } -#if LANG_CXX11 TEST_F(MapImplTest, InsertByInitializerList) { map_.insert({{1, 100}, {2, 200}}); ExpectElements({{1, 100}, {2, 200}}); @@ -684,7 +680,6 @@ TEST_F(MapImplTest, InsertByInitializerList) { map_.insert({{2, 201}, {3, 301}}); ExpectElements({{1, 100}, {2, 200}, {3, 301}}); } -#endif TEST_F(MapImplTest, EraseSingleByKey) { int32 key = 0; @@ -1269,19 +1264,19 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) { &message, fd_map_int32_foreign_message); // Get entry default instances - google::protobuf::scoped_ptr<Message> entry_int32_int32( + std::unique_ptr<Message> entry_int32_int32( MessageFactory::generated_factory() ->GetPrototype(fd_map_int32_int32->message_type()) ->New()); - google::protobuf::scoped_ptr<Message> entry_int32_double( + std::unique_ptr<Message> entry_int32_double( MessageFactory::generated_factory() ->GetPrototype(fd_map_int32_double->message_type()) ->New()); - google::protobuf::scoped_ptr<Message> entry_string_string( + std::unique_ptr<Message> entry_string_string( MessageFactory::generated_factory() ->GetPrototype(fd_map_string_string->message_type()) ->New()); - google::protobuf::scoped_ptr<Message> entry_int32_foreign_message( + std::unique_ptr<Message> entry_int32_foreign_message( MessageFactory::generated_factory() ->GetPrototype(fd_map_int32_foreign_message->message_type()) ->New()); @@ -1819,7 +1814,7 @@ TEST_F(MapFieldReflectionTest, MapSizeWithDuplicatedKey) { // Dynamic Message { DynamicMessageFactory factory; - google::protobuf::scoped_ptr<Message> message( + std::unique_ptr<Message> message( factory.GetPrototype(unittest::TestMap::descriptor())->New()); const Reflection* reflection = message->GetReflection(); const FieldDescriptor* field = @@ -1836,6 +1831,7 @@ TEST_F(MapFieldReflectionTest, MapSizeWithDuplicatedKey) { EXPECT_EQ(2, reflection->FieldSize(*message, field)); EXPECT_EQ(1, MapSize(reflection, field, *message)); + EXPECT_EQ(2, reflection->FieldSize(*message, field)); } // Generated Message @@ -2004,7 +2000,7 @@ TEST(GeneratedMapFieldTest, CopyFromDynamicMessage) { // Construct a new version of the dynamic message via the factory. DynamicMessageFactory factory; - google::protobuf::scoped_ptr<Message> message1; + std::unique_ptr<Message> message1; message1.reset( factory.GetPrototype(unittest::TestMap::descriptor())->New()); MapReflectionTester reflection_tester( @@ -2021,7 +2017,7 @@ TEST(GeneratedMapFieldTest, CopyFromDynamicMessageMapReflection) { // Construct a new version of the dynamic message via the factory. DynamicMessageFactory factory; - google::protobuf::scoped_ptr<Message> message1; + std::unique_ptr<Message> message1; message1.reset( factory.GetPrototype(unittest::TestMap::descriptor())->New()); MapReflectionTester reflection_tester( @@ -2040,7 +2036,7 @@ TEST(GeneratedMapFieldTest, DynamicMessageCopyFrom) { // Construct a new version of the dynamic message via the factory. DynamicMessageFactory factory; - google::protobuf::scoped_ptr<Message> message1; + std::unique_ptr<Message> message1; message1.reset( factory.GetPrototype(unittest::TestMap::descriptor())->New()); @@ -2059,7 +2055,7 @@ TEST(GeneratedMapFieldTest, DynamicMessageCopyFromMapReflection) { // Construct a dynamic message via the factory. DynamicMessageFactory factory; - google::protobuf::scoped_ptr<Message> message1; + std::unique_ptr<Message> message1; message1.reset( factory.GetPrototype(unittest::TestMap::descriptor())->New()); @@ -2073,7 +2069,7 @@ TEST(GeneratedMapFieldTest, SyncDynamicMapWithRepeatedField) { MapReflectionTester reflection_tester( unittest::TestMap::descriptor()); DynamicMessageFactory factory; - google::protobuf::scoped_ptr<Message> message; + std::unique_ptr<Message> message; message.reset( factory.GetPrototype(unittest::TestMap::descriptor())->New()); reflection_tester.SetMapFieldsViaReflection(message.get()); @@ -2725,7 +2721,7 @@ TEST_F(MapFieldInDynamicMessageTest, MapIndependentOffsets) { // Check that all fields have independent offsets by setting each // one to a unique value then checking that they all still have those // unique values (i.e. they don't stomp each other). - google::protobuf::scoped_ptr<Message> message(map_prototype_->New()); + std::unique_ptr<Message> message(map_prototype_->New()); MapReflectionTester reflection_tester(map_descriptor_); reflection_tester.SetMapFieldsViaReflection(message.get()); @@ -2734,7 +2730,7 @@ TEST_F(MapFieldInDynamicMessageTest, MapIndependentOffsets) { TEST_F(MapFieldInDynamicMessageTest, DynamicMapReflection) { // Check that map fields work properly. - google::protobuf::scoped_ptr<Message> message(map_prototype_->New()); + std::unique_ptr<Message> message(map_prototype_->New()); // Check set functions. MapReflectionTester reflection_tester(map_descriptor_); @@ -2748,7 +2744,7 @@ TEST_F(MapFieldInDynamicMessageTest, MapSpaceUsed) { // Since we share the implementation with generated messages, we don't need // to test very much here. Just make sure it appears to be working. - google::protobuf::scoped_ptr<Message> message(map_prototype_->New()); + std::unique_ptr<Message> message(map_prototype_->New()); MapReflectionTester reflection_tester(map_descriptor_); int initial_space_used = message->SpaceUsed(); @@ -2761,13 +2757,13 @@ TEST_F(MapFieldInDynamicMessageTest, RecursiveMap) { TestRecursiveMapMessage from; (*from.mutable_a())[""]; string data = from.SerializeAsString(); - google::protobuf::scoped_ptr<Message> to( + std::unique_ptr<Message> to( factory_.GetPrototype(recursive_map_descriptor_)->New()); ASSERT_TRUE(to->ParseFromString(data)); } TEST_F(MapFieldInDynamicMessageTest, MapValueReferernceValidAfterSerialize) { - google::protobuf::scoped_ptr<Message> message(map_prototype_->New()); + std::unique_ptr<Message> message(map_prototype_->New()); MapReflectionTester reflection_tester(map_descriptor_); reflection_tester.SetMapFieldsViaMapReflection(message.get()); @@ -2798,7 +2794,7 @@ TEST_F(MapFieldInDynamicMessageTest, MapValueReferernceValidAfterSerialize) { } TEST_F(MapFieldInDynamicMessageTest, MapEntryReferernceValidAfterSerialize) { - google::protobuf::scoped_ptr<Message> message(map_prototype_->New()); + std::unique_ptr<Message> message(map_prototype_->New()); MapReflectionTester reflection_tester(map_descriptor_); reflection_tester.SetMapFieldsViaReflection(message.get()); @@ -2967,7 +2963,7 @@ TEST(WireFormatForMapFieldTest, SerializeMap) { TEST(WireFormatForMapFieldTest, SerializeMapDynamicMessage) { DynamicMessageFactory factory; - google::protobuf::scoped_ptr<Message> dynamic_message; + std::unique_ptr<Message> dynamic_message; dynamic_message.reset( factory.GetPrototype(unittest::TestMap::descriptor())->New()); MapReflectionTester reflection_tester( @@ -3293,7 +3289,6 @@ TEST(ArenaTest, IsInitialized) { EXPECT_EQ(0, (*message->mutable_map_int32_int32())[0]); } -#if LANG_CXX11 TEST(MoveTest, MoveConstructorWorks) { Map<int32, TestAllTypes> original_map; original_map[42].mutable_optional_nested_message()->set_bb(42); @@ -3329,7 +3324,6 @@ TEST(MoveTest, MoveAssignmentWorks) { EXPECT_EQ(nested_msg42_ptr, &moved_to_map[42].optional_nested_message()); EXPECT_EQ(nested_msg43_ptr, &moved_to_map[43].optional_nested_message()); } -#endif } // namespace internal } // namespace protobuf diff --git a/src/google/protobuf/message.cc b/src/google/protobuf/message.cc index 42ec0337..810db233 100644 --- a/src/google/protobuf/message.cc +++ b/src/google/protobuf/message.cc @@ -38,20 +38,22 @@ #include <google/protobuf/message.h> +#include <google/protobuf/stubs/casts.h> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/mutex.h> #include <google/protobuf/stubs/once.h> +#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/reflection_internal.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> -#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/map_field.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> + #include <google/protobuf/stubs/map_util.h> #include <google/protobuf/stubs/singleton.h> #include <google/protobuf/stubs/stl_util.h> diff --git a/src/google/protobuf/message.h b/src/google/protobuf/message.h index fc630b58..f3d1a58a 100644 --- a/src/google/protobuf/message.h +++ b/src/google/protobuf/message.h @@ -112,7 +112,7 @@ #include <iosfwd> #include <string> -#include <google/protobuf/stubs/type_traits.h> +#include <type_traits> #include <vector> #include <google/protobuf/arena.h> @@ -342,7 +342,7 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite { // // This method remains virtual in case a subclass does not implement // reflection and wants to override the default behavior. - virtual const Reflection* GetReflection() const PROTOBUF_FINAL { + virtual const Reflection* GetReflection() const final { return GetMetadata().reflection; } diff --git a/src/google/protobuf/message_lite.cc b/src/google/protobuf/message_lite.cc index 123b142d..65af7cea 100644 --- a/src/google/protobuf/message_lite.cc +++ b/src/google/protobuf/message_lite.cc @@ -316,7 +316,11 @@ bool MessageLite::SerializeToArray(void* data, int size) const { } bool MessageLite::SerializePartialToArray(void* data, int size) const { - int byte_size = ByteSizeLong(); + size_t byte_size = ByteSizeLong(); + if (byte_size > INT_MAX) { + GOOGLE_LOG(ERROR) << "Exceeded maximum protobuf size of 2GB: " << size; + return false; + } if (size < byte_size) return false; uint8* start = reinterpret_cast<uint8*>(data); uint8* end = SerializeWithCachedSizesToArray(start); diff --git a/src/google/protobuf/message_lite.h b/src/google/protobuf/message_lite.h index 0b2b24b2..4cbec330 100644 --- a/src/google/protobuf/message_lite.h +++ b/src/google/protobuf/message_lite.h @@ -43,11 +43,11 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/once.h> +#include <google/protobuf/arena.h> #include <google/protobuf/stubs/port.h> namespace google { namespace protobuf { -class Arena; template <typename T> class RepeatedPtrField; namespace io { @@ -60,6 +60,7 @@ namespace internal { class RepeatedPtrFieldBase; class WireFormatLite; +class WeakFieldMap; #ifndef SWIG // We compute sizes as size_t but cache them as int. This function converts a @@ -113,13 +114,7 @@ class ExplicitlyConstructed { get_mutable()->~T(); } -#if LANG_CXX11 - constexpr -#endif - const T& - get() const { - return reinterpret_cast<const T&>(union_); - } + constexpr const T& get() const { return reinterpret_cast<const T&>(union_); } T* get_mutable() { return reinterpret_cast<T*>(&union_); } private: @@ -133,7 +128,7 @@ class ExplicitlyConstructed { // Default empty string object. Don't use this directly. Instead, call // GetEmptyString() to get the reference. -extern ExplicitlyConstructed< ::std::string> fixed_address_empty_string; +LIBPROTOBUF_EXPORT extern ExplicitlyConstructed<::std::string> fixed_address_empty_string; LIBPROTOBUF_EXPORT extern ProtobufOnceType empty_string_once_init_; LIBPROTOBUF_EXPORT void InitEmptyString(); @@ -274,7 +269,7 @@ class LIBPROTOBUF_EXPORT MessageLite { // Reads a protocol buffer from the stream and merges it into this - // Message. Singular fields read from the input overwrite what is + // Message. Singular fields read from the what is // already in the Message and repeated fields are appended to those // already present. // @@ -399,12 +394,18 @@ class LIBPROTOBUF_EXPORT MessageLite { return repeated; } + template <typename T> + static T* CreateMaybeMessage(Arena* arena) { + return Arena::CreateMaybeMessage<T>(arena); + } + private: // TODO(gerbens) make this a pure abstract function virtual const void* InternalGetTable() const { return NULL; } friend class internal::WireFormatLite; friend class Message; + friend class internal::WeakFieldMap; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageLite); }; diff --git a/src/google/protobuf/message_unittest.cc b/src/google/protobuf/message_unittest.cc index a27036e7..45b46bee 100644 --- a/src/google/protobuf/message_unittest.cc +++ b/src/google/protobuf/message_unittest.cc @@ -32,542 +32,20 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/message.h> - -#include <sys/types.h> -#include <sys/stat.h> -#include <fcntl.h> -#ifndef _MSC_VER -#include <unistd.h> -#endif -#include <sstream> -#include <fstream> - -#include <google/protobuf/test_util.h> #include <google/protobuf/unittest.pb.h> -#include <google/protobuf/io/coded_stream.h> -#include <google/protobuf/io/zero_copy_stream.h> -#include <google/protobuf/io/zero_copy_stream_impl.h> -#include <google/protobuf/descriptor.pb.h> -#include <google/protobuf/arena.h> -#include <google/protobuf/descriptor.h> -#include <google/protobuf/generated_message_reflection.h> -#include <google/protobuf/stubs/logging.h> -#include <google/protobuf/stubs/common.h> -#include <google/protobuf/stubs/logging.h> -#include <google/protobuf/testing/googletest.h> -#include <gtest/gtest.h> -#include <google/protobuf/stubs/io_win32.h> +#define MESSAGE_TEST_NAME MessageTest +#define MESSAGE_FACTORY_TEST_NAME MessageFactoryTest +#define UNITTEST_PACKAGE_NAME "protobuf_unittest" +#define UNITTEST ::protobuf_unittest +#define UNITTEST_IMPORT ::protobuf_unittest_import + +// Must include after the above macros. +#include <google/protobuf/test_util.inc> +#include <google/protobuf/message_unittest.inc> +// Make extract script happy. namespace google { namespace protobuf { - -#if defined(_WIN32) -// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import -// them like we do below. -using google::protobuf::internal::win32::close; -using google::protobuf::internal::win32::open; -#endif - -#ifndef O_BINARY -#ifdef _O_BINARY -#define O_BINARY _O_BINARY -#else -#define O_BINARY 0 // If this isn't defined, the platform doesn't need it. -#endif -#endif - -TEST(MessageTest, SerializeHelpers) { - // TODO(kenton): Test more helpers? They're all two-liners so it seems - // like a waste of time. - - protobuf_unittest::TestAllTypes message; - TestUtil::SetAllFields(&message); - std::stringstream stream; - - string str1("foo"); - string str2("bar"); - - EXPECT_TRUE(message.SerializeToString(&str1)); - EXPECT_TRUE(message.AppendToString(&str2)); - EXPECT_TRUE(message.SerializeToOstream(&stream)); - - EXPECT_EQ(str1.size() + 3, str2.size()); - EXPECT_EQ("bar", str2.substr(0, 3)); - // Don't use EXPECT_EQ because we don't want to dump raw binary data to - // stdout. - EXPECT_TRUE(str2.substr(3) == str1); - - // GCC gives some sort of error if we try to just do stream.str() == str1. - string temp = stream.str(); - EXPECT_TRUE(temp == str1); - - EXPECT_TRUE(message.SerializeAsString() == str1); - -} - -TEST(MessageTest, SerializeToBrokenOstream) { - std::ofstream out; - protobuf_unittest::TestAllTypes message; - message.set_optional_int32(123); - - EXPECT_FALSE(message.SerializeToOstream(&out)); -} - -TEST(MessageTest, ParseFromFileDescriptor) { - string filename = TestSourceDir() + - "/google/protobuf/testdata/golden_message"; - int file = open(filename.c_str(), O_RDONLY | O_BINARY); - ASSERT_GE(file, 0); - - protobuf_unittest::TestAllTypes message; - EXPECT_TRUE(message.ParseFromFileDescriptor(file)); - TestUtil::ExpectAllFieldsSet(message); - - EXPECT_GE(close(file), 0); -} - -TEST(MessageTest, ParsePackedFromFileDescriptor) { - string filename = - TestSourceDir() + - "/google/protobuf/testdata/golden_packed_fields_message"; - int file = open(filename.c_str(), O_RDONLY | O_BINARY); - ASSERT_GE(file, 0); - - protobuf_unittest::TestPackedTypes message; - EXPECT_TRUE(message.ParseFromFileDescriptor(file)); - TestUtil::ExpectPackedFieldsSet(message); - - EXPECT_GE(close(file), 0); -} - -TEST(MessageTest, ParseHelpers) { - // TODO(kenton): Test more helpers? They're all two-liners so it seems - // like a waste of time. - string data; - - { - // Set up. - protobuf_unittest::TestAllTypes message; - TestUtil::SetAllFields(&message); - message.SerializeToString(&data); - } - - { - // Test ParseFromString. - protobuf_unittest::TestAllTypes message; - EXPECT_TRUE(message.ParseFromString(data)); - TestUtil::ExpectAllFieldsSet(message); - } - - { - // Test ParseFromIstream. - protobuf_unittest::TestAllTypes message; - std::stringstream stream(data); - EXPECT_TRUE(message.ParseFromIstream(&stream)); - EXPECT_TRUE(stream.eof()); - TestUtil::ExpectAllFieldsSet(message); - } - - { - // Test ParseFromBoundedZeroCopyStream. - string data_with_junk(data); - data_with_junk.append("some junk on the end"); - io::ArrayInputStream stream(data_with_junk.data(), data_with_junk.size()); - protobuf_unittest::TestAllTypes message; - EXPECT_TRUE(message.ParseFromBoundedZeroCopyStream(&stream, data.size())); - TestUtil::ExpectAllFieldsSet(message); - } - - { - // Test that ParseFromBoundedZeroCopyStream fails (but doesn't crash) if - // EOF is reached before the expected number of bytes. - io::ArrayInputStream stream(data.data(), data.size()); - protobuf_unittest::TestAllTypes message; - EXPECT_FALSE( - message.ParseFromBoundedZeroCopyStream(&stream, data.size() + 1)); - } -} - -TEST(MessageTest, ParseFailsIfNotInitialized) { - unittest::TestRequired message; - std::vector<string> errors; - - { - ScopedMemoryLog log; - EXPECT_FALSE(message.ParseFromString("")); - errors = log.GetMessages(ERROR); - } - - ASSERT_EQ(1, errors.size()); - EXPECT_EQ("Can't parse message of type \"protobuf_unittest.TestRequired\" " - "because it is missing required fields: a, b, c", - errors[0]); -} - -TEST(MessageTest, BypassInitializationCheckOnParse) { - unittest::TestRequired message; - io::ArrayInputStream raw_input(NULL, 0); - io::CodedInputStream input(&raw_input); - EXPECT_TRUE(message.MergePartialFromCodedStream(&input)); -} - -TEST(MessageTest, InitializationErrorString) { - unittest::TestRequired message; - EXPECT_EQ("a, b, c", message.InitializationErrorString()); -} - -TEST(MessageTest, DynamicCastToGenerated) { - unittest::TestAllTypes test_all_types; - - google::protobuf::Message* test_all_types_pointer = &test_all_types; - EXPECT_EQ(&test_all_types, - google::protobuf::internal::DynamicCastToGenerated<unittest::TestAllTypes>( - test_all_types_pointer)); - EXPECT_EQ(NULL, - google::protobuf::internal::DynamicCastToGenerated<unittest::TestRequired>( - test_all_types_pointer)); - - const google::protobuf::Message* test_all_types_pointer_const = &test_all_types; - EXPECT_EQ( - &test_all_types, - google::protobuf::internal::DynamicCastToGenerated<const unittest::TestAllTypes>( - test_all_types_pointer_const)); - EXPECT_EQ( - NULL, - google::protobuf::internal::DynamicCastToGenerated<const unittest::TestRequired>( - test_all_types_pointer_const)); -} - -#ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet. - -TEST(MessageTest, SerializeFailsIfNotInitialized) { - unittest::TestRequired message; - string data; - EXPECT_DEBUG_DEATH(EXPECT_TRUE(message.SerializeToString(&data)), - "Can't serialize message of type \"protobuf_unittest.TestRequired\" because " - "it is missing required fields: a, b, c"); -} - -TEST(MessageTest, CheckInitialized) { - unittest::TestRequired message; - EXPECT_DEATH(message.CheckInitialized(), - "Message of type \"protobuf_unittest.TestRequired\" is missing required " - "fields: a, b, c"); -} - -#endif // PROTOBUF_HAS_DEATH_TEST - -namespace { -// An input stream that repeats a string's content for a number of times. It -// helps us create a really large input without consuming too much memory. Used -// to test the parsing behavior when the input size exceeds 2G or close to it. -class RepeatedInputStream : public io::ZeroCopyInputStream { - public: - RepeatedInputStream(const string& data, size_t count) - : data_(data), count_(count), position_(0), total_byte_count_(0) {} - - virtual bool Next(const void** data, int* size) { - if (position_ == data_.size()) { - if (--count_ == 0) { - return false; - } - position_ = 0; - } - *data = &data_[position_]; - *size = static_cast<int>(data_.size() - position_); - position_ = data_.size(); - total_byte_count_ += *size; - return true; - } - - virtual void BackUp(int count) { - position_ -= static_cast<size_t>(count); - total_byte_count_ -= count; - } - - virtual bool Skip(int count) { - while (count > 0) { - const void* data; - int size; - if (!Next(&data, &size)) { - break; - } - if (size >= count) { - BackUp(size - count); - return true; - } else { - count -= size; - } - } - return false; - } - - virtual int64 ByteCount() const { return total_byte_count_; } - - private: - string data_; - size_t count_; // The number of strings that haven't been consuemd. - size_t position_; // Position in the string for the next read. - int64 total_byte_count_; -}; -} // namespace - -TEST(MessageTest, TestParseMessagesCloseTo2G) { - // Create a message with a large string field. - string value = string(64 * 1024 * 1024, 'x'); - protobuf_unittest::TestAllTypes message; - message.set_optional_string(value); - - // Repeat this message in the input stream to make the total input size - // close to 2G. - string data = message.SerializeAsString(); - size_t count = static_cast<size_t>(kint32max) / data.size(); - RepeatedInputStream input(data, count); - - // The parsing should succeed. - protobuf_unittest::TestAllTypes result; - EXPECT_TRUE(result.ParseFromZeroCopyStream(&input)); - - // When there are multiple occurences of a singulr field, the last one - // should win. - EXPECT_EQ(value, result.optional_string()); -} - -TEST(MessageTest, TestParseMessagesOver2G) { - // Create a message with a large string field. - string value = string(64 * 1024 * 1024, 'x'); - protobuf_unittest::TestAllTypes message; - message.set_optional_string(value); - - // Repeat this message in the input stream to make the total input size - // larger than 2G. - string data = message.SerializeAsString(); - size_t count = static_cast<size_t>(kint32max) / data.size() + 1; - RepeatedInputStream input(data, count); - - // The parsing should fail. - protobuf_unittest::TestAllTypes result; - EXPECT_FALSE(result.ParseFromZeroCopyStream(&input)); -} - -TEST(MessageTest, BypassInitializationCheckOnSerialize) { - unittest::TestRequired message; - io::ArrayOutputStream raw_output(NULL, 0); - io::CodedOutputStream output(&raw_output); - EXPECT_TRUE(message.SerializePartialToCodedStream(&output)); -} - -TEST(MessageTest, FindInitializationErrors) { - unittest::TestRequired message; - std::vector<string> errors; - message.FindInitializationErrors(&errors); - ASSERT_EQ(3, errors.size()); - EXPECT_EQ("a", errors[0]); - EXPECT_EQ("b", errors[1]); - EXPECT_EQ("c", errors[2]); -} - -TEST(MessageTest, ParseFailsOnInvalidMessageEnd) { - unittest::TestAllTypes message; - - // Control case. - EXPECT_TRUE(message.ParseFromArray("", 0)); - - // The byte is a valid varint, but not a valid tag (zero). - EXPECT_FALSE(message.ParseFromArray("\0", 1)); - - // The byte is a malformed varint. - EXPECT_FALSE(message.ParseFromArray("\200", 1)); - - // The byte is an endgroup tag, but we aren't parsing a group. - EXPECT_FALSE(message.ParseFromArray("\014", 1)); -} - -// Regression test for b/23630858 -TEST(MessageTest, MessageIsStillValidAfterParseFails) { - unittest::TestAllTypes message; - - // 9 0xFFs for the "optional_uint64" field. - string invalid_data = "\x20\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"; - - EXPECT_FALSE(message.ParseFromString(invalid_data)); - message.Clear(); - EXPECT_EQ(0, message.optional_uint64()); - - // invalid data for field "optional_string". Length prefix is 1 but no - // payload. - string invalid_string_data = "\x72\x01"; - { - google::protobuf::Arena arena; - unittest::TestAllTypes* arena_message = - google::protobuf::Arena::CreateMessage<unittest::TestAllTypes>(&arena); - EXPECT_FALSE(arena_message->ParseFromString(invalid_string_data)); - arena_message->Clear(); - EXPECT_EQ("", arena_message->optional_string()); - } -} - - -namespace { - -void ExpectMessageMerged(const unittest::TestAllTypes& message) { - EXPECT_EQ(3, message.optional_int32()); - EXPECT_EQ(2, message.optional_int64()); - EXPECT_EQ("hello", message.optional_string()); -} - -void AssignParsingMergeMessages( - unittest::TestAllTypes* msg1, - unittest::TestAllTypes* msg2, - unittest::TestAllTypes* msg3) { - msg1->set_optional_int32(1); - msg2->set_optional_int64(2); - msg3->set_optional_int32(3); - msg3->set_optional_string("hello"); -} - -} // namespace - -// Test that if an optional or required message/group field appears multiple -// times in the input, they need to be merged. -TEST(MessageTest, ParsingMerge) { - unittest::TestParsingMerge::RepeatedFieldsGenerator generator; - unittest::TestAllTypes* msg1; - unittest::TestAllTypes* msg2; - unittest::TestAllTypes* msg3; - -#define ASSIGN_REPEATED_FIELD(FIELD) \ - msg1 = generator.add_##FIELD(); \ - msg2 = generator.add_##FIELD(); \ - msg3 = generator.add_##FIELD(); \ - AssignParsingMergeMessages(msg1, msg2, msg3) - - ASSIGN_REPEATED_FIELD(field1); - ASSIGN_REPEATED_FIELD(field2); - ASSIGN_REPEATED_FIELD(field3); - ASSIGN_REPEATED_FIELD(ext1); - ASSIGN_REPEATED_FIELD(ext2); - -#undef ASSIGN_REPEATED_FIELD -#define ASSIGN_REPEATED_GROUP(FIELD) \ - msg1 = generator.add_##FIELD()->mutable_field1(); \ - msg2 = generator.add_##FIELD()->mutable_field1(); \ - msg3 = generator.add_##FIELD()->mutable_field1(); \ - AssignParsingMergeMessages(msg1, msg2, msg3) - - ASSIGN_REPEATED_GROUP(group1); - ASSIGN_REPEATED_GROUP(group2); - -#undef ASSIGN_REPEATED_GROUP - - string buffer; - generator.SerializeToString(&buffer); - unittest::TestParsingMerge parsing_merge; - parsing_merge.ParseFromString(buffer); - - // Required and optional fields should be merged. - ExpectMessageMerged(parsing_merge.required_all_types()); - ExpectMessageMerged(parsing_merge.optional_all_types()); - ExpectMessageMerged( - parsing_merge.optionalgroup().optional_group_all_types()); - ExpectMessageMerged( - parsing_merge.GetExtension(unittest::TestParsingMerge::optional_ext)); - - // Repeated fields should not be merged. - EXPECT_EQ(3, parsing_merge.repeated_all_types_size()); - EXPECT_EQ(3, parsing_merge.repeatedgroup_size()); - EXPECT_EQ(3, parsing_merge.ExtensionSize( - unittest::TestParsingMerge::repeated_ext)); -} - -TEST(MessageTest, MergeFrom) { - unittest::TestAllTypes source; - unittest::TestAllTypes dest; - - // Optional fields - source.set_optional_int32(1); // only source - source.set_optional_int64(2); // both source and dest - dest.set_optional_int64(3); - dest.set_optional_uint32(4); // only dest - - // Optional fields with defaults - source.set_default_int32(13); // only source - source.set_default_int64(14); // both source and dest - dest.set_default_int64(15); - dest.set_default_uint32(16); // only dest - - // Repeated fields - source.add_repeated_int32(5); // only source - source.add_repeated_int32(6); - source.add_repeated_int64(7); // both source and dest - source.add_repeated_int64(8); - dest.add_repeated_int64(9); - dest.add_repeated_int64(10); - dest.add_repeated_uint32(11); // only dest - dest.add_repeated_uint32(12); - - dest.MergeFrom(source); - - // Optional fields: source overwrites dest if source is specified - EXPECT_EQ(1, dest.optional_int32()); // only source: use source - EXPECT_EQ(2, dest.optional_int64()); // source and dest: use source - EXPECT_EQ(4, dest.optional_uint32()); // only dest: use dest - EXPECT_EQ(0, dest.optional_uint64()); // neither: use default - - // Optional fields with defaults - EXPECT_EQ(13, dest.default_int32()); // only source: use source - EXPECT_EQ(14, dest.default_int64()); // source and dest: use source - EXPECT_EQ(16, dest.default_uint32()); // only dest: use dest - EXPECT_EQ(44, dest.default_uint64()); // neither: use default - - // Repeated fields: concatenate source onto the end of dest - ASSERT_EQ(2, dest.repeated_int32_size()); - EXPECT_EQ(5, dest.repeated_int32(0)); - EXPECT_EQ(6, dest.repeated_int32(1)); - ASSERT_EQ(4, dest.repeated_int64_size()); - EXPECT_EQ(9, dest.repeated_int64(0)); - EXPECT_EQ(10, dest.repeated_int64(1)); - EXPECT_EQ(7, dest.repeated_int64(2)); - EXPECT_EQ(8, dest.repeated_int64(3)); - ASSERT_EQ(2, dest.repeated_uint32_size()); - EXPECT_EQ(11, dest.repeated_uint32(0)); - EXPECT_EQ(12, dest.repeated_uint32(1)); - ASSERT_EQ(0, dest.repeated_uint64_size()); -} - -TEST(MessageTest, IsInitialized) { - protobuf_unittest::TestIsInitialized msg; - EXPECT_TRUE(msg.IsInitialized()); - protobuf_unittest::TestIsInitialized::SubMessage* sub_message = msg.mutable_sub_message(); - EXPECT_TRUE(msg.IsInitialized()); - protobuf_unittest::TestIsInitialized::SubMessage::SubGroup* sub_group = sub_message->mutable_subgroup(); - EXPECT_FALSE(msg.IsInitialized()); - sub_group->set_i(1); - EXPECT_TRUE(msg.IsInitialized()); -} - -TEST(MessageFactoryTest, GeneratedFactoryLookup) { - EXPECT_EQ( - MessageFactory::generated_factory()->GetPrototype( - protobuf_unittest::TestAllTypes::descriptor()), - &protobuf_unittest::TestAllTypes::default_instance()); -} - -TEST(MessageFactoryTest, GeneratedFactoryUnknownType) { - // Construct a new descriptor. - DescriptorPool pool; - FileDescriptorProto file; - file.set_name("foo.proto"); - file.add_message_type()->set_name("Foo"); - const Descriptor* descriptor = pool.BuildFile(file)->message_type(0); - - // Trying to construct it should return NULL. - EXPECT_TRUE( - MessageFactory::generated_factory()->GetPrototype(descriptor) == NULL); -} - - } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/message_unittest.inc b/src/google/protobuf/message_unittest.inc new file mode 100644 index 00000000..6ffdcce0 --- /dev/null +++ b/src/google/protobuf/message_unittest.inc @@ -0,0 +1,577 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. +// +// This file needs to be included as .inc as it depends on certain macros being +// defined prior to its inclusion. + +#include <google/protobuf/message.h> + +#include <fcntl.h> +#include <sys/stat.h> +#include <sys/types.h> +#ifndef _MSC_VER +#include <unistd.h> +#endif +#include <fstream> +#include <sstream> + +#include <google/protobuf/io/coded_stream.h> +#include <google/protobuf/io/zero_copy_stream.h> +#include <google/protobuf/io/zero_copy_stream_impl.h> +#include <google/protobuf/descriptor.pb.h> +#include <google/protobuf/arena.h> +#include <google/protobuf/descriptor.h> +#include <google/protobuf/generated_message_reflection.h> + +#include <google/protobuf/stubs/logging.h> +#include <google/protobuf/stubs/common.h> +#include <google/protobuf/stubs/logging.h> +#include <google/protobuf/testing/googletest.h> +#include <gtest/gtest.h> +#include <google/protobuf/stubs/io_win32.h> + +namespace google { +namespace protobuf { + +#if defined(_WIN32) +// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import +// them like we do below. +using google::protobuf::internal::win32::close; +using google::protobuf::internal::win32::open; +#endif + +#ifndef O_BINARY +#ifdef _O_BINARY +#define O_BINARY _O_BINARY +#else +#define O_BINARY 0 // If this isn't defined, the platform doesn't need it. +#endif +#endif + +TEST(MESSAGE_TEST_NAME, SerializeHelpers) { + // TODO(kenton): Test more helpers? They're all two-liners so it seems + // like a waste of time. + + UNITTEST::TestAllTypes message; + TestUtil::SetAllFields(&message); + std::stringstream stream; + + string str1("foo"); + string str2("bar"); + + EXPECT_TRUE(message.SerializeToString(&str1)); + EXPECT_TRUE(message.AppendToString(&str2)); + EXPECT_TRUE(message.SerializeToOstream(&stream)); + + EXPECT_EQ(str1.size() + 3, str2.size()); + EXPECT_EQ("bar", str2.substr(0, 3)); + // Don't use EXPECT_EQ because we don't want to dump raw binary data to + // stdout. + EXPECT_TRUE(str2.substr(3) == str1); + + // GCC gives some sort of error if we try to just do stream.str() == str1. + string temp = stream.str(); + EXPECT_TRUE(temp == str1); + + EXPECT_TRUE(message.SerializeAsString() == str1); + +} + +TEST(MESSAGE_TEST_NAME, SerializeToBrokenOstream) { + std::ofstream out; + UNITTEST::TestAllTypes message; + message.set_optional_int32(123); + + EXPECT_FALSE(message.SerializeToOstream(&out)); +} + +TEST(MESSAGE_TEST_NAME, ParseFromFileDescriptor) { + string filename = TestSourceDir() + + "/google/protobuf/testdata/golden_message"; + int file = open(filename.c_str(), O_RDONLY | O_BINARY); + ASSERT_GE(file, 0); + + UNITTEST::TestAllTypes message; + EXPECT_TRUE(message.ParseFromFileDescriptor(file)); + TestUtil::ExpectAllFieldsSet(message); + + EXPECT_GE(close(file), 0); +} + +TEST(MESSAGE_TEST_NAME, ParsePackedFromFileDescriptor) { + string filename = + TestSourceDir() + + "/google/protobuf/testdata/golden_packed_fields_message"; + int file = open(filename.c_str(), O_RDONLY | O_BINARY); + ASSERT_GE(file, 0); + + UNITTEST::TestPackedTypes message; + EXPECT_TRUE(message.ParseFromFileDescriptor(file)); + TestUtil::ExpectPackedFieldsSet(message); + + EXPECT_GE(close(file), 0); +} + +TEST(MESSAGE_TEST_NAME, ParseHelpers) { + // TODO(kenton): Test more helpers? They're all two-liners so it seems + // like a waste of time. + string data; + + { + // Set up. + UNITTEST::TestAllTypes message; + TestUtil::SetAllFields(&message); + message.SerializeToString(&data); + } + + { + // Test ParseFromString. + UNITTEST::TestAllTypes message; + EXPECT_TRUE(message.ParseFromString(data)); + TestUtil::ExpectAllFieldsSet(message); + } + + { + // Test ParseFromIstream. + UNITTEST::TestAllTypes message; + std::stringstream stream(data); + EXPECT_TRUE(message.ParseFromIstream(&stream)); + EXPECT_TRUE(stream.eof()); + TestUtil::ExpectAllFieldsSet(message); + } + + { + // Test ParseFromBoundedZeroCopyStream. + string data_with_junk(data); + data_with_junk.append("some junk on the end"); + io::ArrayInputStream stream(data_with_junk.data(), data_with_junk.size()); + UNITTEST::TestAllTypes message; + EXPECT_TRUE(message.ParseFromBoundedZeroCopyStream(&stream, data.size())); + TestUtil::ExpectAllFieldsSet(message); + } + + { + // Test that ParseFromBoundedZeroCopyStream fails (but doesn't crash) if + // EOF is reached before the expected number of bytes. + io::ArrayInputStream stream(data.data(), data.size()); + UNITTEST::TestAllTypes message; + EXPECT_FALSE( + message.ParseFromBoundedZeroCopyStream(&stream, data.size() + 1)); + } +} + +TEST(MESSAGE_TEST_NAME, ParseFailsIfNotInitialized) { + UNITTEST::TestRequired message; + std::vector<string> errors; + + { + ScopedMemoryLog log; + EXPECT_FALSE(message.ParseFromString("")); + errors = log.GetMessages(ERROR); + } + + ASSERT_EQ(1, errors.size()); + EXPECT_EQ( + "Can't parse message of type \"" + string(UNITTEST_PACKAGE_NAME) + + ".TestRequired\" because it is missing required fields: a, b, c", + errors[0]); +} + +TEST(MESSAGE_TEST_NAME, BypassInitializationCheckOnParse) { + UNITTEST::TestRequired message; + io::ArrayInputStream raw_input(nullptr, 0); + io::CodedInputStream input(&raw_input); + EXPECT_TRUE(message.MergePartialFromCodedStream(&input)); +} + +TEST(MESSAGE_TEST_NAME, InitializationErrorString) { + UNITTEST::TestRequired message; + EXPECT_EQ("a, b, c", message.InitializationErrorString()); +} + +TEST(MESSAGE_TEST_NAME, DynamicCastToGenerated) { + UNITTEST::TestAllTypes test_all_types; + + google::protobuf::Message* test_all_types_pointer = &test_all_types; + EXPECT_EQ(&test_all_types, + google::protobuf::internal::DynamicCastToGenerated<UNITTEST::TestAllTypes>( + test_all_types_pointer)); + EXPECT_EQ(nullptr, + google::protobuf::internal::DynamicCastToGenerated<UNITTEST::TestRequired>( + test_all_types_pointer)); + + const google::protobuf::Message* test_all_types_pointer_const = &test_all_types; + EXPECT_EQ( + &test_all_types, + google::protobuf::internal::DynamicCastToGenerated<const UNITTEST::TestAllTypes>( + test_all_types_pointer_const)); + EXPECT_EQ( + nullptr, + google::protobuf::internal::DynamicCastToGenerated<const UNITTEST::TestRequired>( + test_all_types_pointer_const)); +} + +#ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet. + +TEST(MESSAGE_TEST_NAME, SerializeFailsIfNotInitialized) { + UNITTEST::TestRequired message; + string data; + EXPECT_DEBUG_DEATH(EXPECT_TRUE(message.SerializeToString(&data)), + "Can't serialize message of type \"" + + string(UNITTEST_PACKAGE_NAME) + + ".TestRequired\" because " + "it is missing required fields: a, b, c"); +} + +TEST(MESSAGE_TEST_NAME, CheckInitialized) { + UNITTEST::TestRequired message; + EXPECT_DEATH(message.CheckInitialized(), + "Message of type \"" + + string(UNITTEST_PACKAGE_NAME) + + ".TestRequired\" is missing required " + "fields: a, b, c"); +} + +#endif // PROTOBUF_HAS_DEATH_TEST + +namespace { +// An input stream that repeats a string's content for a number of times. It +// helps us create a really large input without consuming too much memory. Used +// to test the parsing behavior when the input size exceeds 2G or close to it. +class RepeatedInputStream : public io::ZeroCopyInputStream { + public: + RepeatedInputStream(const string& data, size_t count) + : data_(data), count_(count), position_(0), total_byte_count_(0) {} + + virtual bool Next(const void** data, int* size) { + if (position_ == data_.size()) { + if (--count_ == 0) { + return false; + } + position_ = 0; + } + *data = &data_[position_]; + *size = static_cast<int>(data_.size() - position_); + position_ = data_.size(); + total_byte_count_ += *size; + return true; + } + + virtual void BackUp(int count) { + position_ -= static_cast<size_t>(count); + total_byte_count_ -= count; + } + + virtual bool Skip(int count) { + while (count > 0) { + const void* data; + int size; + if (!Next(&data, &size)) { + break; + } + if (size >= count) { + BackUp(size - count); + return true; + } else { + count -= size; + } + } + return false; + } + + virtual int64 ByteCount() const { return total_byte_count_; } + + private: + string data_; + size_t count_; // The number of strings that haven't been consuemd. + size_t position_; // Position in the string for the next read. + int64 total_byte_count_; +}; +} // namespace + +TEST(MESSAGE_TEST_NAME, TestParseMessagesCloseTo2G) { + // Create a message with a large string field. + string value = string(64 * 1024 * 1024, 'x'); + UNITTEST::TestAllTypes message; + message.set_optional_string(value); + + // Repeat this message in the input stream to make the total input size + // close to 2G. + string data = message.SerializeAsString(); + size_t count = static_cast<size_t>(kint32max) / data.size(); + RepeatedInputStream input(data, count); + + // The parsing should succeed. + UNITTEST::TestAllTypes result; + EXPECT_TRUE(result.ParseFromZeroCopyStream(&input)); + + // When there are multiple occurences of a singulr field, the last one + // should win. + EXPECT_EQ(value, result.optional_string()); +} + +TEST(MESSAGE_TEST_NAME, TestParseMessagesOver2G) { + // Create a message with a large string field. + string value = string(64 * 1024 * 1024, 'x'); + UNITTEST::TestAllTypes message; + message.set_optional_string(value); + + // Repeat this message in the input stream to make the total input size + // larger than 2G. + string data = message.SerializeAsString(); + size_t count = static_cast<size_t>(kint32max) / data.size() + 1; + RepeatedInputStream input(data, count); + + // The parsing should fail. + UNITTEST::TestAllTypes result; + EXPECT_FALSE(result.ParseFromZeroCopyStream(&input)); +} + +TEST(MESSAGE_TEST_NAME, BypassInitializationCheckOnSerialize) { + UNITTEST::TestRequired message; + io::ArrayOutputStream raw_output(nullptr, 0); + io::CodedOutputStream output(&raw_output); + EXPECT_TRUE(message.SerializePartialToCodedStream(&output)); +} + +TEST(MESSAGE_TEST_NAME, FindInitializationErrors) { + UNITTEST::TestRequired message; + std::vector<string> errors; + message.FindInitializationErrors(&errors); + ASSERT_EQ(3, errors.size()); + EXPECT_EQ("a", errors[0]); + EXPECT_EQ("b", errors[1]); + EXPECT_EQ("c", errors[2]); +} + +TEST(MESSAGE_TEST_NAME, ParseFailsOnInvalidMessageEnd) { + UNITTEST::TestAllTypes message; + + // Control case. + EXPECT_TRUE(message.ParseFromArray("", 0)); + + // The byte is a valid varint, but not a valid tag (zero). + EXPECT_FALSE(message.ParseFromArray("\0", 1)); + + // The byte is a malformed varint. + EXPECT_FALSE(message.ParseFromArray("\200", 1)); + + // The byte is an endgroup tag, but we aren't parsing a group. + EXPECT_FALSE(message.ParseFromArray("\014", 1)); +} + +// Regression test for b/23630858 +TEST(MESSAGE_TEST_NAME, MessageIsStillValidAfterParseFails) { + UNITTEST::TestAllTypes message; + + // 9 0xFFs for the "optional_uint64" field. + string invalid_data = "\x20\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"; + + EXPECT_FALSE(message.ParseFromString(invalid_data)); + message.Clear(); + EXPECT_EQ(0, message.optional_uint64()); + + // invalid data for field "optional_string". Length prefix is 1 but no + // payload. + string invalid_string_data = "\x72\x01"; + { + google::protobuf::Arena arena; + UNITTEST::TestAllTypes* arena_message = + google::protobuf::Arena::CreateMessage<UNITTEST::TestAllTypes>(&arena); + EXPECT_FALSE(arena_message->ParseFromString(invalid_string_data)); + arena_message->Clear(); + EXPECT_EQ("", arena_message->optional_string()); + } +} + + +namespace { + +void ExpectMessageMerged(const UNITTEST::TestAllTypes& message) { + EXPECT_EQ(3, message.optional_int32()); + EXPECT_EQ(2, message.optional_int64()); + EXPECT_EQ("hello", message.optional_string()); +} + +void AssignParsingMergeMessages(UNITTEST::TestAllTypes* msg1, + UNITTEST::TestAllTypes* msg2, + UNITTEST::TestAllTypes* msg3) { + msg1->set_optional_int32(1); + msg2->set_optional_int64(2); + msg3->set_optional_int32(3); + msg3->set_optional_string("hello"); +} + +} // namespace + +// Test that if an optional or required message/group field appears multiple +// times in the input, they need to be merged. +TEST(MESSAGE_TEST_NAME, ParsingMerge) { + UNITTEST::TestParsingMerge::RepeatedFieldsGenerator generator; + UNITTEST::TestAllTypes* msg1; + UNITTEST::TestAllTypes* msg2; + UNITTEST::TestAllTypes* msg3; + +#define ASSIGN_REPEATED_FIELD(FIELD) \ + msg1 = generator.add_##FIELD(); \ + msg2 = generator.add_##FIELD(); \ + msg3 = generator.add_##FIELD(); \ + AssignParsingMergeMessages(msg1, msg2, msg3) + + ASSIGN_REPEATED_FIELD(field1); + ASSIGN_REPEATED_FIELD(field2); + ASSIGN_REPEATED_FIELD(field3); + ASSIGN_REPEATED_FIELD(ext1); + ASSIGN_REPEATED_FIELD(ext2); + +#undef ASSIGN_REPEATED_FIELD +#define ASSIGN_REPEATED_GROUP(FIELD) \ + msg1 = generator.add_##FIELD()->mutable_field1(); \ + msg2 = generator.add_##FIELD()->mutable_field1(); \ + msg3 = generator.add_##FIELD()->mutable_field1(); \ + AssignParsingMergeMessages(msg1, msg2, msg3) + + ASSIGN_REPEATED_GROUP(group1); + ASSIGN_REPEATED_GROUP(group2); + +#undef ASSIGN_REPEATED_GROUP + + string buffer; + generator.SerializeToString(&buffer); + UNITTEST::TestParsingMerge parsing_merge; + parsing_merge.ParseFromString(buffer); + + // Required and optional fields should be merged. + ExpectMessageMerged(parsing_merge.required_all_types()); + ExpectMessageMerged(parsing_merge.optional_all_types()); + ExpectMessageMerged(parsing_merge.optionalgroup().optional_group_all_types()); + ExpectMessageMerged( + parsing_merge.GetExtension(UNITTEST::TestParsingMerge::optional_ext)); + + // Repeated fields should not be merged. + EXPECT_EQ(3, parsing_merge.repeated_all_types_size()); + EXPECT_EQ(3, parsing_merge.repeatedgroup_size()); + EXPECT_EQ( + 3, parsing_merge.ExtensionSize(UNITTEST::TestParsingMerge::repeated_ext)); +} + +TEST(MESSAGE_TEST_NAME, MergeFrom) { + UNITTEST::TestAllTypes source, dest; + + // Optional fields + source.set_optional_int32(1); // only source + source.set_optional_int64(2); // both source and dest + dest.set_optional_int64(3); + dest.set_optional_uint32(4); // only dest + + // Optional fields with defaults + source.set_default_int32(13); // only source + source.set_default_int64(14); // both source and dest + dest.set_default_int64(15); + dest.set_default_uint32(16); // only dest + + // Repeated fields + source.add_repeated_int32(5); // only source + source.add_repeated_int32(6); + source.add_repeated_int64(7); // both source and dest + source.add_repeated_int64(8); + dest.add_repeated_int64(9); + dest.add_repeated_int64(10); + dest.add_repeated_uint32(11); // only dest + dest.add_repeated_uint32(12); + + dest.MergeFrom(source); + + // Optional fields: source overwrites dest if source is specified + EXPECT_EQ(1, dest.optional_int32()); // only source: use source + EXPECT_EQ(2, dest.optional_int64()); // source and dest: use source + EXPECT_EQ(4, dest.optional_uint32()); // only dest: use dest + EXPECT_EQ(0, dest.optional_uint64()); // neither: use default + + // Optional fields with defaults + EXPECT_EQ(13, dest.default_int32()); // only source: use source + EXPECT_EQ(14, dest.default_int64()); // source and dest: use source + EXPECT_EQ(16, dest.default_uint32()); // only dest: use dest + EXPECT_EQ(44, dest.default_uint64()); // neither: use default + + // Repeated fields: concatenate source onto the end of dest + ASSERT_EQ(2, dest.repeated_int32_size()); + EXPECT_EQ(5, dest.repeated_int32(0)); + EXPECT_EQ(6, dest.repeated_int32(1)); + ASSERT_EQ(4, dest.repeated_int64_size()); + EXPECT_EQ(9, dest.repeated_int64(0)); + EXPECT_EQ(10, dest.repeated_int64(1)); + EXPECT_EQ(7, dest.repeated_int64(2)); + EXPECT_EQ(8, dest.repeated_int64(3)); + ASSERT_EQ(2, dest.repeated_uint32_size()); + EXPECT_EQ(11, dest.repeated_uint32(0)); + EXPECT_EQ(12, dest.repeated_uint32(1)); + ASSERT_EQ(0, dest.repeated_uint64_size()); +} + +TEST(MESSAGE_TEST_NAME, IsInitialized) { + UNITTEST::TestIsInitialized msg; + EXPECT_TRUE(msg.IsInitialized()); + UNITTEST::TestIsInitialized::SubMessage* sub_message = + msg.mutable_sub_message(); + EXPECT_TRUE(msg.IsInitialized()); + UNITTEST::TestIsInitialized::SubMessage::SubGroup* sub_group = + sub_message->mutable_subgroup(); + EXPECT_FALSE(msg.IsInitialized()); + sub_group->set_i(1); + EXPECT_TRUE(msg.IsInitialized()); +} + +TEST(MESSAGE_FACTORY_TEST_NAME, GeneratedFactoryLookup) { + EXPECT_EQ(MessageFactory::generated_factory()->GetPrototype( + UNITTEST::TestAllTypes::descriptor()), + &UNITTEST::TestAllTypes::default_instance()); +} + +TEST(MESSAGE_FACTORY_TEST_NAME, GeneratedFactoryUnknownType) { + // Construct a new descriptor. + DescriptorPool pool; + FileDescriptorProto file; + file.set_name("foo.proto"); + file.add_message_type()->set_name("Foo"); + const Descriptor* descriptor = pool.BuildFile(file)->message_type(0); + + // Trying to construct it should return nullptr. + EXPECT_TRUE(MessageFactory::generated_factory()->GetPrototype(descriptor) == + nullptr); +} + + +} // namespace protobuf +} // namespace google diff --git a/src/google/protobuf/preserve_unknown_enum_test.cc b/src/google/protobuf/preserve_unknown_enum_test.cc index 1673e8af..e292199e 100644 --- a/src/google/protobuf/preserve_unknown_enum_test.cc +++ b/src/google/protobuf/preserve_unknown_enum_test.cc @@ -120,7 +120,7 @@ TEST(PreserveUnknownEnumTest, PreserveParseAndSerializeDynamicMessage) { string serialized = orig_message.SerializeAsString(); google::protobuf::DynamicMessageFactory factory; - google::protobuf::scoped_ptr<google::protobuf::Message> message(factory.GetPrototype( + std::unique_ptr<google::protobuf::Message> message(factory.GetPrototype( proto3_preserve_unknown_enum_unittest::MyMessage::descriptor())->New()); EXPECT_EQ(true, message->ParseFromString(serialized)); message->DiscardUnknownFields(); @@ -161,7 +161,7 @@ TEST(PreserveUnknownEnumTest, DynamicProto2HidesUnknownValues) { orig_message.SerializeToString(&serialized); google::protobuf::DynamicMessageFactory factory; - google::protobuf::scoped_ptr<google::protobuf::Message> message(factory.GetPrototype( + std::unique_ptr<google::protobuf::Message> message(factory.GetPrototype( proto2_preserve_unknown_enum_unittest::MyMessage::descriptor())->New()); EXPECT_EQ(true, message->ParseFromString(serialized)); // The intermediate message has everything in its "unknown fields". diff --git a/src/google/protobuf/proto3_arena_lite_unittest.cc b/src/google/protobuf/proto3_arena_lite_unittest.cc index 0f18c027..2ac775d7 100644 --- a/src/google/protobuf/proto3_arena_lite_unittest.cc +++ b/src/google/protobuf/proto3_arena_lite_unittest.cc @@ -30,20 +30,15 @@ #include <string> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <vector> -#include <google/protobuf/test_util.h> -#include <google/protobuf/unittest.pb.h> -#include <google/protobuf/unittest_proto3_arena_lite.pb.h> +#include <google/protobuf/unittest_proto3_arena.pb.h> #include <google/protobuf/arena.h> #include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> namespace google { -using proto3_arena_lite_unittest::TestAllTypes; +using proto3_arena_unittest::TestAllTypes; namespace protobuf { namespace { @@ -56,9 +51,9 @@ void SetAllFields(TestAllTypes* m) { m->mutable_optional_nested_message()->set_bb(42); m->mutable_optional_foreign_message()->set_c(43); m->set_optional_nested_enum( - proto3_arena_lite_unittest::TestAllTypes_NestedEnum_BAZ); + proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ); m->set_optional_foreign_enum( - proto3_arena_lite_unittest::FOREIGN_BAZ); + proto3_arena_unittest::FOREIGN_BAZ); m->mutable_optional_lazy_message()->set_bb(45); m->add_repeated_int32(100); m->add_repeated_string("asdf"); @@ -66,9 +61,9 @@ void SetAllFields(TestAllTypes* m) { m->add_repeated_nested_message()->set_bb(46); m->add_repeated_foreign_message()->set_c(47); m->add_repeated_nested_enum( - proto3_arena_lite_unittest::TestAllTypes_NestedEnum_BAZ); + proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ); m->add_repeated_foreign_enum( - proto3_arena_lite_unittest::FOREIGN_BAZ); + proto3_arena_unittest::FOREIGN_BAZ); m->add_repeated_lazy_message()->set_bb(49); m->set_oneof_uint32(1); @@ -84,9 +79,9 @@ void ExpectAllFieldsSet(const TestAllTypes& m) { EXPECT_EQ(42, m.optional_nested_message().bb()); EXPECT_EQ(true, m.has_optional_foreign_message()); EXPECT_EQ(43, m.optional_foreign_message().c()); - EXPECT_EQ(proto3_arena_lite_unittest::TestAllTypes_NestedEnum_BAZ, + EXPECT_EQ(proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ, m.optional_nested_enum()); - EXPECT_EQ(proto3_arena_lite_unittest::FOREIGN_BAZ, + EXPECT_EQ(proto3_arena_unittest::FOREIGN_BAZ, m.optional_foreign_enum()); EXPECT_EQ(true, m.has_optional_lazy_message()); EXPECT_EQ(45, m.optional_lazy_message().bb()); @@ -102,15 +97,15 @@ void ExpectAllFieldsSet(const TestAllTypes& m) { EXPECT_EQ(1, m.repeated_foreign_message_size()); EXPECT_EQ(47, m.repeated_foreign_message(0).c()); EXPECT_EQ(1, m.repeated_nested_enum_size()); - EXPECT_EQ(proto3_arena_lite_unittest::TestAllTypes_NestedEnum_BAZ, + EXPECT_EQ(proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ, m.repeated_nested_enum(0)); EXPECT_EQ(1, m.repeated_foreign_enum_size()); - EXPECT_EQ(proto3_arena_lite_unittest::FOREIGN_BAZ, + EXPECT_EQ(proto3_arena_unittest::FOREIGN_BAZ, m.repeated_foreign_enum(0)); EXPECT_EQ(1, m.repeated_lazy_message_size()); EXPECT_EQ(49, m.repeated_lazy_message(0).bb()); - EXPECT_EQ(proto3_arena_lite_unittest::TestAllTypes::kOneofString, + EXPECT_EQ(proto3_arena_unittest::TestAllTypes::kOneofString, m.oneof_field_case()); EXPECT_EQ("test", m.oneof_string()); } @@ -154,7 +149,7 @@ TEST(Proto3ArenaLiteTest, ReleaseMessage) { Arena arena; TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena); arena_message->mutable_optional_nested_message()->set_bb(118); - google::protobuf::scoped_ptr<TestAllTypes::NestedMessage> nested( + std::unique_ptr<TestAllTypes::NestedMessage> nested( arena_message->release_optional_nested_message()); EXPECT_EQ(118, nested->bb()); } diff --git a/src/google/protobuf/proto3_arena_unittest.cc b/src/google/protobuf/proto3_arena_unittest.cc index 3a0fb804..dac73781 100644 --- a/src/google/protobuf/proto3_arena_unittest.cc +++ b/src/google/protobuf/proto3_arena_unittest.cc @@ -30,9 +30,6 @@ #include <string> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <vector> #include <google/protobuf/test_util.h> @@ -198,7 +195,7 @@ TEST(Proto3ArenaTest, ReleaseMessage) { Arena arena; TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena); arena_message->mutable_optional_nested_message()->set_bb(118); - google::protobuf::scoped_ptr<TestAllTypes::NestedMessage> nested( + std::unique_ptr<TestAllTypes::NestedMessage> nested( arena_message->release_optional_nested_message()); EXPECT_EQ(118, nested->bb()); } diff --git a/src/google/protobuf/proto3_lite_unittest.cc b/src/google/protobuf/proto3_lite_unittest.cc index 2e2beea9..8b2c5742 100644 --- a/src/google/protobuf/proto3_lite_unittest.cc +++ b/src/google/protobuf/proto3_lite_unittest.cc @@ -30,13 +30,8 @@ #include <string> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <vector> -#include <google/protobuf/test_util.h> -#include <google/protobuf/unittest.pb.h> #include <google/protobuf/unittest_proto3_lite.pb.h> #include <google/protobuf/arena.h> #include <google/protobuf/testing/googletest.h> diff --git a/src/google/protobuf/reflection.h b/src/google/protobuf/reflection.h index fcb9a435..5d0fc42b 100755 --- a/src/google/protobuf/reflection.h +++ b/src/google/protobuf/reflection.h @@ -34,9 +34,6 @@ #define GOOGLE_PROTOBUF_REFLECTION_H__ #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/message.h> #include <google/protobuf/generated_enum_util.h> @@ -63,7 +60,7 @@ MutableRepeatedFieldRef<T> Reflection::GetMutableRepeatedFieldRef( // RepeatedFieldRef definition for non-message types. template<typename T> class RepeatedFieldRef< - T, typename internal::enable_if<!internal::is_base_of<Message, T>::value>::type> { + T, typename std::enable_if<!std::is_base_of<Message, T>::value>::type> { typedef typename internal::RefTypeTraits<T>::iterator IteratorType; typedef typename internal::RefTypeTraits<T>::AccessorType AccessorType; @@ -112,7 +109,7 @@ class RepeatedFieldRef< // MutableRepeatedFieldRef definition for non-message types. template<typename T> class MutableRepeatedFieldRef< - T, typename internal::enable_if<!internal::is_base_of<Message, T>::value>::type> { + T, typename std::enable_if<!std::is_base_of<Message, T>::value>::type> { typedef typename internal::RefTypeTraits<T>::AccessorType AccessorType; public: @@ -177,7 +174,7 @@ class MutableRepeatedFieldRef< // RepeatedFieldRef definition for message types. template<typename T> class RepeatedFieldRef< - T, typename internal::enable_if<internal::is_base_of<Message, T>::value>::type> { + T, typename std::enable_if<std::is_base_of<Message, T>::value>::type> { typedef typename internal::RefTypeTraits<T>::iterator IteratorType; typedef typename internal::RefTypeTraits<T>::AccessorType AccessorType; @@ -219,7 +216,7 @@ class RepeatedFieldRef< } iterator end() const { // The end iterator must not be dereferenced, no need for scratch space. - return iterator(data_, accessor_, false, NULL); + return iterator(data_, accessor_, false, nullptr); } private: @@ -245,7 +242,7 @@ class RepeatedFieldRef< // MutableRepeatedFieldRef definition for message types. template<typename T> class MutableRepeatedFieldRef< - T, typename internal::enable_if<internal::is_base_of<Message, T>::value>::type> { + T, typename std::enable_if<std::is_base_of<Message, T>::value>::type> { typedef typename internal::RefTypeTraits<T>::AccessorType AccessorType; public: @@ -447,7 +444,7 @@ class RepeatedFieldRefIterator iterator_(begin ? accessor->BeginIterator(data) : accessor->EndIterator(data)), // The end iterator must not be dereferenced, no need for scratch space. - scratch_space_(begin ? new AccessorValueType : NULL) {} + scratch_space_(begin ? new AccessorValueType : nullptr) {} // Constructor for message fields. RepeatedFieldRefIterator(const void* data, const RepeatedFieldAccessor* accessor, @@ -508,7 +505,7 @@ class RepeatedFieldRefIterator const void* data_; const RepeatedFieldAccessor* accessor_; void* iterator_; - google::protobuf::scoped_ptr<AccessorValueType> scratch_space_; + std::unique_ptr<AccessorValueType> scratch_space_; }; // TypeTraits that maps the type parameter T of RepeatedFieldRef or @@ -535,7 +532,7 @@ DEFINE_PRIMITIVE(BOOL, bool) template<typename T> struct RefTypeTraits< - T, typename internal::enable_if<PrimitiveTraits<T>::is_primitive>::type> { + T, typename std::enable_if<PrimitiveTraits<T>::is_primitive>::type> { typedef RepeatedFieldRefIterator<T> iterator; typedef RepeatedFieldAccessor AccessorType; typedef T AccessorValueType; @@ -550,7 +547,7 @@ struct RefTypeTraits< template<typename T> struct RefTypeTraits< - T, typename internal::enable_if<is_proto_enum<T>::value>::type> { + T, typename std::enable_if<is_proto_enum<T>::value>::type> { typedef RepeatedFieldRefIterator<T> iterator; typedef RepeatedFieldAccessor AccessorType; // We use int32 for repeated enums in RepeatedFieldAccessor. @@ -566,7 +563,7 @@ struct RefTypeTraits< template<typename T> struct RefTypeTraits< - T, typename internal::enable_if< ::google::protobuf::internal::is_same<string, T>::value>::type> { + T, typename std::enable_if<std::is_same<string, T>::value>::type> { typedef RepeatedFieldRefIterator<T> iterator; typedef RepeatedFieldAccessor AccessorType; typedef string AccessorValueType; @@ -594,7 +591,7 @@ struct MessageDescriptorGetter<Message> { template<typename T> struct RefTypeTraits< - T, typename internal::enable_if<internal::is_base_of<Message, T>::value>::type> { + T, typename std::enable_if<std::is_base_of<Message, T>::value>::type> { typedef RepeatedFieldRefIterator<T> iterator; typedef RepeatedFieldAccessor AccessorType; typedef Message AccessorValueType; diff --git a/src/google/protobuf/reflection_ops.cc b/src/google/protobuf/reflection_ops.cc index eb2a0e7a..3cd50340 100644 --- a/src/google/protobuf/reflection_ops.cc +++ b/src/google/protobuf/reflection_ops.cc @@ -50,10 +50,10 @@ namespace internal { static const Reflection* GetReflectionOrDie(const Message& m) { const Reflection* r = m.GetReflection(); - if (r == NULL) { + if (r == nullptr) { const Descriptor* d = m.GetDescriptor(); const string& mtype = d ? d->name() : "unknown"; - // RawMessage is one known type for which GetReflection() returns NULL. + // RawMessage is one known type for which GetReflection() returns nullptr. GOOGLE_LOG(FATAL) << "Message does not support reflection (type " << mtype << ")."; } return r; diff --git a/src/google/protobuf/repeated_field.h b/src/google/protobuf/repeated_field.h index 5fc619f2..b47ea994 100644 --- a/src/google/protobuf/repeated_field.h +++ b/src/google/protobuf/repeated_field.h @@ -61,6 +61,7 @@ #include <google/protobuf/implicit_weak_message.h> #include <google/protobuf/message_lite.h> #include <google/protobuf/stubs/port.h> +#include <type_traits> // Forward-declare these so that we can make them friends. @@ -108,7 +109,7 @@ inline int CalculateReserve(Iter begin, Iter end) { // not ever use a RepeatedField directly; they will use the get-by-index, // set-by-index, and add accessors that are generated for all repeated fields. template <typename Element> -class RepeatedField PROTOBUF_FINAL { +class RepeatedField final { public: RepeatedField(); explicit RepeatedField(Arena* arena); @@ -119,10 +120,8 @@ class RepeatedField PROTOBUF_FINAL { RepeatedField& operator=(const RepeatedField& other); -#if LANG_CXX11 RepeatedField(RepeatedField&& other) noexcept; RepeatedField& operator=(RepeatedField&& other) noexcept; -#endif bool empty() const; int size() const; @@ -352,7 +351,7 @@ namespace internal { // effectively. template <typename Element, bool HasTrivialCopy = - has_trivial_copy<Element>::value> + std::is_pod<Element>::value> struct ElementCopier { void operator()(Element* to, const Element* from, int array_size); }; @@ -386,8 +385,8 @@ struct TypeImplementsMergeBehaviorProbeForMergeFrom { CheckType<U, bool, &U::MergeFrom>*); template<typename U> static HasNoMerge Check(...); - // Resolves to either google::protobuf::internal::true_type or google::protobuf::internal::false_type. - typedef google::protobuf::internal::integral_constant<bool, + // Resolves to either std::true_type or std::false_type. + typedef std::integral_constant<bool, (sizeof(Check<T>(0)) == sizeof(HasMerge))> type; }; @@ -398,7 +397,7 @@ struct TypeImplementsMergeBehavior : template <> struct TypeImplementsMergeBehavior< ::std::string> { - typedef google::protobuf::internal::true_type type; + typedef std::true_type type; }; // This is the common base class for RepeatedPtrFields. It deals only in void* @@ -465,11 +464,9 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase { inline void InternalSwap(RepeatedPtrFieldBase* other); protected: -#if LANG_CXX11 template <typename TypeHandler> void Add(typename TypeHandler::Type&& value, - internal::enable_if<TypeHandler::Moveable>* dummy = NULL); -#endif + std::enable_if<TypeHandler::Moveable>* dummy = NULL); template <typename TypeHandler> void RemoveLast(); @@ -532,9 +529,9 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase { typename TypeHandler::Type* ReleaseCleared(); template <typename TypeHandler> - void AddAllocatedInternal(typename TypeHandler::Type* value, google::protobuf::internal::true_type); + void AddAllocatedInternal(typename TypeHandler::Type* value, std::true_type); template <typename TypeHandler> - void AddAllocatedInternal(typename TypeHandler::Type* value, google::protobuf::internal::false_type); + void AddAllocatedInternal(typename TypeHandler::Type* value, std::false_type); template <typename TypeHandler> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void AddAllocatedSlowWithCopy(typename TypeHandler::Type* value, @@ -544,9 +541,9 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase { void AddAllocatedSlowWithoutCopy(typename TypeHandler::Type* value); template <typename TypeHandler> - typename TypeHandler::Type* ReleaseLastInternal(google::protobuf::internal::true_type); + typename TypeHandler::Type* ReleaseLastInternal(std::true_type); template <typename TypeHandler> - typename TypeHandler::Type* ReleaseLastInternal(google::protobuf::internal::false_type); + typename TypeHandler::Type* ReleaseLastInternal(std::false_type); template<typename TypeHandler> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void SwapFallback(RepeatedPtrFieldBase* other); @@ -640,9 +637,7 @@ class GenericTypeHandler { public: typedef GenericType Type; typedef GenericType WeakType; -#if LANG_CXX11 static const bool Moveable = false; -#endif static inline GenericType* New(Arena* arena) { return ::google::protobuf::Arena::CreateMaybeMessage<Type>(arena); @@ -732,20 +727,15 @@ class StringTypeHandler { public: typedef string Type; typedef string WeakType; -#if LANG_CXX11 - static const bool Moveable = - std::is_move_constructible<Type>::value && - std::is_move_assignable<Type>::value; -#endif + static const bool Moveable = std::is_move_constructible<Type>::value && + std::is_move_assignable<Type>::value; static inline string* New(Arena* arena) { return Arena::Create<string>(arena); } -#if LANG_CXX11 static inline string* New(Arena* arena, string&& value) { return Arena::Create<string>(arena, std::move(value)); } -#endif static inline string* NewFromPrototype(const string*, ::google::protobuf::Arena* arena) { return New(arena); @@ -773,7 +763,7 @@ class StringTypeHandler { // RepeatedPtrField is like RepeatedField, but used for repeated strings or // Messages. template <typename Element> -class RepeatedPtrField PROTOBUF_FINAL : private internal::RepeatedPtrFieldBase { +class RepeatedPtrField final : private internal::RepeatedPtrFieldBase { public: RepeatedPtrField(); explicit RepeatedPtrField(::google::protobuf::Arena* arena); @@ -785,10 +775,8 @@ class RepeatedPtrField PROTOBUF_FINAL : private internal::RepeatedPtrFieldBase { RepeatedPtrField& operator=(const RepeatedPtrField& other); -#if LANG_CXX11 RepeatedPtrField(RepeatedPtrField&& other) noexcept; RepeatedPtrField& operator=(RepeatedPtrField&& other) noexcept; -#endif bool empty() const; int size() const; @@ -796,9 +784,7 @@ class RepeatedPtrField PROTOBUF_FINAL : private internal::RepeatedPtrFieldBase { const Element& Get(int index) const; Element* Mutable(int index); Element* Add(); -#if LANG_CXX11 void Add(Element&& value); -#endif const Element& operator[](int index) const { return Get(index); } Element& operator[](int index) { return *Mutable(index); } @@ -928,7 +914,7 @@ class RepeatedPtrField PROTOBUF_FINAL : private internal::RepeatedPtrFieldBase { // RepeatedPtrField<T> temp_field; // temp_field.AddAllocated(new T); // ... // Do something with temp_field - // temp_field.ExtractSubrange(0, temp_field.size(), NULL); + // temp_field.ExtractSubrange(0, temp_field.size(), nullptr); // If you put temp_field on the arena this fails, because the ownership // transfers to the arena at the "AddAllocated" call and is not released // anymore causing a double delete. UnsafeArenaAddAllocated prevents this. @@ -1027,9 +1013,9 @@ class RepeatedPtrField PROTOBUF_FINAL : private internal::RepeatedPtrFieldBase { // MergeFrom()), so we must resolve this at compile time. ExtractSubrange() // uses SFINAE to choose one of the below implementations. void ExtractSubrangeInternal(int start, int num, Element** elements, - google::protobuf::internal::true_type); + std::true_type); void ExtractSubrangeInternal(int start, int num, Element** elements, - google::protobuf::internal::false_type); + std::false_type); friend class Arena; friend class MessageLite; @@ -1100,8 +1086,6 @@ RepeatedField<Element>::operator=(const RepeatedField& other) { return *this; } -#if LANG_CXX11 - template <typename Element> inline RepeatedField<Element>::RepeatedField(RepeatedField&& other) noexcept : RepeatedField() { @@ -1129,8 +1113,6 @@ inline RepeatedField<Element>& RepeatedField<Element>::operator=( return *this; } -#endif // LANG_CXX11 - template <typename Element> inline bool RepeatedField<Element>::empty() const { return current_size_ == 0; @@ -1556,11 +1538,10 @@ inline typename TypeHandler::Type* RepeatedPtrFieldBase::Add( return result; } -#if LANG_CXX11 template <typename TypeHandler> inline void RepeatedPtrFieldBase::Add( typename TypeHandler::Type&& value, - internal::enable_if<TypeHandler::Moveable>*) { + std::enable_if<TypeHandler::Moveable>*) { if (rep_ != NULL && current_size_ < rep_->allocated_size) { *cast<TypeHandler>(rep_->elements[current_size_++]) = std::move(value); return; @@ -1573,7 +1554,6 @@ inline void RepeatedPtrFieldBase::Add( TypeHandler::New(arena_, std::move(value)); rep_->elements[current_size_++] = result; } -#endif template <typename TypeHandler> inline void RepeatedPtrFieldBase::RemoveLast() { @@ -1716,7 +1696,7 @@ inline typename TypeHandler::Type* RepeatedPtrFieldBase::AddFromCleared() { template <typename TypeHandler> void RepeatedPtrFieldBase::AddAllocatedInternal( typename TypeHandler::Type* value, - google::protobuf::internal::true_type) { + std::true_type) { Arena* element_arena = reinterpret_cast<Arena*>( TypeHandler::GetMaybeArenaPointer(value)); Arena* arena = GetArenaNoVirtual(); @@ -1766,7 +1746,7 @@ void RepeatedPtrFieldBase::AddAllocatedSlowWithCopy( template <typename TypeHandler> void RepeatedPtrFieldBase::AddAllocatedInternal( typename TypeHandler::Type* value, - google::protobuf::internal::false_type) { + std::false_type) { if (rep_ && rep_->allocated_size < total_size_) { // Fast path: underlying arena representation (tagged pointer) is equal to // our arena pointer, and we can add to array without resizing it (at least @@ -1816,7 +1796,7 @@ void RepeatedPtrFieldBase::UnsafeArenaAddAllocated( // ReleaseLast() for types that implement merge/copy behavior. template <typename TypeHandler> inline typename TypeHandler::Type* -RepeatedPtrFieldBase::ReleaseLastInternal(google::protobuf::internal::true_type) { +RepeatedPtrFieldBase::ReleaseLastInternal(std::true_type) { // First, release an element. typename TypeHandler::Type* result = UnsafeArenaReleaseLast<TypeHandler>(); // Now perform a copy if we're on an arena. @@ -1837,7 +1817,7 @@ RepeatedPtrFieldBase::ReleaseLastInternal(google::protobuf::internal::true_type) // case. template <typename TypeHandler> inline typename TypeHandler::Type* -RepeatedPtrFieldBase::ReleaseLastInternal(google::protobuf::internal::false_type) { +RepeatedPtrFieldBase::ReleaseLastInternal(std::false_type) { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL) << "ReleaseLast() called on a RepeatedPtrField that is on an arena, " << "with a type that does not implement MergeFrom. This is unsafe; " @@ -1943,8 +1923,6 @@ inline RepeatedPtrField<Element>& RepeatedPtrField<Element>::operator=( return *this; } -#if LANG_CXX11 - template <typename Element> inline RepeatedPtrField<Element>::RepeatedPtrField( RepeatedPtrField&& other) noexcept @@ -1973,8 +1951,6 @@ inline RepeatedPtrField<Element>& RepeatedPtrField<Element>::operator=( return *this; } -#endif // LANG_CXX11 - template <typename Element> inline bool RepeatedPtrField<Element>::empty() const { return RepeatedPtrFieldBase::empty(); @@ -2001,12 +1977,10 @@ inline Element* RepeatedPtrField<Element>::Add() { return RepeatedPtrFieldBase::Add<TypeHandler>(); } -#if LANG_CXX11 template <typename Element> inline void RepeatedPtrField<Element>::Add(Element&& value) { RepeatedPtrFieldBase::Add<TypeHandler>(std::move(value)); } -#endif template <typename Element> inline void RepeatedPtrField<Element>::RemoveLast() { @@ -2036,7 +2010,7 @@ inline void RepeatedPtrField<Element>::ExtractSubrange( // behavior. template <typename Element> inline void RepeatedPtrField<Element>::ExtractSubrangeInternal( - int start, int num, Element** elements, google::protobuf::internal::true_type) { + int start, int num, Element** elements, std::true_type) { GOOGLE_DCHECK_GE(start, 0); GOOGLE_DCHECK_GE(num, 0); GOOGLE_DCHECK_LE(start + num, size()); @@ -2069,7 +2043,7 @@ inline void RepeatedPtrField<Element>::ExtractSubrangeInternal( // behavior. template<typename Element> inline void RepeatedPtrField<Element>::ExtractSubrangeInternal( - int start, int num, Element** elements, google::protobuf::internal::false_type) { + int start, int num, Element** elements, std::false_type) { // This case is identical to UnsafeArenaExtractSubrange(). However, since // ExtractSubrange() must return heap-allocated objects by contract, and we // cannot fulfill this contract if we are an on arena, we must GOOGLE_DCHECK() that @@ -2241,7 +2215,7 @@ class RepeatedPtrIterator // Shadow the value_type in std::iterator<> because const_iterator::value_type // needs to be T, not const T. - typedef typename remove_const<Element>::type value_type; + typedef typename std::remove_const<Element>::type value_type; // Let the compiler know that these are type names, so we don't have to // write "typename" in front of them everywhere. @@ -2259,7 +2233,7 @@ class RepeatedPtrIterator : it_(other.it_) { // Force a compiler error if the other type is not convertible to ours. if (false) { - implicit_cast<Element*>(static_cast<OtherElement*>(NULL)); + implicit_cast<Element*>(static_cast<OtherElement*>(nullptr)); } } @@ -2335,7 +2309,7 @@ class RepeatedPtrOverPtrsIterator // Shadow the value_type in std::iterator<> because const_iterator::value_type // needs to be T, not const T. - typedef typename remove_const<Element>::type value_type; + typedef typename std::remove_const<Element>::type value_type; // Let the compiler know that these are type names, so we don't have to // write "typename" in front of them everywhere. @@ -2520,12 +2494,10 @@ template<typename T> class RepeatedPtrFieldBackInsertIterator *field_->Add() = *ptr_to_value; return *this; } -#if LANG_CXX11 RepeatedPtrFieldBackInsertIterator<T>& operator=(T&& value) { *field_->Add() = std::move(value); return *this; } -#endif RepeatedPtrFieldBackInsertIterator<T>& operator*() { return *this; } @@ -2640,7 +2612,7 @@ AllocatedRepeatedPtrFieldBackInserter( // RepeatedPtrField<T> temp_field; // temp_field.AddAllocated(new T); // ... // Do something with temp_field -// temp_field.ExtractSubrange(0, temp_field.size(), NULL); +// temp_field.ExtractSubrange(0, temp_field.size(), nullptr); // If you put temp_field on the arena this fails, because the ownership // transfers to the arena at the "AddAllocated" call and is not released anymore // causing a double delete. Using UnsafeArenaAddAllocated prevents this. diff --git a/src/google/protobuf/repeated_field_reflection_unittest.cc b/src/google/protobuf/repeated_field_reflection_unittest.cc index fd466565..74ec83b0 100644 --- a/src/google/protobuf/repeated_field_reflection_unittest.cc +++ b/src/google/protobuf/repeated_field_reflection_unittest.cc @@ -704,7 +704,7 @@ TEST(RepeatedFieldReflectionTest, RepeatedFieldRefDynamicMessage) { desc->FindFieldByName("repeated_int32"); DynamicMessageFactory factory; - google::protobuf::scoped_ptr<Message> dynamic_message(factory.GetPrototype(desc)->New()); + std::unique_ptr<Message> dynamic_message(factory.GetPrototype(desc)->New()); const Reflection* refl = dynamic_message->GetReflection(); MutableRepeatedFieldRef<int32> rf_int32 = diff --git a/src/google/protobuf/repeated_field_unittest.cc b/src/google/protobuf/repeated_field_unittest.cc index 16919711..053a4d68 100644 --- a/src/google/protobuf/repeated_field_unittest.cc +++ b/src/google/protobuf/repeated_field_unittest.cc @@ -383,8 +383,6 @@ TEST(RepeatedField, SelfAssign) { EXPECT_EQ(8, source.Get(1)); } -#if LANG_CXX11 - TEST(RepeatedField, MoveConstruct) { { RepeatedField<int> source; @@ -405,7 +403,7 @@ TEST(RepeatedField, MoveConstruct) { source->Add(1); source->Add(2); RepeatedField<int> destination = std::move(*source); - EXPECT_EQ(NULL, destination.GetArena()); + EXPECT_EQ(nullptr, destination.GetArena()); EXPECT_THAT(destination, ElementsAre(1, 2)); // This property isn't guaranteed but it's useful to have a test that would // catch changes in this area. @@ -517,8 +515,6 @@ TEST(RepeatedField, MoveAssign) { } } -#endif // LANG_CXX11 - TEST(RepeatedField, MutableDataIsMutable) { RepeatedField<int> field; field.Add(1); @@ -1045,8 +1041,6 @@ TEST(RepeatedPtrField, SelfAssign) { EXPECT_EQ("8", source.Get(1)); } -#if LANG_CXX11 - TEST(RepeatedPtrField, MoveConstruct) { { RepeatedPtrField<string> source; @@ -1067,7 +1061,7 @@ TEST(RepeatedPtrField, MoveConstruct) { *source->Add() = "1"; *source->Add() = "2"; RepeatedPtrField<string> destination = std::move(*source); - EXPECT_EQ(NULL, destination.GetArena()); + EXPECT_EQ(nullptr, destination.GetArena()); EXPECT_THAT(destination, ElementsAre("1", "2")); // This property isn't guaranteed but it's useful to have a test that would // catch changes in this area. @@ -1179,8 +1173,6 @@ TEST(RepeatedPtrField, MoveAssign) { } } -#endif // LANG_CXX11 - TEST(RepeatedPtrField, MutableDataIsMutable) { RepeatedPtrField<string> field; *field.Add() = "1"; @@ -1844,7 +1836,6 @@ TEST_F(RepeatedFieldInsertionIteratorsTest, EXPECT_EQ(testproto.DebugString(), goldenproto.DebugString()); } -#if LANG_CXX11 TEST_F(RepeatedFieldInsertionIteratorsTest, MoveStrings) { std::vector<string> src = {"a", "b", "c", "d"}; std::vector<string> copy = src; // copy since move leaves in undefined state @@ -1874,7 +1865,6 @@ TEST_F(RepeatedFieldInsertionIteratorsTest, MoveProtos) { testproto.repeated_nested_message(i).DebugString()); } } -#endif } // namespace diff --git a/src/google/protobuf/source_context.pb.cc b/src/google/protobuf/source_context.pb.cc index b9d8f3cb..af93e6b2 100644 --- a/src/google/protobuf/source_context.pb.cc +++ b/src/google/protobuf/source_context.pb.cc @@ -7,7 +7,6 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> -#include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> @@ -19,6 +18,7 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + namespace google { namespace protobuf { class SourceContextDefaultTypeInternal { @@ -29,14 +29,9 @@ class SourceContextDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto { -void InitDefaultsSourceContextImpl() { +static void InitDefaultsSourceContext() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_SourceContext_default_instance_; new (ptr) ::google::protobuf::SourceContext(); @@ -45,9 +40,11 @@ void InitDefaultsSourceContextImpl() { ::google::protobuf::SourceContext::InitAsDefaultInstance(); } -void InitDefaultsSourceContext() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSourceContextImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_SourceContext = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsSourceContext}, {}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_SourceContext.base); } ::google::protobuf::Metadata file_level_metadata[1]; @@ -68,17 +65,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_SourceContext_default_instance_), }; -void protobuf_AssignDescriptors() { +static void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/source_context.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/source_context.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } -void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); +static void protobuf_AssignDescriptorsOnce() { + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -87,7 +83,7 @@ void protobuf_RegisterTypes(const ::std::string&) { ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1); } -void AddDescriptorsImpl() { +static void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n$google/protobuf/source_context.proto\022\017" @@ -105,8 +101,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -128,16 +124,14 @@ const int SourceContext::kFileNameFieldNumber; SourceContext::SourceContext() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.SourceContext) } SourceContext::SourceContext(const SourceContext& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); file_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.file_name().size() > 0) { @@ -148,7 +142,6 @@ SourceContext::SourceContext(const SourceContext& from) void SourceContext::SharedCtor() { file_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - _cached_size_ = 0; } SourceContext::~SourceContext() { @@ -161,9 +154,7 @@ void SourceContext::SharedDtor() { } void SourceContext::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* SourceContext::descriptor() { ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::protobuf_AssignDescriptorsOnce(); @@ -171,7 +162,7 @@ const ::google::protobuf::Descriptor* SourceContext::descriptor() { } const SourceContext& SourceContext::default_instance() { - ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base); return *internal_default_instance(); } @@ -192,7 +183,7 @@ bool SourceContext::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.SourceContext) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -298,9 +289,7 @@ size_t SourceContext::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -356,9 +345,9 @@ void SourceContext::Swap(SourceContext* other) { } void SourceContext::InternalSwap(SourceContext* other) { using std::swap; - file_name_.Swap(&other->file_name_); + file_name_.Swap(&other->file_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata SourceContext::GetMetadata() const { @@ -372,7 +361,7 @@ void SourceContext::InternalSwap(SourceContext* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceContext* Arena::Create< ::google::protobuf::SourceContext >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceContext* Arena::CreateMaybeMessage< ::google::protobuf::SourceContext >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::SourceContext >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/source_context.pb.h b/src/google/protobuf/source_context.pb.h index 81893b1a..16ed21ca 100644 --- a/src/google/protobuf/source_context.pb.h +++ b/src/google/protobuf/source_context.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/source_context.proto -#ifndef PROTOBUF_google_2fprotobuf_2fsource_5fcontext_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2fsource_5fcontext_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto #include <string> @@ -24,12 +24,14 @@ #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> +#include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto { // Internal implementation detail -- do not use these members. @@ -42,11 +44,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsSourceContextImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsSourceContext(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsSourceContext(); -} } // namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto namespace google { namespace protobuf { @@ -57,7 +54,7 @@ LIBPROTOBUF_EXPORT extern SourceContextDefaultTypeInternal _SourceContext_defaul } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceContext* Arena::Create< ::google::protobuf::SourceContext>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceContext* Arena::CreateMaybeMessage<::google::protobuf::SourceContext>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -99,7 +96,7 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @ return reinterpret_cast<const SourceContext*>( &_SourceContext_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void Swap(SourceContext* other); @@ -109,32 +106,33 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @ // implements Message ---------------------------------------------- - inline SourceContext* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<SourceContext>(NULL); + inline SourceContext* New() const final { + return CreateMaybeMessage<SourceContext>(NULL); } - SourceContext* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create<SourceContext>(arena); + SourceContext* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<SourceContext>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const SourceContext& from); void MergeFrom(const SourceContext& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(SourceContext* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -145,7 +143,7 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @ } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -170,9 +168,8 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @ ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr file_name_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContextImpl(); }; // =================================================================== @@ -249,4 +246,4 @@ inline void SourceContext::set_allocated_file_name(::std::string* file_name) { // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2fsource_5fcontext_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto diff --git a/src/google/protobuf/struct.pb.cc b/src/google/protobuf/struct.pb.cc index 309a4d2d..4bf5d45c 100644 --- a/src/google/protobuf/struct.pb.cc +++ b/src/google/protobuf/struct.pb.cc @@ -7,7 +7,6 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> -#include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> @@ -19,6 +18,10 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + +namespace protobuf_google_2fprotobuf_2fstruct_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fstruct_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_ListValue; +} // namespace protobuf_google_2fprotobuf_2fstruct_2eproto namespace google { namespace protobuf { class Struct_FieldsEntry_DoNotUseDefaultTypeInternal { @@ -50,14 +53,9 @@ class ListValueDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2fstruct_2eproto { -void InitDefaultsListValueImpl() { +static void InitDefaultsListValue() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_Struct_FieldsEntry_DoNotUse_default_instance_; new (ptr) ::google::protobuf::Struct_FieldsEntry_DoNotUse(); @@ -83,9 +81,11 @@ void InitDefaultsListValueImpl() { ::google::protobuf::ListValue::InitAsDefaultInstance(); } -void InitDefaultsListValue() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsListValueImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_ListValue = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsListValue}, {}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_ListValue.base); } ::google::protobuf::Metadata file_level_metadata[4]; @@ -140,17 +140,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_ListValue_default_instance_), }; -void protobuf_AssignDescriptors() { +static void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/struct.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/struct.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, file_level_enum_descriptors, NULL); } -void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); +static void protobuf_AssignDescriptorsOnce() { + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -159,7 +158,7 @@ void protobuf_RegisterTypes(const ::std::string&) { ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 4); } -void AddDescriptorsImpl() { +static void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n\034google/protobuf/struct.proto\022\017google.p" @@ -187,8 +186,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -240,9 +239,8 @@ const int Struct::kFieldsFieldNumber; Struct::Struct() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Struct) } @@ -250,22 +248,20 @@ Struct::Struct(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), fields_(arena) { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Struct) } Struct::Struct(const Struct& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); fields_.MergeFrom(from.fields_); // @@protoc_insertion_point(copy_constructor:google.protobuf.Struct) } void Struct::SharedCtor() { - _cached_size_ = 0; } Struct::~Struct() { @@ -284,9 +280,7 @@ void Struct::ArenaDtor(void* object) { void Struct::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Struct::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Struct::descriptor() { ::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce(); @@ -294,7 +288,7 @@ const ::google::protobuf::Descriptor* Struct::descriptor() { } const Struct& Struct::default_instance() { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); return *internal_default_instance(); } @@ -315,7 +309,7 @@ bool Struct::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Struct) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -385,7 +379,7 @@ void Struct::SerializeWithCachedSizes( if (output->IsSerializationDeterministic() && this->fields().size() > 1) { - ::google::protobuf::scoped_array<SortItem> items( + ::std::unique_ptr<SortItem[]> items( new SortItem[this->fields().size()]); typedef ::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::size_type size_type; size_type n = 0; @@ -395,7 +389,7 @@ void Struct::SerializeWithCachedSizes( items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); - ::google::protobuf::scoped_ptr<Struct_FieldsEntry_DoNotUse> entry; + ::std::unique_ptr<Struct_FieldsEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(fields_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); @@ -407,7 +401,7 @@ void Struct::SerializeWithCachedSizes( Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]); } } else { - ::google::protobuf::scoped_ptr<Struct_FieldsEntry_DoNotUse> entry; + ::std::unique_ptr<Struct_FieldsEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_iterator it = this->fields().begin(); it != this->fields().end(); ++it) { @@ -454,7 +448,7 @@ void Struct::SerializeWithCachedSizes( if (deterministic && this->fields().size() > 1) { - ::google::protobuf::scoped_array<SortItem> items( + ::std::unique_ptr<SortItem[]> items( new SortItem[this->fields().size()]); typedef ::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::size_type size_type; size_type n = 0; @@ -464,7 +458,7 @@ void Struct::SerializeWithCachedSizes( items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); - ::google::protobuf::scoped_ptr<Struct_FieldsEntry_DoNotUse> entry; + ::std::unique_ptr<Struct_FieldsEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(fields_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); @@ -478,7 +472,7 @@ void Struct::SerializeWithCachedSizes( Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]); } } else { - ::google::protobuf::scoped_ptr<Struct_FieldsEntry_DoNotUse> entry; + ::std::unique_ptr<Struct_FieldsEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_iterator it = this->fields().begin(); it != this->fields().end(); ++it) { @@ -517,7 +511,7 @@ size_t Struct::ByteSizeLong() const { total_size += 1 * ::google::protobuf::internal::FromIntSize(this->fields_size()); { - ::google::protobuf::scoped_ptr<Struct_FieldsEntry_DoNotUse> entry; + ::std::unique_ptr<Struct_FieldsEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_iterator it = this->fields().begin(); it != this->fields().end(); ++it) { @@ -534,9 +528,7 @@ size_t Struct::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -606,7 +598,6 @@ void Struct::InternalSwap(Struct* other) { using std::swap; fields_.Swap(&other->fields_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Struct::GetMetadata() const { @@ -669,24 +660,22 @@ const int Value::kListValueFieldNumber; Value::Value() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Value) } Value::Value(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Value) } Value::Value(const Value& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); clear_has_kind(); switch (from.kind_case()) { @@ -723,7 +712,6 @@ Value::Value(const Value& from) void Value::SharedCtor() { clear_has_kind(); - _cached_size_ = 0; } Value::~Value() { @@ -745,9 +733,7 @@ void Value::ArenaDtor(void* object) { void Value::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Value::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Value::descriptor() { ::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce(); @@ -755,7 +741,7 @@ const ::google::protobuf::Descriptor* Value::descriptor() { } const Value& Value::default_instance() { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); return *internal_default_instance(); } @@ -816,7 +802,7 @@ bool Value::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Value) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -960,13 +946,13 @@ void Value::SerializeWithCachedSizes( // .google.protobuf.Struct struct_value = 5; if (has_struct_value()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 5, *kind_.struct_value_, output); + 5, this->_internal_struct_value(), output); } // .google.protobuf.ListValue list_value = 6; if (has_list_value()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 6, *kind_.list_value_, output); + 6, this->_internal_list_value(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { @@ -1014,14 +1000,14 @@ void Value::SerializeWithCachedSizes( if (has_struct_value()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 5, *kind_.struct_value_, deterministic, target); + 5, this->_internal_struct_value(), deterministic, target); } // .google.protobuf.ListValue list_value = 6; if (has_list_value()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 6, *kind_.list_value_, deterministic, target); + 6, this->_internal_list_value(), deterministic, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { @@ -1084,9 +1070,7 @@ size_t Value::ByteSizeLong() const { } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1185,7 +1169,6 @@ void Value::InternalSwap(Value* other) { swap(kind_, other->kind_); swap(_oneof_case_[0], other->_oneof_case_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Value::GetMetadata() const { @@ -1204,9 +1187,8 @@ const int ListValue::kValuesFieldNumber; ListValue::ListValue() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.ListValue) } @@ -1214,7 +1196,7 @@ ListValue::ListValue(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), values_(arena) { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.ListValue) @@ -1222,14 +1204,12 @@ ListValue::ListValue(::google::protobuf::Arena* arena) ListValue::ListValue(const ListValue& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - values_(from.values_), - _cached_size_(0) { + values_(from.values_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.ListValue) } void ListValue::SharedCtor() { - _cached_size_ = 0; } ListValue::~ListValue() { @@ -1248,9 +1228,7 @@ void ListValue::ArenaDtor(void* object) { void ListValue::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void ListValue::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* ListValue::descriptor() { ::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1258,7 +1236,7 @@ const ::google::protobuf::Descriptor* ListValue::descriptor() { } const ListValue& ListValue::default_instance() { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); return *internal_default_instance(); } @@ -1279,7 +1257,7 @@ bool ListValue::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.ListValue) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1381,9 +1359,7 @@ size_t ListValue::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1453,7 +1429,6 @@ void ListValue::InternalSwap(ListValue* other) { using std::swap; CastToBase(&values_)->InternalSwap(CastToBase(&other->values_)); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata ListValue::GetMetadata() const { @@ -1467,16 +1442,16 @@ void ListValue::InternalSwap(ListValue* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Struct_FieldsEntry_DoNotUse* Arena::CreateMessage< ::google::protobuf::Struct_FieldsEntry_DoNotUse >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Struct_FieldsEntry_DoNotUse* Arena::CreateMaybeMessage< ::google::protobuf::Struct_FieldsEntry_DoNotUse >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Struct_FieldsEntry_DoNotUse >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Struct* Arena::CreateMessage< ::google::protobuf::Struct >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Struct* Arena::CreateMaybeMessage< ::google::protobuf::Struct >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Struct >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Value* Arena::CreateMessage< ::google::protobuf::Value >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Value* Arena::CreateMaybeMessage< ::google::protobuf::Value >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Value >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ListValue* Arena::CreateMessage< ::google::protobuf::ListValue >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ListValue* Arena::CreateMaybeMessage< ::google::protobuf::ListValue >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::ListValue >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/struct.pb.h b/src/google/protobuf/struct.pb.h index 91aa3cf2..75665ff2 100644 --- a/src/google/protobuf/struct.pb.h +++ b/src/google/protobuf/struct.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/struct.proto -#ifndef PROTOBUF_google_2fprotobuf_2fstruct_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2fstruct_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto #include <string> @@ -24,6 +24,7 @@ #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> +#include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export @@ -34,6 +35,7 @@ #include <google/protobuf/generated_enum_reflection.h> #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fstruct_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2fstruct_2eproto { // Internal implementation detail -- do not use these members. @@ -46,11 +48,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsListValueImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsListValue(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsListValue(); -} } // namespace protobuf_google_2fprotobuf_2fstruct_2eproto namespace google { namespace protobuf { @@ -70,10 +67,10 @@ LIBPROTOBUF_EXPORT extern ValueDefaultTypeInternal _Value_default_instance_; } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::ListValue* Arena::CreateMessage< ::google::protobuf::ListValue>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Struct* Arena::CreateMessage< ::google::protobuf::Struct>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Struct_FieldsEntry_DoNotUse* Arena::CreateMessage< ::google::protobuf::Struct_FieldsEntry_DoNotUse>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Value* Arena::CreateMessage< ::google::protobuf::Value>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::ListValue* Arena::CreateMaybeMessage<::google::protobuf::ListValue>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Struct* Arena::CreateMaybeMessage<::google::protobuf::Struct>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Struct_FieldsEntry_DoNotUse* Arena::CreateMaybeMessage<::google::protobuf::Struct_FieldsEntry_DoNotUse>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Value* Arena::CreateMaybeMessage<::google::protobuf::Value>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -116,7 +113,7 @@ public: Struct_FieldsEntry_DoNotUse(::google::protobuf::Arena* arena); void MergeFrom(const Struct_FieldsEntry_DoNotUse& other); static const Struct_FieldsEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const Struct_FieldsEntry_DoNotUse*>(&_Struct_FieldsEntry_DoNotUse_default_instance_); } - void MergeFrom(const ::google::protobuf::Message& other) PROTOBUF_FINAL; + void MergeFrom(const ::google::protobuf::Message& other) final; ::google::protobuf::Metadata GetMetadata() const; }; @@ -148,10 +145,10 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -162,7 +159,7 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc return reinterpret_cast<const Struct*>( &_Struct_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 1; void UnsafeArenaSwap(Struct* other); @@ -173,32 +170,33 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc // implements Message ---------------------------------------------- - inline Struct* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Struct>(NULL); + inline Struct* New() const final { + return CreateMaybeMessage<Struct>(NULL); } - Struct* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Struct>(arena); + Struct* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<Struct>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Struct& from); void MergeFrom(const Struct& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Struct* other); protected: explicit Struct(::google::protobuf::Arena* arena); @@ -214,7 +212,7 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -243,9 +241,8 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > fields_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fstruct_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValueImpl(); }; // ------------------------------------------------------------------- @@ -275,10 +272,10 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -299,7 +296,7 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ return reinterpret_cast<const Value*>( &_Value_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 2; void UnsafeArenaSwap(Value* other); @@ -310,32 +307,33 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ // implements Message ---------------------------------------------- - inline Value* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Value>(NULL); + inline Value* New() const final { + return CreateMaybeMessage<Value>(NULL); } - Value* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Value>(arena); + Value* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<Value>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Value& from); void MergeFrom(const Value& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Value* other); protected: explicit Value(::google::protobuf::Arena* arena); @@ -351,7 +349,7 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -414,6 +412,9 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ bool has_struct_value() const; void clear_struct_value(); static const int kStructValueFieldNumber = 5; + private: + const ::google::protobuf::Struct& _internal_struct_value() const; + public: const ::google::protobuf::Struct& struct_value() const; ::google::protobuf::Struct* release_struct_value(); ::google::protobuf::Struct* mutable_struct_value(); @@ -426,6 +427,9 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ bool has_list_value() const; void clear_list_value(); static const int kListValueFieldNumber = 6; + private: + const ::google::protobuf::ListValue& _internal_list_value() const; + public: const ::google::protobuf::ListValue& list_value() const; ::google::protobuf::ListValue* release_list_value(); ::google::protobuf::ListValue* mutable_list_value(); @@ -434,6 +438,7 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ ::google::protobuf::ListValue* list_value); ::google::protobuf::ListValue* unsafe_arena_release_list_value(); + void clear_kind(); KindCase kind_case() const; // @@protoc_insertion_point(class_scope:google.protobuf.Value) private: @@ -445,7 +450,6 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ void set_has_list_value(); inline bool has_kind() const; - void clear_kind(); inline void clear_has_kind(); ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; @@ -461,11 +465,10 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ ::google::protobuf::Struct* struct_value_; ::google::protobuf::ListValue* list_value_; } kind_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::uint32 _oneof_case_[1]; friend struct ::protobuf_google_2fprotobuf_2fstruct_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValueImpl(); }; // ------------------------------------------------------------------- @@ -495,10 +498,10 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -509,7 +512,7 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro return reinterpret_cast<const ListValue*>( &_ListValue_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 3; void UnsafeArenaSwap(ListValue* other); @@ -520,32 +523,33 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro // implements Message ---------------------------------------------- - inline ListValue* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<ListValue>(NULL); + inline ListValue* New() const final { + return CreateMaybeMessage<ListValue>(NULL); } - ListValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<ListValue>(arena); + ListValue* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<ListValue>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const ListValue& from); void MergeFrom(const ListValue& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(ListValue* other); protected: explicit ListValue(::google::protobuf::Arena* arena); @@ -561,7 +565,7 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -587,9 +591,8 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::Value > values_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fstruct_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValueImpl(); }; // =================================================================== @@ -852,13 +855,16 @@ inline void Value::clear_struct_value() { clear_has_kind(); } } +inline const ::google::protobuf::Struct& Value::_internal_struct_value() const { + return *kind_.struct_value_; +} inline ::google::protobuf::Struct* Value::release_struct_value() { // @@protoc_insertion_point(field_release:google.protobuf.Value.struct_value) if (has_struct_value()) { clear_has_kind(); ::google::protobuf::Struct* temp = kind_.struct_value_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } kind_.struct_value_ = NULL; return temp; @@ -895,7 +901,7 @@ inline ::google::protobuf::Struct* Value::mutable_struct_value() { if (!has_struct_value()) { clear_kind(); set_has_struct_value(); - kind_.struct_value_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::Struct >( + kind_.struct_value_ = CreateMaybeMessage< ::google::protobuf::Struct >( GetArenaNoVirtual()); } // @@protoc_insertion_point(field_mutable:google.protobuf.Value.struct_value) @@ -917,13 +923,16 @@ inline void Value::clear_list_value() { clear_has_kind(); } } +inline const ::google::protobuf::ListValue& Value::_internal_list_value() const { + return *kind_.list_value_; +} inline ::google::protobuf::ListValue* Value::release_list_value() { // @@protoc_insertion_point(field_release:google.protobuf.Value.list_value) if (has_list_value()) { clear_has_kind(); ::google::protobuf::ListValue* temp = kind_.list_value_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } kind_.list_value_ = NULL; return temp; @@ -960,7 +969,7 @@ inline ::google::protobuf::ListValue* Value::mutable_list_value() { if (!has_list_value()) { clear_kind(); set_has_list_value(); - kind_.list_value_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ListValue >( + kind_.list_value_ = CreateMaybeMessage< ::google::protobuf::ListValue >( GetArenaNoVirtual()); } // @@protoc_insertion_point(field_mutable:google.protobuf.Value.list_value) @@ -1028,7 +1037,7 @@ ListValue::values() const { namespace google { namespace protobuf { -template <> struct is_proto_enum< ::google::protobuf::NullValue> : ::google::protobuf::internal::true_type {}; +template <> struct is_proto_enum< ::google::protobuf::NullValue> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::NullValue>() { return ::google::protobuf::NullValue_descriptor(); @@ -1039,4 +1048,4 @@ inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::NullValue>() // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2fstruct_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto diff --git a/src/google/protobuf/stubs/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/callback.h b/src/google/protobuf/stubs/callback.h index 9ec04979..6888f136 100644 --- a/src/google/protobuf/stubs/callback.h +++ b/src/google/protobuf/stubs/callback.h @@ -1,8 +1,9 @@ #ifndef GOOGLE_PROTOBUF_STUBS_CALLBACK_H_ #define GOOGLE_PROTOBUF_STUBS_CALLBACK_H_ +#include <type_traits> + #include <google/protobuf/stubs/macros.h> -#include <google/protobuf/stubs/type_traits.h> // =================================================================== // emulates google3/base/callback.h @@ -342,7 +343,7 @@ class FunctionResultCallback_1_1 : public ResultCallback1<R, A1> { template <typename T> struct InternalConstRef { - typedef typename remove_reference<T>::type base_type; + typedef typename std::remove_reference<T>::type base_type; typedef const base_type& type; }; @@ -397,11 +398,11 @@ class MethodResultCallback_5_2 : public ResultCallback2<R, A1, A2> { T* object_; MethodType method_; bool self_deleting_; - typename remove_reference<P1>::type p1_; - typename remove_reference<P2>::type p2_; - typename remove_reference<P3>::type p3_; - typename remove_reference<P4>::type p4_; - typename remove_reference<P5>::type p5_; + typename std::remove_reference<P1>::type p1_; + typename std::remove_reference<P2>::type p2_; + typename std::remove_reference<P3>::type p3_; + typename std::remove_reference<P4>::type p4_; + typename std::remove_reference<P5>::type p5_; }; } // namespace internal diff --git a/src/google/protobuf/stubs/casts.h b/src/google/protobuf/stubs/casts.h index be652849..35e2dba0 100644 --- a/src/google/protobuf/stubs/casts.h +++ b/src/google/protobuf/stubs/casts.h @@ -31,8 +31,9 @@ #ifndef GOOGLE_PROTOBUF_CASTS_H__ #define GOOGLE_PROTOBUF_CASTS_H__ +#include <type_traits> + #include <google/protobuf/stubs/common.h> -#include <google/protobuf/stubs/type_traits.h> namespace google { namespace protobuf { @@ -95,7 +96,7 @@ inline To down_cast(From* f) { // so we only accept pointers template<typename To, typename From> // use like this: down_cast<T&>(foo); inline To down_cast(From& f) { - typedef typename remove_reference<To>::type* ToAsPointer; + typedef typename std::remove_reference<To>::type* ToAsPointer; // Ensures that To is a sub-type of From *. This test is here only // for compile-time type checking, and has no overhead in an // optimized build at run-time, as it will be optimized away diff --git a/src/google/protobuf/stubs/common.cc b/src/google/protobuf/stubs/common.cc index 73822168..33d24c57 100755 --- a/src/google/protobuf/stubs/common.cc +++ b/src/google/protobuf/stubs/common.cc @@ -314,86 +314,6 @@ namespace internal { FunctionClosure0::~FunctionClosure0() {} } void DoNothing() {} // =================================================================== -// emulates google3/base/mutex.cc - -#ifdef _WIN32 - -struct Mutex::Internal { - CRITICAL_SECTION mutex; -#ifndef NDEBUG - // Used only to implement AssertHeld(). - DWORD thread_id; -#endif -}; - -Mutex::Mutex() - : mInternal(new Internal) { - InitializeCriticalSection(&mInternal->mutex); -} - -Mutex::~Mutex() { - DeleteCriticalSection(&mInternal->mutex); - delete mInternal; -} - -void Mutex::Lock() { - EnterCriticalSection(&mInternal->mutex); -#ifndef NDEBUG - mInternal->thread_id = GetCurrentThreadId(); -#endif -} - -void Mutex::Unlock() { -#ifndef NDEBUG - mInternal->thread_id = 0; -#endif - LeaveCriticalSection(&mInternal->mutex); -} - -void Mutex::AssertHeld() { -#ifndef NDEBUG - GOOGLE_DCHECK_EQ(mInternal->thread_id, GetCurrentThreadId()); -#endif -} - -#elif defined(HAVE_PTHREAD) - -struct Mutex::Internal { - pthread_mutex_t mutex; -}; - -Mutex::Mutex() - : mInternal(new Internal) { - pthread_mutex_init(&mInternal->mutex, NULL); -} - -Mutex::~Mutex() { - pthread_mutex_destroy(&mInternal->mutex); - delete mInternal; -} - -void Mutex::Lock() { - int result = pthread_mutex_lock(&mInternal->mutex); - if (result != 0) { - GOOGLE_LOG(FATAL) << "pthread_mutex_lock: " << strerror(result); - } -} - -void Mutex::Unlock() { - int result = pthread_mutex_unlock(&mInternal->mutex); - if (result != 0) { - GOOGLE_LOG(FATAL) << "pthread_mutex_unlock: " << strerror(result); - } -} - -void Mutex::AssertHeld() { - // pthreads dosn't provide a way to check which thread holds the mutex. - // TODO(kenton): Maybe keep track of locking thread ID like with WIN32? -} - -#endif - -// =================================================================== // emulates google3/util/endian/endian.h // // TODO(xiaofeng): PROTOBUF_LITTLE_ENDIAN is unfortunately defined in @@ -430,9 +350,9 @@ struct ShutdownData { } } - vector<void (*)()> functions; - vector<const std::string*> strings; - vector<const MessageLite*> messages; + std::vector<void (*)()> functions; + std::vector<const std::string*> strings; + std::vector<const MessageLite*> messages; Mutex mutex; }; diff --git a/src/google/protobuf/stubs/common.h b/src/google/protobuf/stubs/common.h index d11b8100..c336383d 100644 --- a/src/google/protobuf/stubs/common.h +++ b/src/google/protobuf/stubs/common.h @@ -38,6 +38,7 @@ #include <algorithm> #include <iostream> #include <map> +#include <memory> #include <set> #include <string> #include <vector> @@ -48,7 +49,6 @@ // TODO(liujisi): Remove the following includes after the include clean-up. #include <google/protobuf/stubs/logging.h> -#include <google/protobuf/stubs/scoped_ptr.h> #include <google/protobuf/stubs/mutex.h> #include <google/protobuf/stubs/callback.h> @@ -229,12 +229,7 @@ class FatalException : public std::exception { // This is at the end of the file instead of the beginning to work around a bug // in some versions of MSVC. -// TODO(acozzette): remove these using statements -using std::istream; -using std::ostream; -using std::pair; using std::string; -using std::vector; } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/stubs/common_unittest.cc b/src/google/protobuf/stubs/common_unittest.cc index f9e2cfd4..798a2a27 100644 --- a/src/google/protobuf/stubs/common_unittest.cc +++ b/src/google/protobuf/stubs/common_unittest.cc @@ -75,7 +75,7 @@ TEST(CommonTest, IntMinMaxConstants) { EXPECT_EQ(0, kuint64max + 1); } -vector<string> captured_messages_; +std::vector<string> captured_messages_; void CaptureLog(LogLevel level, const char* filename, int line, const string& message) { diff --git a/src/google/protobuf/stubs/hash.h b/src/google/protobuf/stubs/hash.h index 218cd948..fd8ba156 100644 --- a/src/google/protobuf/stubs/hash.h +++ b/src/google/protobuf/stubs/hash.h @@ -93,7 +93,7 @@ # endif // GCC <= 4.1 does not define std::tr1::hash for `long long int` or `long long unsigned int` -# if __GNUC__ == 4 && defined(__GNUC__MINOR__) && __GNUC__MINOR__ <= 1 +# if __GNUC__ == 4 && defined(__GNUC_MINOR__) && __GNUC_MINOR__ <= 1 # undef GOOGLE_PROTOBUF_HAS_TR1 # undef GOOGLE_PROTOBUF_HAVE_HASH_MAP # undef GOOGLE_PROTOBUF_HAVE_HASH_SET @@ -235,7 +235,8 @@ class hash_set : public std::set<Key, HashFcn> { HashFcn hash_function() const { return HashFcn(); } }; -#elif defined(_MSC_VER) && !defined(_STLPORT_VERSION) +#elif defined(_MSC_VER) && !defined(_STLPORT_VERSION) && \ + !(defined(_LIBCPP_STD_VER) && _LIBCPP_STD_VER >= 11) template <typename Key> struct hash : public GOOGLE_PROTOBUF_HASH_COMPARE<Key> { @@ -408,8 +409,8 @@ struct hash<string> { }; template <typename First, typename Second> -struct hash<pair<First, Second> > { - inline size_t operator()(const pair<First, Second>& key) const { +struct hash<std::pair<First, Second> > { + inline size_t operator()(const std::pair<First, Second>& key) const { size_t first_hash = hash<First>()(key.first); size_t second_hash = hash<Second>()(key.second); @@ -420,8 +421,8 @@ struct hash<pair<First, Second> > { static const size_t bucket_size = 4; static const size_t min_buckets = 8; - inline bool operator()(const pair<First, Second>& a, - const pair<First, Second>& b) const { + inline bool operator()(const std::pair<First, Second>& a, + const std::pair<First, Second>& b) const { return a < b; } }; diff --git a/src/google/protobuf/stubs/int128.cc b/src/google/protobuf/stubs/int128.cc index a5090801..7b993e8f 100644 --- a/src/google/protobuf/stubs/int128.cc +++ b/src/google/protobuf/stubs/int128.cc @@ -76,52 +76,36 @@ static inline int Fls128(uint128 n) { return Fls64(Uint128Low64(n)); } -// Long division/modulo for uint128 implemented using the shift-subtract -// division algorithm adapted from: -// http://stackoverflow.com/questions/5386377/division-without-using void uint128::DivModImpl(uint128 dividend, uint128 divisor, uint128* quotient_ret, uint128* remainder_ret) { if (divisor == 0) { GOOGLE_LOG(FATAL) << "Division or mod by zero: dividend.hi=" << dividend.hi_ << ", lo=" << dividend.lo_; - } - - if (divisor > dividend) { + } else if (dividend < divisor) { *quotient_ret = 0; *remainder_ret = dividend; return; - } - - if (divisor == dividend) { - *quotient_ret = 1; - *remainder_ret = 0; - return; - } - - uint128 denominator = divisor; - uint128 position = 1; - uint128 quotient = 0; - - // Left aligns the MSB of the denominator and the dividend. - int shift = Fls128(dividend) - Fls128(denominator); - denominator <<= shift; - position <<= shift; - - // Uses shift-subtract algorithm to divide dividend by denominator. The - // remainder will be left in dividend. - while (position > 0) { - if (dividend >= denominator) { - dividend -= denominator; - quotient |= position; + } else { + int dividend_bit_length = Fls128(dividend); + int divisor_bit_length = Fls128(divisor); + int difference = dividend_bit_length - divisor_bit_length; + uint128 quotient = 0; + while (difference >= 0) { + quotient <<= 1; + uint128 shifted_divisor = divisor << difference; + if (shifted_divisor <= dividend) { + dividend -= shifted_divisor; + quotient += 1; + } + difference -= 1; } - position >>= 1; - denominator >>= 1; + //record the final quotient and remainder + *quotient_ret = quotient; + *remainder_ret = dividend; } - - *quotient_ret = quotient; - *remainder_ret = dividend; } + uint128& uint128::operator/=(const uint128& divisor) { uint128 quotient = 0; uint128 remainder = 0; diff --git a/src/google/protobuf/stubs/io_win32.cc b/src/google/protobuf/stubs/io_win32.cc index 5ead98c8..4407facb 100644 --- a/src/google/protobuf/stubs/io_win32.cc +++ b/src/google/protobuf/stubs/io_win32.cc @@ -52,13 +52,13 @@ #include <errno.h> #include <fcntl.h> #include <io.h> +#include <memory> #include <sys/stat.h> #include <sys/types.h> #include <wctype.h> #include <windows.h> #include <google/protobuf/stubs/io_win32.h> -#include <google/protobuf/stubs/scoped_ptr.h> #include <memory> #include <sstream> @@ -229,7 +229,7 @@ bool as_windows_path(const char* path, wstring* result) { if (size == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) { return false; } - scoped_array<WCHAR> wcwd(new WCHAR[size]); + std::unique_ptr<WCHAR[]> wcwd(new WCHAR[size]); ::GetCurrentDirectoryW(size, wcwd.get()); wpath = join_paths(wcwd.get(), wpath); } @@ -371,7 +371,7 @@ bool wcs_to_mbs(const WCHAR* s, string* out, bool outUtf8) { || usedDefaultChar) { return false; } - scoped_array<CHAR> astr(new CHAR[size]); + std::unique_ptr<CHAR[]> astr(new CHAR[size]); WideCharToMultiByte( outUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, astr.get(), size, NULL, NULL); out->assign(astr.get()); @@ -390,7 +390,7 @@ bool mbs_to_wcs(const char* s, wstring* out, bool inUtf8) { if (size == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) { return false; } - scoped_array<WCHAR> wstr(new WCHAR[size]); + std::unique_ptr<WCHAR[]> wstr(new WCHAR[size]); MultiByteToWideChar( inUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, wstr.get(), size + 1); out->assign(wstr.get()); diff --git a/src/google/protobuf/stubs/io_win32_unittest.cc b/src/google/protobuf/stubs/io_win32_unittest.cc index b216aece..c933757c 100644 --- a/src/google/protobuf/stubs/io_win32_unittest.cc +++ b/src/google/protobuf/stubs/io_win32_unittest.cc @@ -48,7 +48,6 @@ #include <windows.h> #include <google/protobuf/stubs/io_win32.h> -#include <google/protobuf/stubs/scoped_ptr.h> #include <gtest/gtest.h> #include <memory> @@ -115,7 +114,7 @@ void StripTrailingSlashes(string* str) { bool GetEnvVarAsUtf8(const WCHAR* name, string* result) { DWORD size = ::GetEnvironmentVariableW(name, NULL, 0); if (size > 0 && GetLastError() != ERROR_ENVVAR_NOT_FOUND) { - scoped_array<WCHAR> wcs(new WCHAR[size]); + std::unique_ptr<WCHAR[]> wcs(new WCHAR[size]); ::GetEnvironmentVariableW(name, wcs.get(), size); // GetEnvironmentVariableA retrieves an Active-Code-Page-encoded text which // we'd first need to convert to UTF-16 then to UTF-8, because there seems @@ -131,7 +130,7 @@ bool GetEnvVarAsUtf8(const WCHAR* name, string* result) { bool GetCwdAsUtf8(string* result) { DWORD size = ::GetCurrentDirectoryW(0, NULL); if (size > 0) { - scoped_array<WCHAR> wcs(new WCHAR[size]); + std::unique_ptr<WCHAR[]> wcs(new WCHAR[size]); ::GetCurrentDirectoryW(size, wcs.get()); // GetCurrentDirectoryA retrieves an Active-Code-Page-encoded text which // we'd first need to convert to UTF-16 then to UTF-8, because there seems @@ -402,7 +401,7 @@ TEST_F(IoWin32Test, ChdirTestNonAscii) { TEST_F(IoWin32Test, AsWindowsPathTest) { DWORD size = GetCurrentDirectoryW(0, NULL); - scoped_array<wchar_t> cwd_str(new wchar_t[size]); + std::unique_ptr<wchar_t[]> cwd_str(new wchar_t[size]); EXPECT_GT(GetCurrentDirectoryW(size, cwd_str.get()), 0); wstring cwd = wstring(L"\\\\?\\") + cwd_str.get(); diff --git a/src/google/protobuf/stubs/map_util.h b/src/google/protobuf/stubs/map_util.h index 887f12a6..3e6d381f 100644 --- a/src/google/protobuf/stubs/map_util.h +++ b/src/google/protobuf/stubs/map_util.h @@ -654,7 +654,8 @@ InsertOrReturnExisting( // delete EraseKeyReturnValuePtr(&my_map, "abc"); // // Use returned value: -// scoped_ptr<MyType> value_ptr(EraseKeyReturnValuePtr(&my_map, "abc")); +// std::unique_ptr<MyType> value_ptr( +// EraseKeyReturnValuePtr(&my_map, "abc")); // if (value_ptr.get()) // value_ptr->DoSomething(); // @@ -708,7 +709,7 @@ void AppendKeysFromMap(const MapContainer& map_container, // without the complexity of a SFINAE-based solution.) template <class MapContainer, class KeyType> void AppendKeysFromMap(const MapContainer& map_container, - vector<KeyType>* key_container) { + std::vector<KeyType>* key_container) { GOOGLE_CHECK(key_container != NULL); // We now have the opportunity to call reserve(). Calling reserve() every // time is a bad idea for some use cases: libstdc++'s implementation of @@ -752,7 +753,7 @@ void AppendValuesFromMap(const MapContainer& map_container, // without the complexity of a SFINAE-based solution.) template <class MapContainer, class ValueType> void AppendValuesFromMap(const MapContainer& map_container, - vector<ValueType>* value_container) { + std::vector<ValueType>* value_container) { GOOGLE_CHECK(value_container != NULL); // See AppendKeysFromMap for why this is done. if (value_container->empty()) { diff --git a/src/google/protobuf/stubs/mathlimits.h b/src/google/protobuf/stubs/mathlimits.h index 2391ac4c..9c9d0e9a 100644 --- a/src/google/protobuf/stubs/mathlimits.h +++ b/src/google/protobuf/stubs/mathlimits.h @@ -243,7 +243,7 @@ DECL_UNSIGNED_INT_LIMITS(unsigned long long int) #endif // ========================================================================= // -#ifdef WIN32 // Lacks built-in isnan() and isinf() +#if WIN32 && !__MINGW32__ // Lacks built-in isnan() and isinf() #define DECL_FP_LIMIT_FUNCS \ static bool IsFinite(const Type x) { return _finite(x); } \ static bool IsNaN(const Type x) { return _isnan(x); } \ diff --git a/src/google/protobuf/stubs/mutex.h b/src/google/protobuf/stubs/mutex.h index 174290f6..47edb7a3 100644 --- a/src/google/protobuf/stubs/mutex.h +++ b/src/google/protobuf/stubs/mutex.h @@ -30,46 +30,48 @@ #ifndef GOOGLE_PROTOBUF_STUBS_MUTEX_H_ #define GOOGLE_PROTOBUF_STUBS_MUTEX_H_ -#ifdef GOOGLE_PROTOBUF_NO_THREADLOCAL -#include <pthread.h> -#endif +#include <mutex> #include <google/protobuf/stubs/macros.h> +// Define thread-safety annotations for use below, if we are building with +// Clang. +#if defined(__clang__) && !defined(SWIG) +#define GOOGLE_PROTOBUF_ACQUIRE(...) \ + __attribute__((acquire_capability(__VA_ARGS__))) +#define GOOGLE_PROTOBUF_RELEASE(...) \ + __attribute__((release_capability(__VA_ARGS__))) +#else +#define GOOGLE_PROTOBUF_ACQUIRE(...) +#define GOOGLE_PROTOBUF_RELEASE(...) +#endif + // =================================================================== // emulates google3/base/mutex.h namespace google { namespace protobuf { namespace internal { -// A Mutex is a non-reentrant (aka non-recursive) mutex. At most one thread T -// may hold a mutex at a given time. If T attempts to Lock() the same Mutex -// while holding it, T will deadlock. -class LIBPROTOBUF_EXPORT Mutex { - public: - // Create a Mutex that is not held by anybody. - Mutex(); - - // Destructor - ~Mutex(); - - // Block if necessary until this Mutex is free, then acquire it exclusively. - void Lock(); - - // Release this Mutex. Caller must hold it exclusively. - void Unlock(); +#define GOOGLE_PROTOBUF_LINKER_INITIALIZED +// Mutex is a natural type to wrap. As both google and other organization have +// specialized mutexes. gRPC also provides an injection mechanism for custom +// mutexes. +class LIBPROTOBUF_EXPORT WrappedMutex { + public: + WrappedMutex() = default; + void Lock() GOOGLE_PROTOBUF_ACQUIRE() { mu_.lock(); } + void Unlock() GOOGLE_PROTOBUF_RELEASE() { mu_.unlock(); } // Crash if this Mutex is not held exclusively by this thread. // May fail to crash when it should; will never crash when it should not. - void AssertHeld(); + void AssertHeld() const {} private: - struct Internal; - Internal* mInternal; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Mutex); + std::mutex mu_; }; +using Mutex = WrappedMutex; + // MutexLock(mu) acquires mu when constructed and releases it when destroyed. class LIBPROTOBUF_EXPORT MutexLock { public: @@ -133,8 +135,10 @@ using internal::ReaderMutexLock; using internal::WriterMutexLock; using internal::MutexLockMaybe; - } // namespace protobuf } // namespace google +#undef GOOGLE_PROTOBUF_ACQUIRE +#undef GOOGLE_PROTOBUF_RELEASE + #endif // GOOGLE_PROTOBUF_STUBS_MUTEX_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.h b/src/google/protobuf/stubs/once.h index 1f082c37..f3835ccd 100644 --- a/src/google/protobuf/stubs/once.h +++ b/src/google/protobuf/stubs/once.h @@ -78,88 +78,51 @@ #ifndef GOOGLE_PROTOBUF_STUBS_ONCE_H__ #define GOOGLE_PROTOBUF_STUBS_ONCE_H__ -#include <google/protobuf/stubs/atomicops.h> -#include <google/protobuf/stubs/callback.h> -#include <google/protobuf/stubs/common.h> +#include <mutex> +#include <utility> namespace google { namespace protobuf { +namespace internal { -#ifdef GOOGLE_PROTOBUF_NO_THREAD_SAFETY - -typedef bool ProtobufOnceType; - -#define GOOGLE_PROTOBUF_ONCE_INIT false - -inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)()) { - if (!*once) { - *once = true; - init_func(); - } +using once_flag = std::once_flag; +template <typename... Args> +void call_once(Args&&... args ) { + std::call_once(std::forward<Args>(args)...); } -template <typename Arg> -inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)(Arg), - Arg arg) { - if (!*once) { - *once = true; - init_func(arg); - } -} +} // namespace internal -#else - -enum { - ONCE_STATE_UNINITIALIZED = 0, - ONCE_STATE_EXECUTING_CLOSURE = 1, - ONCE_STATE_DONE = 2 -}; - -typedef internal::AtomicWord ProtobufOnceType; - -#define GOOGLE_PROTOBUF_ONCE_INIT ::google::protobuf::ONCE_STATE_UNINITIALIZED - -LIBPROTOBUF_EXPORT -void GoogleOnceInitImpl(ProtobufOnceType* once, Closure* closure); +// TODO(gerbens) remove this once third_party is fully extracted +using ProtobufOnceType = internal::once_flag; inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)()) { - if (internal::Acquire_Load(once) != ONCE_STATE_DONE) { - internal::FunctionClosure0 func(init_func, false); - GoogleOnceInitImpl(once, &func); - } + std::call_once(*once, init_func); } template <typename Arg> -inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)(Arg*), - Arg* arg) { - if (internal::Acquire_Load(once) != ONCE_STATE_DONE) { - internal::FunctionClosure1<Arg*> func(init_func, false, arg); - GoogleOnceInitImpl(once, &func); - } +inline void GoogleOnceInitArg(ProtobufOnceType* once, void (*init_func)(Arg*), + Arg* arg) { + std::call_once(*once, init_func, arg); } -#endif // GOOGLE_PROTOBUF_NO_THREAD_SAFETY - class GoogleOnceDynamic { public: - GoogleOnceDynamic() : state_(GOOGLE_PROTOBUF_ONCE_INIT) { } - // If this->Init() has not been called before by any thread, // execute (*func_with_arg)(arg) then return. // Otherwise, wait until that prior invocation has finished // executing its function, then return. template<typename T> void Init(void (*func_with_arg)(T*), T* arg) { - GoogleOnceInit<T>(&this->state_, - func_with_arg, - arg); + GoogleOnceInitArg<T>(&this->state_, func_with_arg, arg); } private: ProtobufOnceType state_; }; +#define GOOGLE_PROTOBUF_ONCE_TYPE ::google::protobuf::ProtobufOnceType #define GOOGLE_PROTOBUF_DECLARE_ONCE(NAME) \ - ::google::protobuf::ProtobufOnceType NAME = GOOGLE_PROTOBUF_ONCE_INIT + ::google::protobuf::ProtobufOnceType NAME } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/stubs/once_unittest.cc b/src/google/protobuf/stubs/once_unittest.cc deleted file mode 100644 index d5f7779e..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); - - scoped_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); - - scoped_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/platform_macros.h b/src/google/protobuf/stubs/platform_macros.h index c3a64dd2..ff4dea7b 100644 --- a/src/google/protobuf/stubs/platform_macros.h +++ b/src/google/protobuf/stubs/platform_macros.h @@ -99,6 +99,7 @@ GOOGLE_PROTOBUF_PLATFORM_ERROR #if defined(__APPLE__) #define GOOGLE_PROTOBUF_OS_APPLE +#include <Availability.h> #include <TargetConditionals.h> #if TARGET_OS_IPHONE #define GOOGLE_PROTOBUF_OS_IPHONE @@ -125,4 +126,9 @@ GOOGLE_PROTOBUF_PLATFORM_ERROR #define GOOGLE_PROTOBUF_NO_THREADLOCAL #endif +#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 1070 +// __thread keyword requires at least 10.7 +#define GOOGLE_PROTOBUF_NO_THREADLOCAL +#endif + #endif // GOOGLE_PROTOBUF_PLATFORM_MACROS_H_ diff --git a/src/google/protobuf/stubs/port.h b/src/google/protobuf/stubs/port.h index ebbf7da6..3aa6403b 100644 --- a/src/google/protobuf/stubs/port.h +++ b/src/google/protobuf/stubs/port.h @@ -91,9 +91,10 @@ // These #includes are for the byte swap functions declared later on. #ifdef _MSC_VER #include <stdlib.h> // NOLINT(build/include) +#include <intrin.h> #elif defined(__APPLE__) #include <libkern/OSByteOrder.h> -#elif defined(__GLIBC__) || defined(__CYGWIN__) +#elif defined(__GLIBC__) || defined(__BIONIC__) || defined(__CYGWIN__) #include <byteswap.h> // IWYU pragma: export #endif @@ -209,6 +210,19 @@ static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF); #define GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE GOOGLE_ATTRIBUTE_NOINLINE +#ifndef GOOGLE_ATTRIBUTE_FUNC_ALIGN +#if defined(__clang__) || \ + defined(__GNUC__) && (__GNUC__ > 4 ||(__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) +// Function alignment attribute introduced in gcc 4.3 +#define GOOGLE_ATTRIBUTE_FUNC_ALIGN(bytes) __attribute__ ((aligned(bytes))) +#else +#define GOOGLE_ATTRIBUTE_FUNC_ALIGN(bytes) +#endif +#endif + +#define GOOGLE_PROTOBUF_ATTRIBUTE_FUNC_ALIGN(bytes) \ + GOOGLE_ATTRIBUTE_FUNC_ALIGN(bytes) + #ifndef GOOGLE_PREDICT_TRUE #ifdef __GNUC__ // Provided at least since GCC 3.0. @@ -227,6 +241,13 @@ static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF); #endif #endif +#ifndef GOOGLE_PROTOBUF_ATTRIBUTE_RETURNS_NONNULL +#ifdef __GNUC__ +#define GOOGLE_PROTOBUF_ATTRIBUTE_RETURNS_NONNULL \ + __attribute__((returns_nonnull)) +#endif +#endif + // Delimits a block of code which may write to memory which is simultaneously // written by other threads, but which has been determined to be thread-safe // (e.g. because it is an idempotent write). @@ -237,20 +258,6 @@ static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF); #define GOOGLE_SAFE_CONCURRENT_WRITES_END() #endif -#if defined(__clang__) && defined(__has_cpp_attribute) \ - && !defined(GOOGLE_PROTOBUF_OS_APPLE) -# if defined(GOOGLE_PROTOBUF_OS_NACL) || defined(EMSCRIPTEN) || \ - __has_cpp_attribute(clang::fallthrough) -# define GOOGLE_FALLTHROUGH_INTENDED [[clang::fallthrough]] -# endif -#elif defined(__GNUC__) && __GNUC__ > 6 -# define GOOGLE_FALLTHROUGH_INTENDED [[gnu::fallthrough]] -#endif - -#ifndef GOOGLE_FALLTHROUGH_INTENDED -# define GOOGLE_FALLTHROUGH_INTENDED -#endif - #define GOOGLE_GUARDED_BY(x) #define GOOGLE_ATTRIBUTE_COLD @@ -373,7 +380,7 @@ inline void GOOGLE_UNALIGNED_STORE64(void *p, uint64 v) { #define bswap_32(x) OSSwapInt32(x) #define bswap_64(x) OSSwapInt64(x) -#elif !defined(__GLIBC__) && !defined(__CYGWIN__) +#elif !defined(__GLIBC__) && !defined(__BIONIC__) && !defined(__CYGWIN__) #ifndef bswap_16 static inline uint16 bswap_16(uint16 x) { @@ -416,12 +423,10 @@ class Bits { static uint32 Log2FloorNonZero(uint32 n) { #if defined(__GNUC__) return 31 ^ static_cast<uint32>(__builtin_clz(n)); -#elif defined(COMPILER_MSVC) && defined(_M_IX86) - _asm { - bsr ebx, n - mov n, ebx - } - return n; +#elif defined(_MSC_VER) + unsigned long where; + _BitScanReverse(&where, n); + return where; #else return Log2FloorNonZero_Portable(n); #endif @@ -436,6 +441,10 @@ class Bits { // implementation instead. #if defined(__GNUC__) && !defined(GOOGLE_PROTOBUF_USE_PORTABLE_LOG2) return 63 ^ static_cast<uint32>(__builtin_clzll(n)); +#elif defined(_MSC_VER) && defined(_M_X64) + unsigned long where; + _BitScanReverse64(&where, n); + return where; #else return Log2FloorNonZero64_Portable(n); #endif diff --git a/src/google/protobuf/stubs/scoped_ptr.h b/src/google/protobuf/stubs/scoped_ptr.h deleted file mode 100644 index 4423c118..00000000 --- a/src/google/protobuf/stubs/scoped_ptr.h +++ /dev/null @@ -1,236 +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. - -#ifndef GOOGLE_PROTOBUF_STUBS_SCOPED_PTR_H_ -#define GOOGLE_PROTOBUF_STUBS_SCOPED_PTR_H_ - -#include <google/protobuf/stubs/port.h> - -namespace google { -namespace protobuf { - -// =================================================================== -// from google3/base/scoped_ptr.h - -namespace internal { - -// This is an implementation designed to match the anticipated future TR2 -// implementation of the scoped_ptr class, and its closely-related brethren, -// scoped_array, scoped_ptr_malloc, and make_scoped_ptr. - -template <class C> class scoped_ptr; -template <class C> class scoped_array; - -// A scoped_ptr<T> is like a T*, except that the destructor of scoped_ptr<T> -// automatically deletes the pointer it holds (if any). -// That is, scoped_ptr<T> owns the T object that it points to. -// Like a T*, a scoped_ptr<T> may hold either NULL or a pointer to a T object. -// -// The size of a scoped_ptr is small: -// sizeof(scoped_ptr<C>) == sizeof(C*) -template <class C> -class scoped_ptr { - public: - - // The element type - typedef C element_type; - - // Constructor. Defaults to initializing with NULL. - // There is no way to create an uninitialized scoped_ptr. - // The input parameter must be allocated with new. - explicit scoped_ptr(C* p = NULL) : ptr_(p) { } - - // Destructor. If there is a C object, delete it. - // We don't need to test ptr_ == NULL because C++ does that for us. - ~scoped_ptr() { - enum { type_must_be_complete = sizeof(C) }; - delete ptr_; - } - - // Reset. Deletes the current owned object, if any. - // Then takes ownership of a new object, if given. - // this->reset(this->get()) works. - void reset(C* p = NULL) { - if (p != ptr_) { - enum { type_must_be_complete = sizeof(C) }; - delete ptr_; - ptr_ = p; - } - } - - // Accessors to get the owned object. - // operator* and operator-> will assert() if there is no current object. - C& operator*() const { - assert(ptr_ != NULL); - return *ptr_; - } - C* operator->() const { - assert(ptr_ != NULL); - return ptr_; - } - C* get() const { return ptr_; } - - // Comparison operators. - // These return whether two scoped_ptr refer to the same object, not just to - // two different but equal objects. - bool operator==(C* p) const { return ptr_ == p; } - bool operator!=(C* p) const { return ptr_ != p; } - - // Swap two scoped pointers. - void swap(scoped_ptr& p2) { - C* tmp = ptr_; - ptr_ = p2.ptr_; - p2.ptr_ = tmp; - } - - // Release a pointer. - // The return value is the current pointer held by this object. - // If this object holds a NULL pointer, the return value is NULL. - // After this operation, this object will hold a NULL pointer, - // and will not own the object any more. - C* release() { - C* retVal = ptr_; - ptr_ = NULL; - return retVal; - } - - private: - C* ptr_; - - // Forbid comparison of scoped_ptr types. If C2 != C, it totally doesn't - // make sense, and if C2 == C, it still doesn't make sense because you should - // never have the same object owned by two different scoped_ptrs. - template <class C2> bool operator==(scoped_ptr<C2> const& p2) const; - template <class C2> bool operator!=(scoped_ptr<C2> const& p2) const; - - // Disallow evil constructors - scoped_ptr(const scoped_ptr&); - void operator=(const scoped_ptr&); -}; - -// scoped_array<C> is like scoped_ptr<C>, except that the caller must allocate -// with new [] and the destructor deletes objects with delete []. -// -// As with scoped_ptr<C>, a scoped_array<C> either points to an object -// or is NULL. A scoped_array<C> owns the object that it points to. -// -// Size: sizeof(scoped_array<C>) == sizeof(C*) -template <class C> -class scoped_array { - public: - - // The element type - typedef C element_type; - - // Constructor. Defaults to initializing with NULL. - // There is no way to create an uninitialized scoped_array. - // The input parameter must be allocated with new []. - explicit scoped_array(C* p = NULL) : array_(p) { } - - // Destructor. If there is a C object, delete it. - // We don't need to test ptr_ == NULL because C++ does that for us. - ~scoped_array() { - enum { type_must_be_complete = sizeof(C) }; - delete[] array_; - } - - // Reset. Deletes the current owned object, if any. - // Then takes ownership of a new object, if given. - // this->reset(this->get()) works. - void reset(C* p = NULL) { - if (p != array_) { - enum { type_must_be_complete = sizeof(C) }; - delete[] array_; - array_ = p; - } - } - - // Get one element of the current object. - // Will assert() if there is no current object, or index i is negative. - C& operator[](std::ptrdiff_t i) const { - assert(i >= 0); - assert(array_ != NULL); - return array_[i]; - } - - // Get a pointer to the zeroth element of the current object. - // If there is no current object, return NULL. - C* get() const { - return array_; - } - - // Comparison operators. - // These return whether two scoped_array refer to the same object, not just to - // two different but equal objects. - bool operator==(C* p) const { return array_ == p; } - bool operator!=(C* p) const { return array_ != p; } - - // Swap two scoped arrays. - void swap(scoped_array& p2) { - C* tmp = array_; - array_ = p2.array_; - p2.array_ = tmp; - } - - // Release an array. - // The return value is the current pointer held by this object. - // If this object holds a NULL pointer, the return value is NULL. - // After this operation, this object will hold a NULL pointer, - // and will not own the object any more. - C* release() { - C* retVal = array_; - array_ = NULL; - return retVal; - } - - private: - C* array_; - - // Forbid comparison of different scoped_array types. - template <class C2> bool operator==(scoped_array<C2> const& p2) const; - template <class C2> bool operator!=(scoped_array<C2> const& p2) const; - - // Disallow evil constructors - scoped_array(const scoped_array&); - void operator=(const scoped_array&); -}; - -} // namespace internal - -// We made these internal so that they would show up as such in the docs, -// but we don't want to stick "internal::" in front of them everywhere. -using internal::scoped_ptr; -using internal::scoped_array; - - -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_STUBS_SCOPED_PTR_H_ 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/singleton.h b/src/google/protobuf/stubs/singleton.h index 9301f549..2e6ccbdb 100644 --- a/src/google/protobuf/stubs/singleton.h +++ b/src/google/protobuf/stubs/singleton.h @@ -30,7 +30,6 @@ #ifndef GOOGLE_PROTOBUF_STUBS_SINGLETON_H__ #define GOOGLE_PROTOBUF_STUBS_SINGLETON_H__ -#include <google/protobuf/stubs/atomicops.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/once.h> diff --git a/src/google/protobuf/stubs/status.cc b/src/google/protobuf/stubs/status.cc index dd1bd614..2bfbe0b4 100644 --- a/src/google/protobuf/stubs/status.cc +++ b/src/google/protobuf/stubs/status.cc @@ -124,7 +124,7 @@ string Status::ToString() const { } } -ostream& operator<<(ostream& os, const Status& x) { +std::ostream& operator<<(std::ostream& os, const Status& x) { os << x.ToString(); return os; } diff --git a/src/google/protobuf/stubs/status.h b/src/google/protobuf/stubs/status.h index 614ab994..c5d38f0b 100644 --- a/src/google/protobuf/stubs/status.h +++ b/src/google/protobuf/stubs/status.h @@ -106,7 +106,7 @@ class LIBPROTOBUF_EXPORT Status { }; // Prints a human-readable representation of 'x' to 'os'. -LIBPROTOBUF_EXPORT ostream& operator<<(ostream& os, const Status& x); +LIBPROTOBUF_EXPORT std::ostream& operator<<(std::ostream& os, const Status& x); #define EXPECT_OK(value) EXPECT_TRUE((value).ok()) diff --git a/src/google/protobuf/stubs/stringprintf.cc b/src/google/protobuf/stubs/stringprintf.cc index 83fdfe45..d98b9b87 100644 --- a/src/google/protobuf/stubs/stringprintf.cc +++ b/src/google/protobuf/stubs/stringprintf.cc @@ -137,7 +137,7 @@ const int kStringPrintfVectorMaxArgs = 32; // and we can fix the problem or protect against an attack. static const char string_printf_empty_block[256] = { '\0' }; -string StringPrintfVector(const char* format, const vector<string>& v) { +string StringPrintfVector(const char* format, const std::vector<string>& v) { GOOGLE_CHECK_LE(v.size(), kStringPrintfVectorMaxArgs) << "StringPrintfVector currently only supports up to " << kStringPrintfVectorMaxArgs << " arguments. " diff --git a/src/google/protobuf/stubs/stringprintf.h b/src/google/protobuf/stubs/stringprintf.h index ab1ab558..7183ec6a 100644 --- a/src/google/protobuf/stubs/stringprintf.h +++ b/src/google/protobuf/stubs/stringprintf.h @@ -68,7 +68,7 @@ LIBPROTOBUF_EXPORT extern const int kStringPrintfVectorMaxArgs; // You can use this version when all your arguments are strings, but // you don't know how many arguments you'll have at compile time. // StringPrintfVector will LOG(FATAL) if v.size() > kStringPrintfVectorMaxArgs -LIBPROTOBUF_EXPORT extern string StringPrintfVector(const char* format, const vector<string>& v); +LIBPROTOBUF_EXPORT extern string StringPrintfVector(const char* format, const std::vector<string>& v); } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/stubs/strutil.cc b/src/google/protobuf/stubs/strutil.cc index 1a4d71c8..552d416f 100644 --- a/src/google/protobuf/stubs/strutil.cc +++ b/src/google/protobuf/stubs/strutil.cc @@ -226,8 +226,8 @@ void SplitStringToIteratorUsing(const string& full, void SplitStringUsing(const string& full, const char* delim, - vector<string>* result) { - std::back_insert_iterator< vector<string> > it(*result); + std::vector<string>* result) { + std::back_insert_iterator< std::vector<string> > it(*result); SplitStringToIteratorUsing(full, delim, it); } @@ -264,8 +264,8 @@ void SplitStringToIteratorAllowEmpty(const StringType& full, } void SplitStringAllowEmpty(const string& full, const char* delim, - vector<string>* result) { - std::back_insert_iterator<vector<string> > it(*result); + std::vector<string>* result) { + std::back_insert_iterator<std::vector<string> > it(*result); SplitStringToIteratorAllowEmpty(full, delim, 0, it); } @@ -303,7 +303,7 @@ static void JoinStringsIterator(const ITERATOR& start, } } -void JoinStrings(const vector<string>& components, +void JoinStrings(const std::vector<string>& components, const char* delim, string * result) { JoinStringsIterator(components.begin(), components.end(), delim, result); @@ -332,7 +332,7 @@ int UnescapeCEscapeSequences(const char* source, char* dest) { } int UnescapeCEscapeSequences(const char* source, char* dest, - vector<string> *errors) { + std::vector<string> *errors) { GOOGLE_DCHECK(errors == NULL) << "Error reporting not implemented."; char* d = dest; @@ -468,8 +468,8 @@ int UnescapeCEscapeString(const string& src, string* dest) { } int UnescapeCEscapeString(const string& src, string* dest, - vector<string> *errors) { - scoped_array<char> unescaped(new char[src.size() + 1]); + std::vector<string> *errors) { + std::unique_ptr<char[]> unescaped(new char[src.size() + 1]); int len = UnescapeCEscapeSequences(src.c_str(), unescaped.get(), errors); GOOGLE_CHECK(dest); dest->assign(unescaped.get(), len); @@ -477,7 +477,7 @@ int UnescapeCEscapeString(const string& src, string* dest, } string UnescapeCEscapeString(const string& src) { - scoped_array<char> unescaped(new char[src.size() + 1]); + std::unique_ptr<char[]> unescaped(new char[src.size() + 1]); int len = UnescapeCEscapeSequences(src.c_str(), unescaped.get(), NULL); return string(unescaped.get(), len); } @@ -620,7 +620,7 @@ namespace strings { string Utf8SafeCEscape(const string& src) { const int dest_length = src.size() * 4 + 1; // Maximum possible expansion - scoped_array<char> dest(new char[dest_length]); + std::unique_ptr<char[]> dest(new char[dest_length]); const int len = CEscapeInternal(src.data(), src.size(), dest.get(), dest_length, false, true); GOOGLE_DCHECK_GE(len, 0); @@ -629,7 +629,7 @@ string Utf8SafeCEscape(const string& src) { string CHexEscape(const string& src) { const int dest_length = src.size() * 4 + 1; // Maximum possible expansion - scoped_array<char> dest(new char[dest_length]); + std::unique_ptr<char[]> dest(new char[dest_length]); const int len = CEscapeInternal(src.data(), src.size(), dest.get(), dest_length, true, false); GOOGLE_DCHECK_GE(len, 0); diff --git a/src/google/protobuf/stubs/strutil.h b/src/google/protobuf/stubs/strutil.h index df28c94d..a839b8b3 100644 --- a/src/google/protobuf/stubs/strutil.h +++ b/src/google/protobuf/stubs/strutil.h @@ -213,7 +213,7 @@ LIBPROTOBUF_EXPORT string StringReplace(const string& s, const string& oldsub, // over all of them. // ---------------------------------------------------------------------- LIBPROTOBUF_EXPORT void SplitStringUsing(const string& full, const char* delim, - vector<string>* res); + std::vector<string>* res); // Split a string using one or more byte delimiters, presented // as a nul-terminated c string. Append the components to 'result'. @@ -225,15 +225,15 @@ LIBPROTOBUF_EXPORT void SplitStringUsing(const string& full, const char* delim, // ---------------------------------------------------------------------- LIBPROTOBUF_EXPORT void SplitStringAllowEmpty(const string& full, const char* delim, - vector<string>* result); + std::vector<string>* result); // ---------------------------------------------------------------------- // Split() // Split a string using a character delimiter. // ---------------------------------------------------------------------- -inline vector<string> Split( +inline std::vector<string> Split( const string& full, const char* delim, bool skip_empty = true) { - vector<string> result; + std::vector<string> result; if (skip_empty) { SplitStringUsing(full, delim, &result); } else { @@ -250,10 +250,10 @@ inline vector<string> Split( // another takes a pointer to the target string. In the latter case the // target string is cleared and overwritten. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT void JoinStrings(const vector<string>& components, +LIBPROTOBUF_EXPORT void JoinStrings(const std::vector<string>& components, const char* delim, string* result); -inline string JoinStrings(const vector<string>& components, +inline string JoinStrings(const std::vector<string>& components, const char* delim) { string result; JoinStrings(components, delim, &result); @@ -285,15 +285,15 @@ inline string JoinStrings(const vector<string>& components, // // Errors: In the first form of the call, errors are reported with // LOG(ERROR). The same is true for the second form of the call if -// the pointer to the string vector is NULL; otherwise, error -// messages are stored in the vector. In either case, the effect on +// the pointer to the string std::vector is NULL; otherwise, error +// messages are stored in the std::vector. In either case, the effect on // the dest array is not defined, but rest of the source will be // processed. // ---------------------------------------------------------------------- LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest); LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest, - vector<string> *errors); + std::vector<string> *errors); // ---------------------------------------------------------------------- // UnescapeCEscapeString() @@ -312,7 +312,7 @@ LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest, LIBPROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest); LIBPROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest, - vector<string> *errors); + std::vector<string> *errors); LIBPROTOBUF_EXPORT string UnescapeCEscapeString(const string& src); // ---------------------------------------------------------------------- diff --git a/src/google/protobuf/stubs/strutil_unittest.cc b/src/google/protobuf/stubs/strutil_unittest.cc index 5d62fc4a..6bf0f598 100644 --- a/src/google/protobuf/stubs/strutil_unittest.cc +++ b/src/google/protobuf/stubs/strutil_unittest.cc @@ -782,7 +782,7 @@ TEST(Base64, EscapeAndUnescape) { reinterpret_cast<const unsigned char*>(base64_strings[i].plaintext); int plain_length = strlen(base64_strings[i].plaintext); int cypher_length = strlen(base64_strings[i].cyphertext); - vector<char> buffer(cypher_length+1); + std::vector<char> buffer(cypher_length+1); int encode_length = WebSafeBase64Escape(unsigned_plaintext, plain_length, &buffer[0], 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 49c10ace..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 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/test_util.cc b/src/google/protobuf/test_util.cc index 4e02a85d..795cb6ae 100644 --- a/src/google/protobuf/test_util.cc +++ b/src/google/protobuf/test_util.cc @@ -39,3312 +39,9 @@ #endif #include <google/protobuf/test_util.h> -#include <google/protobuf/descriptor.h> -#include <google/protobuf/message.h> - -#include <google/protobuf/stubs/logging.h> -#include <google/protobuf/stubs/common.h> -#include <google/protobuf/testing/googletest.h> -#include <gtest/gtest.h> namespace google { namespace protobuf { -void TestUtil::SetAllFields(unittest::TestAllTypes* message) { - SetOptionalFields(message); - AddRepeatedFields1(message); - AddRepeatedFields2(message); - SetDefaultFields(message); - SetOneofFields(message); -} - -void TestUtil::SetOptionalFields(unittest::TestAllTypes* message) { - message->set_optional_int32 (101); - message->set_optional_int64 (102); - message->set_optional_uint32 (103); - message->set_optional_uint64 (104); - message->set_optional_sint32 (105); - message->set_optional_sint64 (106); - message->set_optional_fixed32 (107); - message->set_optional_fixed64 (108); - message->set_optional_sfixed32(109); - message->set_optional_sfixed64(110); - message->set_optional_float (111); - message->set_optional_double (112); - message->set_optional_bool (true); - message->set_optional_string ("115"); - message->set_optional_bytes ("116"); - - message->mutable_optionalgroup ()->set_a(117); - message->mutable_optional_nested_message ()->set_bb(118); - message->mutable_optional_foreign_message ()->set_c(119); - message->mutable_optional_import_message ()->set_d(120); - message->mutable_optional_public_import_message()->set_e(126); - message->mutable_optional_lazy_message ()->set_bb(127); - - message->set_optional_nested_enum (unittest::TestAllTypes::BAZ); - message->set_optional_foreign_enum(unittest::FOREIGN_BAZ ); - message->set_optional_import_enum (unittest_import::IMPORT_BAZ); - - // StringPiece and Cord fields are only accessible via reflection in the - // open source release; see comments in compiler/cpp/string_field.cc. -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - message->GetReflection()->SetString( - message, - message->GetDescriptor()->FindFieldByName("optional_string_piece"), - "124"); - message->GetReflection()->SetString( - message, - message->GetDescriptor()->FindFieldByName("optional_cord"), - "125"); -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS -} - -// ------------------------------------------------------------------- - -void TestUtil::AddRepeatedFields1(unittest::TestAllTypes* message) { - message->add_repeated_int32 (201); - message->add_repeated_int64 (202); - message->add_repeated_uint32 (203); - message->add_repeated_uint64 (204); - message->add_repeated_sint32 (205); - message->add_repeated_sint64 (206); - message->add_repeated_fixed32 (207); - message->add_repeated_fixed64 (208); - message->add_repeated_sfixed32(209); - message->add_repeated_sfixed64(210); - message->add_repeated_float (211); - message->add_repeated_double (212); - message->add_repeated_bool (true); - message->add_repeated_string ("215"); - message->add_repeated_bytes ("216"); - - message->add_repeatedgroup ()->set_a(217); - message->add_repeated_nested_message ()->set_bb(218); - message->add_repeated_foreign_message()->set_c(219); - message->add_repeated_import_message ()->set_d(220); - message->add_repeated_lazy_message ()->set_bb(227); - - message->add_repeated_nested_enum (unittest::TestAllTypes::BAR); - message->add_repeated_foreign_enum(unittest::FOREIGN_BAR ); - message->add_repeated_import_enum (unittest_import::IMPORT_BAR); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - message->GetReflection()->AddString( - message, - message->GetDescriptor()->FindFieldByName("repeated_string_piece"), - "224"); - message->GetReflection()->AddString( - message, - message->GetDescriptor()->FindFieldByName("repeated_cord"), - "225"); -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS -} - -void TestUtil::AddRepeatedFields2(unittest::TestAllTypes* message) { - // Add a second one of each field. - message->add_repeated_int32 (301); - message->add_repeated_int64 (302); - message->add_repeated_uint32 (303); - message->add_repeated_uint64 (304); - message->add_repeated_sint32 (305); - message->add_repeated_sint64 (306); - message->add_repeated_fixed32 (307); - message->add_repeated_fixed64 (308); - message->add_repeated_sfixed32(309); - message->add_repeated_sfixed64(310); - message->add_repeated_float (311); - message->add_repeated_double (312); - message->add_repeated_bool (false); - message->add_repeated_string ("315"); - message->add_repeated_bytes ("316"); - - message->add_repeatedgroup ()->set_a(317); - message->add_repeated_nested_message ()->set_bb(318); - message->add_repeated_foreign_message()->set_c(319); - message->add_repeated_import_message ()->set_d(320); - message->add_repeated_lazy_message ()->set_bb(327); - - message->add_repeated_nested_enum (unittest::TestAllTypes::BAZ); - message->add_repeated_foreign_enum(unittest::FOREIGN_BAZ ); - message->add_repeated_import_enum (unittest_import::IMPORT_BAZ); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - message->GetReflection()->AddString( - message, - message->GetDescriptor()->FindFieldByName("repeated_string_piece"), - "324"); - message->GetReflection()->AddString( - message, - message->GetDescriptor()->FindFieldByName("repeated_cord"), - "325"); -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS -} - -// ------------------------------------------------------------------- - -void TestUtil::SetDefaultFields(unittest::TestAllTypes* message) { - message->set_default_int32 (401); - message->set_default_int64 (402); - message->set_default_uint32 (403); - message->set_default_uint64 (404); - message->set_default_sint32 (405); - message->set_default_sint64 (406); - message->set_default_fixed32 (407); - message->set_default_fixed64 (408); - message->set_default_sfixed32(409); - message->set_default_sfixed64(410); - message->set_default_float (411); - message->set_default_double (412); - message->set_default_bool (false); - message->set_default_string ("415"); - message->set_default_bytes ("416"); - - message->set_default_nested_enum (unittest::TestAllTypes::FOO); - message->set_default_foreign_enum(unittest::FOREIGN_FOO ); - message->set_default_import_enum (unittest_import::IMPORT_FOO); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - message->GetReflection()->SetString( - message, - message->GetDescriptor()->FindFieldByName("default_string_piece"), - "424"); - message->GetReflection()->SetString( - message, - message->GetDescriptor()->FindFieldByName("default_cord"), - "425"); -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS -} - -// ------------------------------------------------------------------- - -void TestUtil::ModifyRepeatedFields(unittest::TestAllTypes* message) { - message->set_repeated_int32 (1, 501); - message->set_repeated_int64 (1, 502); - message->set_repeated_uint32 (1, 503); - message->set_repeated_uint64 (1, 504); - message->set_repeated_sint32 (1, 505); - message->set_repeated_sint64 (1, 506); - message->set_repeated_fixed32 (1, 507); - message->set_repeated_fixed64 (1, 508); - message->set_repeated_sfixed32(1, 509); - message->set_repeated_sfixed64(1, 510); - message->set_repeated_float (1, 511); - message->set_repeated_double (1, 512); - message->set_repeated_bool (1, true); - message->set_repeated_string (1, "515"); - message->set_repeated_bytes (1, "516"); - - message->mutable_repeatedgroup (1)->set_a(517); - message->mutable_repeated_nested_message (1)->set_bb(518); - message->mutable_repeated_foreign_message(1)->set_c(519); - message->mutable_repeated_import_message (1)->set_d(520); - message->mutable_repeated_lazy_message (1)->set_bb(527); - - message->set_repeated_nested_enum (1, unittest::TestAllTypes::FOO); - message->set_repeated_foreign_enum(1, unittest::FOREIGN_FOO ); - message->set_repeated_import_enum (1, unittest_import::IMPORT_FOO); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - message->GetReflection()->SetRepeatedString( - message, - message->GetDescriptor()->FindFieldByName("repeated_string_piece"), - 1, "524"); - message->GetReflection()->SetRepeatedString( - message, - message->GetDescriptor()->FindFieldByName("repeated_cord"), - 1, "525"); -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS -} - -// ------------------------------------------------------------------ -void TestUtil::SetOneofFields(unittest::TestAllTypes* message) { - message->set_oneof_uint32(601); - message->mutable_oneof_nested_message()->set_bb(602); - message->set_oneof_string("603"); - message->set_oneof_bytes("604"); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectAllFieldsSet(const unittest::TestAllTypes& message) { - EXPECT_TRUE(message.has_optional_int32 ()); - EXPECT_TRUE(message.has_optional_int64 ()); - EXPECT_TRUE(message.has_optional_uint32 ()); - EXPECT_TRUE(message.has_optional_uint64 ()); - EXPECT_TRUE(message.has_optional_sint32 ()); - EXPECT_TRUE(message.has_optional_sint64 ()); - EXPECT_TRUE(message.has_optional_fixed32 ()); - EXPECT_TRUE(message.has_optional_fixed64 ()); - EXPECT_TRUE(message.has_optional_sfixed32()); - EXPECT_TRUE(message.has_optional_sfixed64()); - EXPECT_TRUE(message.has_optional_float ()); - EXPECT_TRUE(message.has_optional_double ()); - EXPECT_TRUE(message.has_optional_bool ()); - EXPECT_TRUE(message.has_optional_string ()); - EXPECT_TRUE(message.has_optional_bytes ()); - - EXPECT_TRUE(message.has_optionalgroup ()); - EXPECT_TRUE(message.has_optional_nested_message ()); - EXPECT_TRUE(message.has_optional_foreign_message ()); - EXPECT_TRUE(message.has_optional_import_message ()); - EXPECT_TRUE(message.has_optional_public_import_message()); - EXPECT_TRUE(message.has_optional_lazy_message ()); - - EXPECT_TRUE(message.optionalgroup ().has_a()); - EXPECT_TRUE(message.optional_nested_message ().has_bb()); - EXPECT_TRUE(message.optional_foreign_message ().has_c()); - EXPECT_TRUE(message.optional_import_message ().has_d()); - EXPECT_TRUE(message.optional_public_import_message().has_e()); - EXPECT_TRUE(message.optional_lazy_message ().has_bb()); - - EXPECT_TRUE(message.has_optional_nested_enum ()); - EXPECT_TRUE(message.has_optional_foreign_enum()); - EXPECT_TRUE(message.has_optional_import_enum ()); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - EXPECT_TRUE(message.has_optional_string_piece()); - EXPECT_TRUE(message.has_optional_cord()); -#endif - - EXPECT_EQ(101 , message.optional_int32 ()); - EXPECT_EQ(102 , message.optional_int64 ()); - EXPECT_EQ(103 , message.optional_uint32 ()); - EXPECT_EQ(104 , message.optional_uint64 ()); - EXPECT_EQ(105 , message.optional_sint32 ()); - EXPECT_EQ(106 , message.optional_sint64 ()); - EXPECT_EQ(107 , message.optional_fixed32 ()); - EXPECT_EQ(108 , message.optional_fixed64 ()); - EXPECT_EQ(109 , message.optional_sfixed32()); - EXPECT_EQ(110 , message.optional_sfixed64()); - EXPECT_EQ(111 , message.optional_float ()); - EXPECT_EQ(112 , message.optional_double ()); - EXPECT_TRUE( message.optional_bool ()); - EXPECT_EQ("115", message.optional_string ()); - EXPECT_EQ("116", message.optional_bytes ()); - - EXPECT_EQ(117, message.optionalgroup ().a()); - EXPECT_EQ(118, message.optional_nested_message ().bb()); - EXPECT_EQ(119, message.optional_foreign_message ().c()); - EXPECT_EQ(120, message.optional_import_message ().d()); - EXPECT_EQ(126, message.optional_public_import_message ().e()); - EXPECT_EQ(127, message.optional_lazy_message ().bb()); - - EXPECT_EQ(unittest::TestAllTypes::BAZ, message.optional_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_BAZ , message.optional_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_BAZ, message.optional_import_enum ()); - - - // ----------------------------------------------------------------- - - ASSERT_EQ(2, message.repeated_int32_size ()); - ASSERT_EQ(2, message.repeated_int64_size ()); - ASSERT_EQ(2, message.repeated_uint32_size ()); - ASSERT_EQ(2, message.repeated_uint64_size ()); - ASSERT_EQ(2, message.repeated_sint32_size ()); - ASSERT_EQ(2, message.repeated_sint64_size ()); - ASSERT_EQ(2, message.repeated_fixed32_size ()); - ASSERT_EQ(2, message.repeated_fixed64_size ()); - ASSERT_EQ(2, message.repeated_sfixed32_size()); - ASSERT_EQ(2, message.repeated_sfixed64_size()); - ASSERT_EQ(2, message.repeated_float_size ()); - ASSERT_EQ(2, message.repeated_double_size ()); - ASSERT_EQ(2, message.repeated_bool_size ()); - ASSERT_EQ(2, message.repeated_string_size ()); - ASSERT_EQ(2, message.repeated_bytes_size ()); - - ASSERT_EQ(2, message.repeatedgroup_size ()); - ASSERT_EQ(2, message.repeated_nested_message_size ()); - ASSERT_EQ(2, message.repeated_foreign_message_size()); - ASSERT_EQ(2, message.repeated_import_message_size ()); - ASSERT_EQ(2, message.repeated_lazy_message_size ()); - ASSERT_EQ(2, message.repeated_nested_enum_size ()); - ASSERT_EQ(2, message.repeated_foreign_enum_size ()); - ASSERT_EQ(2, message.repeated_import_enum_size ()); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - ASSERT_EQ(2, message.repeated_string_piece_size()); - ASSERT_EQ(2, message.repeated_cord_size()); -#endif - - EXPECT_EQ(201 , message.repeated_int32 (0)); - EXPECT_EQ(202 , message.repeated_int64 (0)); - EXPECT_EQ(203 , message.repeated_uint32 (0)); - EXPECT_EQ(204 , message.repeated_uint64 (0)); - EXPECT_EQ(205 , message.repeated_sint32 (0)); - EXPECT_EQ(206 , message.repeated_sint64 (0)); - EXPECT_EQ(207 , message.repeated_fixed32 (0)); - EXPECT_EQ(208 , message.repeated_fixed64 (0)); - EXPECT_EQ(209 , message.repeated_sfixed32(0)); - EXPECT_EQ(210 , message.repeated_sfixed64(0)); - EXPECT_EQ(211 , message.repeated_float (0)); - EXPECT_EQ(212 , message.repeated_double (0)); - EXPECT_TRUE( message.repeated_bool (0)); - EXPECT_EQ("215", message.repeated_string (0)); - EXPECT_EQ("216", message.repeated_bytes (0)); - - EXPECT_EQ(217, message.repeatedgroup (0).a()); - EXPECT_EQ(218, message.repeated_nested_message (0).bb()); - EXPECT_EQ(219, message.repeated_foreign_message(0).c()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); - EXPECT_EQ(227, message.repeated_lazy_message (0).bb()); - - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.repeated_nested_enum (0)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.repeated_foreign_enum(0)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.repeated_import_enum (0)); - - EXPECT_EQ(301 , message.repeated_int32 (1)); - EXPECT_EQ(302 , message.repeated_int64 (1)); - EXPECT_EQ(303 , message.repeated_uint32 (1)); - EXPECT_EQ(304 , message.repeated_uint64 (1)); - EXPECT_EQ(305 , message.repeated_sint32 (1)); - EXPECT_EQ(306 , message.repeated_sint64 (1)); - EXPECT_EQ(307 , message.repeated_fixed32 (1)); - EXPECT_EQ(308 , message.repeated_fixed64 (1)); - EXPECT_EQ(309 , message.repeated_sfixed32(1)); - EXPECT_EQ(310 , message.repeated_sfixed64(1)); - EXPECT_EQ(311 , message.repeated_float (1)); - EXPECT_EQ(312 , message.repeated_double (1)); - EXPECT_FALSE( message.repeated_bool (1)); - EXPECT_EQ("315", message.repeated_string (1)); - EXPECT_EQ("316", message.repeated_bytes (1)); - - EXPECT_EQ(317, message.repeatedgroup (1).a()); - EXPECT_EQ(318, message.repeated_nested_message (1).bb()); - EXPECT_EQ(319, message.repeated_foreign_message(1).c()); - EXPECT_EQ(320, message.repeated_import_message (1).d()); - EXPECT_EQ(327, message.repeated_lazy_message (1).bb()); - - EXPECT_EQ(unittest::TestAllTypes::BAZ, message.repeated_nested_enum (1)); - EXPECT_EQ(unittest::FOREIGN_BAZ , message.repeated_foreign_enum(1)); - EXPECT_EQ(unittest_import::IMPORT_BAZ, message.repeated_import_enum (1)); - - - // ----------------------------------------------------------------- - - EXPECT_TRUE(message.has_default_int32 ()); - EXPECT_TRUE(message.has_default_int64 ()); - EXPECT_TRUE(message.has_default_uint32 ()); - EXPECT_TRUE(message.has_default_uint64 ()); - EXPECT_TRUE(message.has_default_sint32 ()); - EXPECT_TRUE(message.has_default_sint64 ()); - EXPECT_TRUE(message.has_default_fixed32 ()); - EXPECT_TRUE(message.has_default_fixed64 ()); - EXPECT_TRUE(message.has_default_sfixed32()); - EXPECT_TRUE(message.has_default_sfixed64()); - EXPECT_TRUE(message.has_default_float ()); - EXPECT_TRUE(message.has_default_double ()); - EXPECT_TRUE(message.has_default_bool ()); - EXPECT_TRUE(message.has_default_string ()); - EXPECT_TRUE(message.has_default_bytes ()); - - EXPECT_TRUE(message.has_default_nested_enum ()); - EXPECT_TRUE(message.has_default_foreign_enum()); - EXPECT_TRUE(message.has_default_import_enum ()); - - - EXPECT_EQ(401 , message.default_int32 ()); - EXPECT_EQ(402 , message.default_int64 ()); - EXPECT_EQ(403 , message.default_uint32 ()); - EXPECT_EQ(404 , message.default_uint64 ()); - EXPECT_EQ(405 , message.default_sint32 ()); - EXPECT_EQ(406 , message.default_sint64 ()); - EXPECT_EQ(407 , message.default_fixed32 ()); - EXPECT_EQ(408 , message.default_fixed64 ()); - EXPECT_EQ(409 , message.default_sfixed32()); - EXPECT_EQ(410 , message.default_sfixed64()); - EXPECT_EQ(411 , message.default_float ()); - EXPECT_EQ(412 , message.default_double ()); - EXPECT_FALSE( message.default_bool ()); - EXPECT_EQ("415", message.default_string ()); - EXPECT_EQ("416", message.default_bytes ()); - - EXPECT_EQ(unittest::TestAllTypes::FOO, message.default_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_FOO , message.default_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_FOO, message.default_import_enum ()); - - - EXPECT_FALSE(message.has_oneof_uint32 ()); - EXPECT_FALSE(message.has_oneof_nested_message()); - EXPECT_FALSE(message.has_oneof_string ()); - EXPECT_TRUE(message.has_oneof_bytes ()); - - EXPECT_EQ("604", message.oneof_bytes()); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectClear(const unittest::TestAllTypes& message) { - // has_blah() should initially be false for all optional fields. - EXPECT_FALSE(message.has_optional_int32 ()); - EXPECT_FALSE(message.has_optional_int64 ()); - EXPECT_FALSE(message.has_optional_uint32 ()); - EXPECT_FALSE(message.has_optional_uint64 ()); - EXPECT_FALSE(message.has_optional_sint32 ()); - EXPECT_FALSE(message.has_optional_sint64 ()); - EXPECT_FALSE(message.has_optional_fixed32 ()); - EXPECT_FALSE(message.has_optional_fixed64 ()); - EXPECT_FALSE(message.has_optional_sfixed32()); - EXPECT_FALSE(message.has_optional_sfixed64()); - EXPECT_FALSE(message.has_optional_float ()); - EXPECT_FALSE(message.has_optional_double ()); - EXPECT_FALSE(message.has_optional_bool ()); - EXPECT_FALSE(message.has_optional_string ()); - EXPECT_FALSE(message.has_optional_bytes ()); - - EXPECT_FALSE(message.has_optionalgroup ()); - EXPECT_FALSE(message.has_optional_nested_message ()); - EXPECT_FALSE(message.has_optional_foreign_message ()); - EXPECT_FALSE(message.has_optional_import_message ()); - EXPECT_FALSE(message.has_optional_public_import_message()); - EXPECT_FALSE(message.has_optional_lazy_message ()); - - EXPECT_FALSE(message.has_optional_nested_enum ()); - EXPECT_FALSE(message.has_optional_foreign_enum()); - EXPECT_FALSE(message.has_optional_import_enum ()); - - EXPECT_FALSE(message.has_optional_string_piece()); - EXPECT_FALSE(message.has_optional_cord()); - - // Optional fields without defaults are set to zero or something like it. - EXPECT_EQ(0 , message.optional_int32 ()); - EXPECT_EQ(0 , message.optional_int64 ()); - EXPECT_EQ(0 , message.optional_uint32 ()); - EXPECT_EQ(0 , message.optional_uint64 ()); - EXPECT_EQ(0 , message.optional_sint32 ()); - EXPECT_EQ(0 , message.optional_sint64 ()); - EXPECT_EQ(0 , message.optional_fixed32 ()); - EXPECT_EQ(0 , message.optional_fixed64 ()); - EXPECT_EQ(0 , message.optional_sfixed32()); - EXPECT_EQ(0 , message.optional_sfixed64()); - EXPECT_EQ(0 , message.optional_float ()); - EXPECT_EQ(0 , message.optional_double ()); - EXPECT_FALSE( message.optional_bool ()); - EXPECT_EQ("" , message.optional_string ()); - EXPECT_EQ("" , message.optional_bytes ()); - - // Embedded messages should also be clear. - EXPECT_FALSE(message.optionalgroup ().has_a()); - EXPECT_FALSE(message.optional_nested_message ().has_bb()); - EXPECT_FALSE(message.optional_foreign_message ().has_c()); - EXPECT_FALSE(message.optional_import_message ().has_d()); - EXPECT_FALSE(message.optional_public_import_message().has_e()); - EXPECT_FALSE(message.optional_lazy_message ().has_bb()); - - EXPECT_EQ(0, message.optionalgroup ().a()); - EXPECT_EQ(0, message.optional_nested_message ().bb()); - EXPECT_EQ(0, message.optional_foreign_message ().c()); - EXPECT_EQ(0, message.optional_import_message ().d()); - EXPECT_EQ(0, message.optional_public_import_message().e()); - EXPECT_EQ(0, message.optional_lazy_message ().bb()); - - // Enums without defaults are set to the first value in the enum. - EXPECT_EQ(unittest::TestAllTypes::FOO, message.optional_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_FOO , message.optional_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_FOO, message.optional_import_enum ()); - - - // Repeated fields are empty. - EXPECT_EQ(0, message.repeated_int32_size ()); - EXPECT_EQ(0, message.repeated_int64_size ()); - EXPECT_EQ(0, message.repeated_uint32_size ()); - EXPECT_EQ(0, message.repeated_uint64_size ()); - EXPECT_EQ(0, message.repeated_sint32_size ()); - EXPECT_EQ(0, message.repeated_sint64_size ()); - EXPECT_EQ(0, message.repeated_fixed32_size ()); - EXPECT_EQ(0, message.repeated_fixed64_size ()); - EXPECT_EQ(0, message.repeated_sfixed32_size()); - EXPECT_EQ(0, message.repeated_sfixed64_size()); - EXPECT_EQ(0, message.repeated_float_size ()); - EXPECT_EQ(0, message.repeated_double_size ()); - EXPECT_EQ(0, message.repeated_bool_size ()); - EXPECT_EQ(0, message.repeated_string_size ()); - EXPECT_EQ(0, message.repeated_bytes_size ()); - - EXPECT_EQ(0, message.repeatedgroup_size ()); - EXPECT_EQ(0, message.repeated_nested_message_size ()); - EXPECT_EQ(0, message.repeated_foreign_message_size()); - EXPECT_EQ(0, message.repeated_import_message_size ()); - EXPECT_EQ(0, message.repeated_lazy_message_size ()); - EXPECT_EQ(0, message.repeated_nested_enum_size ()); - EXPECT_EQ(0, message.repeated_foreign_enum_size ()); - EXPECT_EQ(0, message.repeated_import_enum_size ()); - - EXPECT_EQ(0, message.repeated_string_piece_size()); - EXPECT_EQ(0, message.repeated_cord_size()); - - // has_blah() should also be false for all default fields. - EXPECT_FALSE(message.has_default_int32 ()); - EXPECT_FALSE(message.has_default_int64 ()); - EXPECT_FALSE(message.has_default_uint32 ()); - EXPECT_FALSE(message.has_default_uint64 ()); - EXPECT_FALSE(message.has_default_sint32 ()); - EXPECT_FALSE(message.has_default_sint64 ()); - EXPECT_FALSE(message.has_default_fixed32 ()); - EXPECT_FALSE(message.has_default_fixed64 ()); - EXPECT_FALSE(message.has_default_sfixed32()); - EXPECT_FALSE(message.has_default_sfixed64()); - EXPECT_FALSE(message.has_default_float ()); - EXPECT_FALSE(message.has_default_double ()); - EXPECT_FALSE(message.has_default_bool ()); - EXPECT_FALSE(message.has_default_string ()); - EXPECT_FALSE(message.has_default_bytes ()); - - EXPECT_FALSE(message.has_default_nested_enum ()); - EXPECT_FALSE(message.has_default_foreign_enum()); - EXPECT_FALSE(message.has_default_import_enum ()); - - - // Fields with defaults have their default values (duh). - EXPECT_EQ( 41 , message.default_int32 ()); - EXPECT_EQ( 42 , message.default_int64 ()); - EXPECT_EQ( 43 , message.default_uint32 ()); - EXPECT_EQ( 44 , message.default_uint64 ()); - EXPECT_EQ(-45 , message.default_sint32 ()); - EXPECT_EQ( 46 , message.default_sint64 ()); - EXPECT_EQ( 47 , message.default_fixed32 ()); - EXPECT_EQ( 48 , message.default_fixed64 ()); - EXPECT_EQ( 49 , message.default_sfixed32()); - EXPECT_EQ(-50 , message.default_sfixed64()); - EXPECT_EQ( 51.5 , message.default_float ()); - EXPECT_EQ( 52e3 , message.default_double ()); - EXPECT_TRUE( message.default_bool ()); - EXPECT_EQ("hello", message.default_string ()); - EXPECT_EQ("world", message.default_bytes ()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.default_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_BAR , message.default_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.default_import_enum ()); - - - EXPECT_FALSE(message.has_oneof_uint32 ()); - EXPECT_FALSE(message.has_oneof_nested_message()); - EXPECT_FALSE(message.has_oneof_string ()); - EXPECT_FALSE(message.has_oneof_bytes ()); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectRepeatedFieldsModified( - const unittest::TestAllTypes& message) { - // ModifyRepeatedFields only sets the second repeated element of each - // field. In addition to verifying this, we also verify that the first - // element and size were *not* modified. - ASSERT_EQ(2, message.repeated_int32_size ()); - ASSERT_EQ(2, message.repeated_int64_size ()); - ASSERT_EQ(2, message.repeated_uint32_size ()); - ASSERT_EQ(2, message.repeated_uint64_size ()); - ASSERT_EQ(2, message.repeated_sint32_size ()); - ASSERT_EQ(2, message.repeated_sint64_size ()); - ASSERT_EQ(2, message.repeated_fixed32_size ()); - ASSERT_EQ(2, message.repeated_fixed64_size ()); - ASSERT_EQ(2, message.repeated_sfixed32_size()); - ASSERT_EQ(2, message.repeated_sfixed64_size()); - ASSERT_EQ(2, message.repeated_float_size ()); - ASSERT_EQ(2, message.repeated_double_size ()); - ASSERT_EQ(2, message.repeated_bool_size ()); - ASSERT_EQ(2, message.repeated_string_size ()); - ASSERT_EQ(2, message.repeated_bytes_size ()); - - ASSERT_EQ(2, message.repeatedgroup_size ()); - ASSERT_EQ(2, message.repeated_nested_message_size ()); - ASSERT_EQ(2, message.repeated_foreign_message_size()); - ASSERT_EQ(2, message.repeated_import_message_size ()); - ASSERT_EQ(2, message.repeated_lazy_message_size ()); - ASSERT_EQ(2, message.repeated_nested_enum_size ()); - ASSERT_EQ(2, message.repeated_foreign_enum_size ()); - ASSERT_EQ(2, message.repeated_import_enum_size ()); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - ASSERT_EQ(2, message.repeated_string_piece_size()); - ASSERT_EQ(2, message.repeated_cord_size()); -#endif - - EXPECT_EQ(201 , message.repeated_int32 (0)); - EXPECT_EQ(202 , message.repeated_int64 (0)); - EXPECT_EQ(203 , message.repeated_uint32 (0)); - EXPECT_EQ(204 , message.repeated_uint64 (0)); - EXPECT_EQ(205 , message.repeated_sint32 (0)); - EXPECT_EQ(206 , message.repeated_sint64 (0)); - EXPECT_EQ(207 , message.repeated_fixed32 (0)); - EXPECT_EQ(208 , message.repeated_fixed64 (0)); - EXPECT_EQ(209 , message.repeated_sfixed32(0)); - EXPECT_EQ(210 , message.repeated_sfixed64(0)); - EXPECT_EQ(211 , message.repeated_float (0)); - EXPECT_EQ(212 , message.repeated_double (0)); - EXPECT_TRUE( message.repeated_bool (0)); - EXPECT_EQ("215", message.repeated_string (0)); - EXPECT_EQ("216", message.repeated_bytes (0)); - - EXPECT_EQ(217, message.repeatedgroup (0).a()); - EXPECT_EQ(218, message.repeated_nested_message (0).bb()); - EXPECT_EQ(219, message.repeated_foreign_message(0).c()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); - EXPECT_EQ(227, message.repeated_lazy_message (0).bb()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.repeated_nested_enum (0)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.repeated_foreign_enum(0)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.repeated_import_enum (0)); - - - // Actually verify the second (modified) elements now. - EXPECT_EQ(501 , message.repeated_int32 (1)); - EXPECT_EQ(502 , message.repeated_int64 (1)); - EXPECT_EQ(503 , message.repeated_uint32 (1)); - EXPECT_EQ(504 , message.repeated_uint64 (1)); - EXPECT_EQ(505 , message.repeated_sint32 (1)); - EXPECT_EQ(506 , message.repeated_sint64 (1)); - EXPECT_EQ(507 , message.repeated_fixed32 (1)); - EXPECT_EQ(508 , message.repeated_fixed64 (1)); - EXPECT_EQ(509 , message.repeated_sfixed32(1)); - EXPECT_EQ(510 , message.repeated_sfixed64(1)); - EXPECT_EQ(511 , message.repeated_float (1)); - EXPECT_EQ(512 , message.repeated_double (1)); - EXPECT_TRUE( message.repeated_bool (1)); - EXPECT_EQ("515", message.repeated_string (1)); - EXPECT_EQ("516", message.repeated_bytes (1)); - - EXPECT_EQ(517, message.repeatedgroup (1).a()); - EXPECT_EQ(518, message.repeated_nested_message (1).bb()); - EXPECT_EQ(519, message.repeated_foreign_message(1).c()); - EXPECT_EQ(520, message.repeated_import_message (1).d()); - EXPECT_EQ(527, message.repeated_lazy_message (1).bb()); - - EXPECT_EQ(unittest::TestAllTypes::FOO, message.repeated_nested_enum (1)); - EXPECT_EQ(unittest::FOREIGN_FOO , message.repeated_foreign_enum(1)); - EXPECT_EQ(unittest_import::IMPORT_FOO, message.repeated_import_enum (1)); - -} - -// ------------------------------------------------------------------- - -void TestUtil::SetPackedFields(unittest::TestPackedTypes* message) { - message->add_packed_int32 (601); - message->add_packed_int64 (602); - message->add_packed_uint32 (603); - message->add_packed_uint64 (604); - message->add_packed_sint32 (605); - message->add_packed_sint64 (606); - message->add_packed_fixed32 (607); - message->add_packed_fixed64 (608); - message->add_packed_sfixed32(609); - message->add_packed_sfixed64(610); - message->add_packed_float (611); - message->add_packed_double (612); - message->add_packed_bool (true); - message->add_packed_enum (unittest::FOREIGN_BAR); - // add a second one of each field - message->add_packed_int32 (701); - message->add_packed_int64 (702); - message->add_packed_uint32 (703); - message->add_packed_uint64 (704); - message->add_packed_sint32 (705); - message->add_packed_sint64 (706); - message->add_packed_fixed32 (707); - message->add_packed_fixed64 (708); - message->add_packed_sfixed32(709); - message->add_packed_sfixed64(710); - message->add_packed_float (711); - message->add_packed_double (712); - message->add_packed_bool (false); - message->add_packed_enum (unittest::FOREIGN_BAZ); -} - -void TestUtil::SetUnpackedFields(unittest::TestUnpackedTypes* message) { - // The values applied here must match those of SetPackedFields. - - message->add_unpacked_int32 (601); - message->add_unpacked_int64 (602); - message->add_unpacked_uint32 (603); - message->add_unpacked_uint64 (604); - message->add_unpacked_sint32 (605); - message->add_unpacked_sint64 (606); - message->add_unpacked_fixed32 (607); - message->add_unpacked_fixed64 (608); - message->add_unpacked_sfixed32(609); - message->add_unpacked_sfixed64(610); - message->add_unpacked_float (611); - message->add_unpacked_double (612); - message->add_unpacked_bool (true); - message->add_unpacked_enum (unittest::FOREIGN_BAR); - // add a second one of each field - message->add_unpacked_int32 (701); - message->add_unpacked_int64 (702); - message->add_unpacked_uint32 (703); - message->add_unpacked_uint64 (704); - message->add_unpacked_sint32 (705); - message->add_unpacked_sint64 (706); - message->add_unpacked_fixed32 (707); - message->add_unpacked_fixed64 (708); - message->add_unpacked_sfixed32(709); - message->add_unpacked_sfixed64(710); - message->add_unpacked_float (711); - message->add_unpacked_double (712); - message->add_unpacked_bool (false); - message->add_unpacked_enum (unittest::FOREIGN_BAZ); -} - -// ------------------------------------------------------------------- - -void TestUtil::ModifyPackedFields(unittest::TestPackedTypes* message) { - message->set_packed_int32 (1, 801); - message->set_packed_int64 (1, 802); - message->set_packed_uint32 (1, 803); - message->set_packed_uint64 (1, 804); - message->set_packed_sint32 (1, 805); - message->set_packed_sint64 (1, 806); - message->set_packed_fixed32 (1, 807); - message->set_packed_fixed64 (1, 808); - message->set_packed_sfixed32(1, 809); - message->set_packed_sfixed64(1, 810); - message->set_packed_float (1, 811); - message->set_packed_double (1, 812); - message->set_packed_bool (1, true); - message->set_packed_enum (1, unittest::FOREIGN_FOO); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectPackedFieldsSet(const unittest::TestPackedTypes& message) { - ASSERT_EQ(2, message.packed_int32_size ()); - ASSERT_EQ(2, message.packed_int64_size ()); - ASSERT_EQ(2, message.packed_uint32_size ()); - ASSERT_EQ(2, message.packed_uint64_size ()); - ASSERT_EQ(2, message.packed_sint32_size ()); - ASSERT_EQ(2, message.packed_sint64_size ()); - ASSERT_EQ(2, message.packed_fixed32_size ()); - ASSERT_EQ(2, message.packed_fixed64_size ()); - ASSERT_EQ(2, message.packed_sfixed32_size()); - ASSERT_EQ(2, message.packed_sfixed64_size()); - ASSERT_EQ(2, message.packed_float_size ()); - ASSERT_EQ(2, message.packed_double_size ()); - ASSERT_EQ(2, message.packed_bool_size ()); - ASSERT_EQ(2, message.packed_enum_size ()); - - EXPECT_EQ(601 , message.packed_int32 (0)); - EXPECT_EQ(602 , message.packed_int64 (0)); - EXPECT_EQ(603 , message.packed_uint32 (0)); - EXPECT_EQ(604 , message.packed_uint64 (0)); - EXPECT_EQ(605 , message.packed_sint32 (0)); - EXPECT_EQ(606 , message.packed_sint64 (0)); - EXPECT_EQ(607 , message.packed_fixed32 (0)); - EXPECT_EQ(608 , message.packed_fixed64 (0)); - EXPECT_EQ(609 , message.packed_sfixed32(0)); - EXPECT_EQ(610 , message.packed_sfixed64(0)); - EXPECT_EQ(611 , message.packed_float (0)); - EXPECT_EQ(612 , message.packed_double (0)); - EXPECT_TRUE( message.packed_bool (0)); - EXPECT_EQ(unittest::FOREIGN_BAR, message.packed_enum(0)); - - EXPECT_EQ(701 , message.packed_int32 (1)); - EXPECT_EQ(702 , message.packed_int64 (1)); - EXPECT_EQ(703 , message.packed_uint32 (1)); - EXPECT_EQ(704 , message.packed_uint64 (1)); - EXPECT_EQ(705 , message.packed_sint32 (1)); - EXPECT_EQ(706 , message.packed_sint64 (1)); - EXPECT_EQ(707 , message.packed_fixed32 (1)); - EXPECT_EQ(708 , message.packed_fixed64 (1)); - EXPECT_EQ(709 , message.packed_sfixed32(1)); - EXPECT_EQ(710 , message.packed_sfixed64(1)); - EXPECT_EQ(711 , message.packed_float (1)); - EXPECT_EQ(712 , message.packed_double (1)); - EXPECT_FALSE( message.packed_bool (1)); - EXPECT_EQ(unittest::FOREIGN_BAZ, message.packed_enum(1)); -} - -void TestUtil::ExpectUnpackedFieldsSet( - const unittest::TestUnpackedTypes& message) { - // The values expected here must match those of ExpectPackedFieldsSet. - - ASSERT_EQ(2, message.unpacked_int32_size ()); - ASSERT_EQ(2, message.unpacked_int64_size ()); - ASSERT_EQ(2, message.unpacked_uint32_size ()); - ASSERT_EQ(2, message.unpacked_uint64_size ()); - ASSERT_EQ(2, message.unpacked_sint32_size ()); - ASSERT_EQ(2, message.unpacked_sint64_size ()); - ASSERT_EQ(2, message.unpacked_fixed32_size ()); - ASSERT_EQ(2, message.unpacked_fixed64_size ()); - ASSERT_EQ(2, message.unpacked_sfixed32_size()); - ASSERT_EQ(2, message.unpacked_sfixed64_size()); - ASSERT_EQ(2, message.unpacked_float_size ()); - ASSERT_EQ(2, message.unpacked_double_size ()); - ASSERT_EQ(2, message.unpacked_bool_size ()); - ASSERT_EQ(2, message.unpacked_enum_size ()); - - EXPECT_EQ(601 , message.unpacked_int32 (0)); - EXPECT_EQ(602 , message.unpacked_int64 (0)); - EXPECT_EQ(603 , message.unpacked_uint32 (0)); - EXPECT_EQ(604 , message.unpacked_uint64 (0)); - EXPECT_EQ(605 , message.unpacked_sint32 (0)); - EXPECT_EQ(606 , message.unpacked_sint64 (0)); - EXPECT_EQ(607 , message.unpacked_fixed32 (0)); - EXPECT_EQ(608 , message.unpacked_fixed64 (0)); - EXPECT_EQ(609 , message.unpacked_sfixed32(0)); - EXPECT_EQ(610 , message.unpacked_sfixed64(0)); - EXPECT_EQ(611 , message.unpacked_float (0)); - EXPECT_EQ(612 , message.unpacked_double (0)); - EXPECT_TRUE( message.unpacked_bool (0)); - EXPECT_EQ(unittest::FOREIGN_BAR, message.unpacked_enum(0)); - - EXPECT_EQ(701 , message.unpacked_int32 (1)); - EXPECT_EQ(702 , message.unpacked_int64 (1)); - EXPECT_EQ(703 , message.unpacked_uint32 (1)); - EXPECT_EQ(704 , message.unpacked_uint64 (1)); - EXPECT_EQ(705 , message.unpacked_sint32 (1)); - EXPECT_EQ(706 , message.unpacked_sint64 (1)); - EXPECT_EQ(707 , message.unpacked_fixed32 (1)); - EXPECT_EQ(708 , message.unpacked_fixed64 (1)); - EXPECT_EQ(709 , message.unpacked_sfixed32(1)); - EXPECT_EQ(710 , message.unpacked_sfixed64(1)); - EXPECT_EQ(711 , message.unpacked_float (1)); - EXPECT_EQ(712 , message.unpacked_double (1)); - EXPECT_FALSE( message.unpacked_bool (1)); - EXPECT_EQ(unittest::FOREIGN_BAZ, message.unpacked_enum(1)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectPackedClear( - const unittest::TestPackedTypes& message) { - // Packed repeated fields are empty. - EXPECT_EQ(0, message.packed_int32_size ()); - EXPECT_EQ(0, message.packed_int64_size ()); - EXPECT_EQ(0, message.packed_uint32_size ()); - EXPECT_EQ(0, message.packed_uint64_size ()); - EXPECT_EQ(0, message.packed_sint32_size ()); - EXPECT_EQ(0, message.packed_sint64_size ()); - EXPECT_EQ(0, message.packed_fixed32_size ()); - EXPECT_EQ(0, message.packed_fixed64_size ()); - EXPECT_EQ(0, message.packed_sfixed32_size()); - EXPECT_EQ(0, message.packed_sfixed64_size()); - EXPECT_EQ(0, message.packed_float_size ()); - EXPECT_EQ(0, message.packed_double_size ()); - EXPECT_EQ(0, message.packed_bool_size ()); - EXPECT_EQ(0, message.packed_enum_size ()); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectPackedFieldsModified( - const unittest::TestPackedTypes& message) { - // Do the same for packed repeated fields. - ASSERT_EQ(2, message.packed_int32_size ()); - ASSERT_EQ(2, message.packed_int64_size ()); - ASSERT_EQ(2, message.packed_uint32_size ()); - ASSERT_EQ(2, message.packed_uint64_size ()); - ASSERT_EQ(2, message.packed_sint32_size ()); - ASSERT_EQ(2, message.packed_sint64_size ()); - ASSERT_EQ(2, message.packed_fixed32_size ()); - ASSERT_EQ(2, message.packed_fixed64_size ()); - ASSERT_EQ(2, message.packed_sfixed32_size()); - ASSERT_EQ(2, message.packed_sfixed64_size()); - ASSERT_EQ(2, message.packed_float_size ()); - ASSERT_EQ(2, message.packed_double_size ()); - ASSERT_EQ(2, message.packed_bool_size ()); - ASSERT_EQ(2, message.packed_enum_size ()); - - EXPECT_EQ(601 , message.packed_int32 (0)); - EXPECT_EQ(602 , message.packed_int64 (0)); - EXPECT_EQ(603 , message.packed_uint32 (0)); - EXPECT_EQ(604 , message.packed_uint64 (0)); - EXPECT_EQ(605 , message.packed_sint32 (0)); - EXPECT_EQ(606 , message.packed_sint64 (0)); - EXPECT_EQ(607 , message.packed_fixed32 (0)); - EXPECT_EQ(608 , message.packed_fixed64 (0)); - EXPECT_EQ(609 , message.packed_sfixed32(0)); - EXPECT_EQ(610 , message.packed_sfixed64(0)); - EXPECT_EQ(611 , message.packed_float (0)); - EXPECT_EQ(612 , message.packed_double (0)); - EXPECT_TRUE( message.packed_bool (0)); - EXPECT_EQ(unittest::FOREIGN_BAR, message.packed_enum(0)); - // Actually verify the second (modified) elements now. - EXPECT_EQ(801 , message.packed_int32 (1)); - EXPECT_EQ(802 , message.packed_int64 (1)); - EXPECT_EQ(803 , message.packed_uint32 (1)); - EXPECT_EQ(804 , message.packed_uint64 (1)); - EXPECT_EQ(805 , message.packed_sint32 (1)); - EXPECT_EQ(806 , message.packed_sint64 (1)); - EXPECT_EQ(807 , message.packed_fixed32 (1)); - EXPECT_EQ(808 , message.packed_fixed64 (1)); - EXPECT_EQ(809 , message.packed_sfixed32(1)); - EXPECT_EQ(810 , message.packed_sfixed64(1)); - EXPECT_EQ(811 , message.packed_float (1)); - EXPECT_EQ(812 , message.packed_double (1)); - EXPECT_TRUE( message.packed_bool (1)); - EXPECT_EQ(unittest::FOREIGN_FOO, message.packed_enum(1)); -} - -// =================================================================== -// Extensions -// -// All this code is exactly equivalent to the above code except that it's -// manipulating extension fields instead of normal ones. -// -// I gave up on the 80-char limit here. Sorry. - -void TestUtil::SetAllExtensions(unittest::TestAllExtensions* message) { - message->SetExtension(unittest::optional_int32_extension , 101); - message->SetExtension(unittest::optional_int64_extension , 102); - message->SetExtension(unittest::optional_uint32_extension , 103); - message->SetExtension(unittest::optional_uint64_extension , 104); - message->SetExtension(unittest::optional_sint32_extension , 105); - message->SetExtension(unittest::optional_sint64_extension , 106); - message->SetExtension(unittest::optional_fixed32_extension , 107); - message->SetExtension(unittest::optional_fixed64_extension , 108); - message->SetExtension(unittest::optional_sfixed32_extension, 109); - message->SetExtension(unittest::optional_sfixed64_extension, 110); - message->SetExtension(unittest::optional_float_extension , 111); - message->SetExtension(unittest::optional_double_extension , 112); - message->SetExtension(unittest::optional_bool_extension , true); - message->SetExtension(unittest::optional_string_extension , "115"); - message->SetExtension(unittest::optional_bytes_extension , "116"); - - message->MutableExtension(unittest::optionalgroup_extension )->set_a(117); - message->MutableExtension(unittest::optional_nested_message_extension )->set_bb(118); - message->MutableExtension(unittest::optional_foreign_message_extension)->set_c(119); - message->MutableExtension(unittest::optional_import_message_extension )->set_d(120); - - message->SetExtension(unittest::optional_nested_enum_extension , unittest::TestAllTypes::BAZ); - message->SetExtension(unittest::optional_foreign_enum_extension, unittest::FOREIGN_BAZ ); - message->SetExtension(unittest::optional_import_enum_extension , unittest_import::IMPORT_BAZ); - - message->SetExtension(unittest::optional_string_piece_extension, "124"); - message->SetExtension(unittest::optional_cord_extension, "125"); - - message->MutableExtension(unittest::optional_public_import_message_extension)->set_e(126); - message->MutableExtension(unittest::optional_lazy_message_extension)->set_bb(127); - - // ----------------------------------------------------------------- - - message->AddExtension(unittest::repeated_int32_extension , 201); - message->AddExtension(unittest::repeated_int64_extension , 202); - message->AddExtension(unittest::repeated_uint32_extension , 203); - message->AddExtension(unittest::repeated_uint64_extension , 204); - message->AddExtension(unittest::repeated_sint32_extension , 205); - message->AddExtension(unittest::repeated_sint64_extension , 206); - message->AddExtension(unittest::repeated_fixed32_extension , 207); - message->AddExtension(unittest::repeated_fixed64_extension , 208); - message->AddExtension(unittest::repeated_sfixed32_extension, 209); - message->AddExtension(unittest::repeated_sfixed64_extension, 210); - message->AddExtension(unittest::repeated_float_extension , 211); - message->AddExtension(unittest::repeated_double_extension , 212); - message->AddExtension(unittest::repeated_bool_extension , true); - message->AddExtension(unittest::repeated_string_extension , "215"); - message->AddExtension(unittest::repeated_bytes_extension , "216"); - - message->AddExtension(unittest::repeatedgroup_extension )->set_a(217); - message->AddExtension(unittest::repeated_nested_message_extension )->set_bb(218); - message->AddExtension(unittest::repeated_foreign_message_extension)->set_c(219); - message->AddExtension(unittest::repeated_import_message_extension )->set_d(220); - message->AddExtension(unittest::repeated_lazy_message_extension )->set_bb(227); - - message->AddExtension(unittest::repeated_nested_enum_extension , unittest::TestAllTypes::BAR); - message->AddExtension(unittest::repeated_foreign_enum_extension, unittest::FOREIGN_BAR ); - message->AddExtension(unittest::repeated_import_enum_extension , unittest_import::IMPORT_BAR); - - message->AddExtension(unittest::repeated_string_piece_extension, "224"); - message->AddExtension(unittest::repeated_cord_extension, "225"); - - // Add a second one of each field. - message->AddExtension(unittest::repeated_int32_extension , 301); - message->AddExtension(unittest::repeated_int64_extension , 302); - message->AddExtension(unittest::repeated_uint32_extension , 303); - message->AddExtension(unittest::repeated_uint64_extension , 304); - message->AddExtension(unittest::repeated_sint32_extension , 305); - message->AddExtension(unittest::repeated_sint64_extension , 306); - message->AddExtension(unittest::repeated_fixed32_extension , 307); - message->AddExtension(unittest::repeated_fixed64_extension , 308); - message->AddExtension(unittest::repeated_sfixed32_extension, 309); - message->AddExtension(unittest::repeated_sfixed64_extension, 310); - message->AddExtension(unittest::repeated_float_extension , 311); - message->AddExtension(unittest::repeated_double_extension , 312); - message->AddExtension(unittest::repeated_bool_extension , false); - message->AddExtension(unittest::repeated_string_extension , "315"); - message->AddExtension(unittest::repeated_bytes_extension , "316"); - - message->AddExtension(unittest::repeatedgroup_extension )->set_a(317); - message->AddExtension(unittest::repeated_nested_message_extension )->set_bb(318); - message->AddExtension(unittest::repeated_foreign_message_extension)->set_c(319); - message->AddExtension(unittest::repeated_import_message_extension )->set_d(320); - message->AddExtension(unittest::repeated_lazy_message_extension )->set_bb(327); - - message->AddExtension(unittest::repeated_nested_enum_extension , unittest::TestAllTypes::BAZ); - message->AddExtension(unittest::repeated_foreign_enum_extension, unittest::FOREIGN_BAZ ); - message->AddExtension(unittest::repeated_import_enum_extension , unittest_import::IMPORT_BAZ); - - message->AddExtension(unittest::repeated_string_piece_extension, "324"); - message->AddExtension(unittest::repeated_cord_extension, "325"); - - // ----------------------------------------------------------------- - - message->SetExtension(unittest::default_int32_extension , 401); - message->SetExtension(unittest::default_int64_extension , 402); - message->SetExtension(unittest::default_uint32_extension , 403); - message->SetExtension(unittest::default_uint64_extension , 404); - message->SetExtension(unittest::default_sint32_extension , 405); - message->SetExtension(unittest::default_sint64_extension , 406); - message->SetExtension(unittest::default_fixed32_extension , 407); - message->SetExtension(unittest::default_fixed64_extension , 408); - message->SetExtension(unittest::default_sfixed32_extension, 409); - message->SetExtension(unittest::default_sfixed64_extension, 410); - message->SetExtension(unittest::default_float_extension , 411); - message->SetExtension(unittest::default_double_extension , 412); - message->SetExtension(unittest::default_bool_extension , false); - message->SetExtension(unittest::default_string_extension , "415"); - message->SetExtension(unittest::default_bytes_extension , "416"); - - message->SetExtension(unittest::default_nested_enum_extension , unittest::TestAllTypes::FOO); - message->SetExtension(unittest::default_foreign_enum_extension, unittest::FOREIGN_FOO ); - message->SetExtension(unittest::default_import_enum_extension , unittest_import::IMPORT_FOO); - - message->SetExtension(unittest::default_string_piece_extension, "424"); - message->SetExtension(unittest::default_cord_extension, "425"); - - SetOneofFields(message); -} - -void TestUtil::SetOneofFields(unittest::TestAllExtensions* message) { - message->SetExtension(unittest::oneof_uint32_extension, 601); - message->MutableExtension(unittest::oneof_nested_message_extension)->set_bb(602); - message->SetExtension(unittest::oneof_string_extension, "603"); - message->SetExtension(unittest::oneof_bytes_extension, "604"); -} - -// ------------------------------------------------------------------- - -void TestUtil::SetAllFieldsAndExtensions( - unittest::TestFieldOrderings* message) { - GOOGLE_CHECK(message); - message->set_my_int(1); - message->set_my_string("foo"); - message->set_my_float(1.0); - message->SetExtension(unittest::my_extension_int, 23); - message->SetExtension(unittest::my_extension_string, "bar"); -} - -// ------------------------------------------------------------------- - -void TestUtil::ModifyRepeatedExtensions(unittest::TestAllExtensions* message) { - message->SetExtension(unittest::repeated_int32_extension , 1, 501); - message->SetExtension(unittest::repeated_int64_extension , 1, 502); - message->SetExtension(unittest::repeated_uint32_extension , 1, 503); - message->SetExtension(unittest::repeated_uint64_extension , 1, 504); - message->SetExtension(unittest::repeated_sint32_extension , 1, 505); - message->SetExtension(unittest::repeated_sint64_extension , 1, 506); - message->SetExtension(unittest::repeated_fixed32_extension , 1, 507); - message->SetExtension(unittest::repeated_fixed64_extension , 1, 508); - message->SetExtension(unittest::repeated_sfixed32_extension, 1, 509); - message->SetExtension(unittest::repeated_sfixed64_extension, 1, 510); - message->SetExtension(unittest::repeated_float_extension , 1, 511); - message->SetExtension(unittest::repeated_double_extension , 1, 512); - message->SetExtension(unittest::repeated_bool_extension , 1, true); - message->SetExtension(unittest::repeated_string_extension , 1, "515"); - message->SetExtension(unittest::repeated_bytes_extension , 1, "516"); - - message->MutableExtension(unittest::repeatedgroup_extension , 1)->set_a(517); - message->MutableExtension(unittest::repeated_nested_message_extension , 1)->set_bb(518); - message->MutableExtension(unittest::repeated_foreign_message_extension, 1)->set_c(519); - message->MutableExtension(unittest::repeated_import_message_extension , 1)->set_d(520); - message->MutableExtension(unittest::repeated_lazy_message_extension , 1)->set_bb(527); - - message->SetExtension(unittest::repeated_nested_enum_extension , 1, unittest::TestAllTypes::FOO); - message->SetExtension(unittest::repeated_foreign_enum_extension, 1, unittest::FOREIGN_FOO ); - message->SetExtension(unittest::repeated_import_enum_extension , 1, unittest_import::IMPORT_FOO); - - message->SetExtension(unittest::repeated_string_piece_extension, 1, "524"); - message->SetExtension(unittest::repeated_cord_extension, 1, "525"); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectAllExtensionsSet( - const unittest::TestAllExtensions& message) { - EXPECT_TRUE(message.HasExtension(unittest::optional_int32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_int64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_uint32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_uint64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_sint32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_sint64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_fixed32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_fixed64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_sfixed32_extension)); - EXPECT_TRUE(message.HasExtension(unittest::optional_sfixed64_extension)); - EXPECT_TRUE(message.HasExtension(unittest::optional_float_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_double_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_bool_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_string_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_bytes_extension )); - - EXPECT_TRUE(message.HasExtension(unittest::optionalgroup_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_nested_message_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_foreign_message_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_import_message_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_public_import_message_extension)); - EXPECT_TRUE(message.HasExtension(unittest::optional_lazy_message_extension )); - - EXPECT_TRUE(message.GetExtension(unittest::optionalgroup_extension ).has_a()); - EXPECT_TRUE(message.GetExtension(unittest::optional_nested_message_extension ).has_bb()); - EXPECT_TRUE(message.GetExtension(unittest::optional_foreign_message_extension ).has_c()); - EXPECT_TRUE(message.GetExtension(unittest::optional_import_message_extension ).has_d()); - EXPECT_TRUE(message.GetExtension(unittest::optional_public_import_message_extension).has_e()); - EXPECT_TRUE(message.GetExtension(unittest::optional_lazy_message_extension ).has_bb()); - - EXPECT_TRUE(message.HasExtension(unittest::optional_nested_enum_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_foreign_enum_extension)); - EXPECT_TRUE(message.HasExtension(unittest::optional_import_enum_extension )); - - EXPECT_TRUE(message.HasExtension(unittest::optional_string_piece_extension)); - EXPECT_TRUE(message.HasExtension(unittest::optional_cord_extension)); - - EXPECT_EQ(101 , message.GetExtension(unittest::optional_int32_extension )); - EXPECT_EQ(102 , message.GetExtension(unittest::optional_int64_extension )); - EXPECT_EQ(103 , message.GetExtension(unittest::optional_uint32_extension )); - EXPECT_EQ(104 , message.GetExtension(unittest::optional_uint64_extension )); - EXPECT_EQ(105 , message.GetExtension(unittest::optional_sint32_extension )); - EXPECT_EQ(106 , message.GetExtension(unittest::optional_sint64_extension )); - EXPECT_EQ(107 , message.GetExtension(unittest::optional_fixed32_extension )); - EXPECT_EQ(108 , message.GetExtension(unittest::optional_fixed64_extension )); - EXPECT_EQ(109 , message.GetExtension(unittest::optional_sfixed32_extension)); - EXPECT_EQ(110 , message.GetExtension(unittest::optional_sfixed64_extension)); - EXPECT_EQ(111 , message.GetExtension(unittest::optional_float_extension )); - EXPECT_EQ(112 , message.GetExtension(unittest::optional_double_extension )); - EXPECT_TRUE( message.GetExtension(unittest::optional_bool_extension )); - EXPECT_EQ("115", message.GetExtension(unittest::optional_string_extension )); - EXPECT_EQ("116", message.GetExtension(unittest::optional_bytes_extension )); - - EXPECT_EQ(117, message.GetExtension(unittest::optionalgroup_extension ).a()); - EXPECT_EQ(118, message.GetExtension(unittest::optional_nested_message_extension ).bb()); - EXPECT_EQ(119, message.GetExtension(unittest::optional_foreign_message_extension).c()); - EXPECT_EQ(120, message.GetExtension(unittest::optional_import_message_extension ).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAZ, message.GetExtension(unittest::optional_nested_enum_extension )); - EXPECT_EQ(unittest::FOREIGN_BAZ , message.GetExtension(unittest::optional_foreign_enum_extension)); - EXPECT_EQ(unittest_import::IMPORT_BAZ, message.GetExtension(unittest::optional_import_enum_extension )); - - EXPECT_EQ("124", message.GetExtension(unittest::optional_string_piece_extension)); - EXPECT_EQ("125", message.GetExtension(unittest::optional_cord_extension)); - EXPECT_EQ(126, message.GetExtension(unittest::optional_public_import_message_extension ).e()); - EXPECT_EQ(127, message.GetExtension(unittest::optional_lazy_message_extension).bb()); - - // ----------------------------------------------------------------- - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed32_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed64_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_float_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_double_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bool_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bytes_extension )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeatedgroup_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_message_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_lazy_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_enum_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_enum_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_enum_extension )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_piece_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_cord_extension)); - - EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension , 0)); - EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension , 0)); - EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension , 0)); - EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension , 0)); - EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension , 0)); - EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension , 0)); - EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension , 0)); - EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension , 0)); - EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension, 0)); - EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension, 0)); - EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension , 0)); - EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension , 0)); - EXPECT_TRUE( message.GetExtension(unittest::repeated_bool_extension , 0)); - EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension , 0)); - EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension , 0)); - - EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 0).a()); - EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb()); - EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c()); - EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 0).d()); - EXPECT_EQ(227, message.GetExtension(unittest::repeated_lazy_message_extension , 0).bb()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::repeated_nested_enum_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension, 0)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::repeated_import_enum_extension , 0)); - - EXPECT_EQ("224", message.GetExtension(unittest::repeated_string_piece_extension, 0)); - EXPECT_EQ("225", message.GetExtension(unittest::repeated_cord_extension, 0)); - - EXPECT_EQ(301 , message.GetExtension(unittest::repeated_int32_extension , 1)); - EXPECT_EQ(302 , message.GetExtension(unittest::repeated_int64_extension , 1)); - EXPECT_EQ(303 , message.GetExtension(unittest::repeated_uint32_extension , 1)); - EXPECT_EQ(304 , message.GetExtension(unittest::repeated_uint64_extension , 1)); - EXPECT_EQ(305 , message.GetExtension(unittest::repeated_sint32_extension , 1)); - EXPECT_EQ(306 , message.GetExtension(unittest::repeated_sint64_extension , 1)); - EXPECT_EQ(307 , message.GetExtension(unittest::repeated_fixed32_extension , 1)); - EXPECT_EQ(308 , message.GetExtension(unittest::repeated_fixed64_extension , 1)); - EXPECT_EQ(309 , message.GetExtension(unittest::repeated_sfixed32_extension, 1)); - EXPECT_EQ(310 , message.GetExtension(unittest::repeated_sfixed64_extension, 1)); - EXPECT_EQ(311 , message.GetExtension(unittest::repeated_float_extension , 1)); - EXPECT_EQ(312 , message.GetExtension(unittest::repeated_double_extension , 1)); - EXPECT_FALSE( message.GetExtension(unittest::repeated_bool_extension , 1)); - EXPECT_EQ("315", message.GetExtension(unittest::repeated_string_extension , 1)); - EXPECT_EQ("316", message.GetExtension(unittest::repeated_bytes_extension , 1)); - - EXPECT_EQ(317, message.GetExtension(unittest::repeatedgroup_extension , 1).a()); - EXPECT_EQ(318, message.GetExtension(unittest::repeated_nested_message_extension , 1).bb()); - EXPECT_EQ(319, message.GetExtension(unittest::repeated_foreign_message_extension, 1).c()); - EXPECT_EQ(320, message.GetExtension(unittest::repeated_import_message_extension , 1).d()); - EXPECT_EQ(327, message.GetExtension(unittest::repeated_lazy_message_extension , 1).bb()); - - EXPECT_EQ(unittest::TestAllTypes::BAZ, message.GetExtension(unittest::repeated_nested_enum_extension , 1)); - EXPECT_EQ(unittest::FOREIGN_BAZ , message.GetExtension(unittest::repeated_foreign_enum_extension, 1)); - EXPECT_EQ(unittest_import::IMPORT_BAZ, message.GetExtension(unittest::repeated_import_enum_extension , 1)); - - EXPECT_EQ("324", message.GetExtension(unittest::repeated_string_piece_extension, 1)); - EXPECT_EQ("325", message.GetExtension(unittest::repeated_cord_extension, 1)); - - // ----------------------------------------------------------------- - - EXPECT_TRUE(message.HasExtension(unittest::default_int32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_int64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_uint32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_uint64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_sint32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_sint64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_fixed32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_fixed64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_sfixed32_extension)); - EXPECT_TRUE(message.HasExtension(unittest::default_sfixed64_extension)); - EXPECT_TRUE(message.HasExtension(unittest::default_float_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_double_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_bool_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_string_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_bytes_extension )); - - EXPECT_TRUE(message.HasExtension(unittest::default_nested_enum_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_foreign_enum_extension)); - EXPECT_TRUE(message.HasExtension(unittest::default_import_enum_extension )); - - EXPECT_TRUE(message.HasExtension(unittest::default_string_piece_extension)); - EXPECT_TRUE(message.HasExtension(unittest::default_cord_extension)); - - EXPECT_EQ(401 , message.GetExtension(unittest::default_int32_extension )); - EXPECT_EQ(402 , message.GetExtension(unittest::default_int64_extension )); - EXPECT_EQ(403 , message.GetExtension(unittest::default_uint32_extension )); - EXPECT_EQ(404 , message.GetExtension(unittest::default_uint64_extension )); - EXPECT_EQ(405 , message.GetExtension(unittest::default_sint32_extension )); - EXPECT_EQ(406 , message.GetExtension(unittest::default_sint64_extension )); - EXPECT_EQ(407 , message.GetExtension(unittest::default_fixed32_extension )); - EXPECT_EQ(408 , message.GetExtension(unittest::default_fixed64_extension )); - EXPECT_EQ(409 , message.GetExtension(unittest::default_sfixed32_extension)); - EXPECT_EQ(410 , message.GetExtension(unittest::default_sfixed64_extension)); - EXPECT_EQ(411 , message.GetExtension(unittest::default_float_extension )); - EXPECT_EQ(412 , message.GetExtension(unittest::default_double_extension )); - EXPECT_FALSE( message.GetExtension(unittest::default_bool_extension )); - EXPECT_EQ("415", message.GetExtension(unittest::default_string_extension )); - EXPECT_EQ("416", message.GetExtension(unittest::default_bytes_extension )); - - EXPECT_EQ(unittest::TestAllTypes::FOO, message.GetExtension(unittest::default_nested_enum_extension )); - EXPECT_EQ(unittest::FOREIGN_FOO , message.GetExtension(unittest::default_foreign_enum_extension)); - EXPECT_EQ(unittest_import::IMPORT_FOO, message.GetExtension(unittest::default_import_enum_extension )); - - EXPECT_EQ("424", message.GetExtension(unittest::default_string_piece_extension)); - EXPECT_EQ("425", message.GetExtension(unittest::default_cord_extension)); - - EXPECT_TRUE(message.HasExtension(unittest::oneof_uint32_extension)); - EXPECT_TRUE(message.GetExtension(unittest::oneof_nested_message_extension).has_bb()); - EXPECT_TRUE(message.HasExtension(unittest::oneof_string_extension)); - EXPECT_TRUE(message.HasExtension(unittest::oneof_bytes_extension)); - - EXPECT_EQ(601, message.GetExtension(unittest::oneof_uint32_extension)); - EXPECT_EQ(602, message.GetExtension(unittest::oneof_nested_message_extension).bb()); - EXPECT_EQ("603", message.GetExtension(unittest::oneof_string_extension)); - EXPECT_EQ("604", message.GetExtension(unittest::oneof_bytes_extension)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectExtensionsClear( - const unittest::TestAllExtensions& message) { - string serialized; - ASSERT_TRUE(message.SerializeToString(&serialized)); - EXPECT_EQ("", serialized); - EXPECT_EQ(0, message.ByteSize()); - - // has_blah() should initially be false for all optional fields. - EXPECT_FALSE(message.HasExtension(unittest::optional_int32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_int64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_uint32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_uint64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_sint32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_sint64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_fixed32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_fixed64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_sfixed32_extension)); - EXPECT_FALSE(message.HasExtension(unittest::optional_sfixed64_extension)); - EXPECT_FALSE(message.HasExtension(unittest::optional_float_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_double_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_bool_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_string_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_bytes_extension )); - - EXPECT_FALSE(message.HasExtension(unittest::optionalgroup_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_nested_message_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_foreign_message_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_import_message_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_public_import_message_extension)); - EXPECT_FALSE(message.HasExtension(unittest::optional_lazy_message_extension )); - - EXPECT_FALSE(message.HasExtension(unittest::optional_nested_enum_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_foreign_enum_extension)); - EXPECT_FALSE(message.HasExtension(unittest::optional_import_enum_extension )); - - EXPECT_FALSE(message.HasExtension(unittest::optional_string_piece_extension)); - EXPECT_FALSE(message.HasExtension(unittest::optional_cord_extension)); - - // Optional fields without defaults are set to zero or something like it. - EXPECT_EQ(0 , message.GetExtension(unittest::optional_int32_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_int64_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_uint32_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_uint64_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sint32_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sint64_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_fixed32_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_fixed64_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sfixed32_extension)); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sfixed64_extension)); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_float_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_double_extension )); - EXPECT_FALSE( message.GetExtension(unittest::optional_bool_extension )); - EXPECT_EQ("" , message.GetExtension(unittest::optional_string_extension )); - EXPECT_EQ("" , message.GetExtension(unittest::optional_bytes_extension )); - - // Embedded messages should also be clear. - EXPECT_FALSE(message.GetExtension(unittest::optionalgroup_extension ).has_a()); - EXPECT_FALSE(message.GetExtension(unittest::optional_nested_message_extension ).has_bb()); - EXPECT_FALSE(message.GetExtension(unittest::optional_foreign_message_extension ).has_c()); - EXPECT_FALSE(message.GetExtension(unittest::optional_import_message_extension ).has_d()); - EXPECT_FALSE(message.GetExtension(unittest::optional_public_import_message_extension).has_e()); - EXPECT_FALSE(message.GetExtension(unittest::optional_lazy_message_extension ).has_bb()); - - EXPECT_EQ(0, message.GetExtension(unittest::optionalgroup_extension ).a()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_nested_message_extension ).bb()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_foreign_message_extension ).c()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_import_message_extension ).d()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_public_import_message_extension).e()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_lazy_message_extension ).bb()); - - // Enums without defaults are set to the first value in the enum. - EXPECT_EQ(unittest::TestAllTypes::FOO, message.GetExtension(unittest::optional_nested_enum_extension )); - EXPECT_EQ(unittest::FOREIGN_FOO , message.GetExtension(unittest::optional_foreign_enum_extension)); - EXPECT_EQ(unittest_import::IMPORT_FOO, message.GetExtension(unittest::optional_import_enum_extension )); - - EXPECT_EQ("", message.GetExtension(unittest::optional_string_piece_extension)); - EXPECT_EQ("", message.GetExtension(unittest::optional_cord_extension)); - - // Repeated fields are empty. - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_int32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_int64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_uint32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_uint64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sint32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sint64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_fixed32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_fixed64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sfixed32_extension)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sfixed64_extension)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_float_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_double_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_bool_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_string_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_bytes_extension )); - - EXPECT_EQ(0, message.ExtensionSize(unittest::repeatedgroup_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_nested_message_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_foreign_message_extension)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_import_message_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_lazy_message_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_nested_enum_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_foreign_enum_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_import_enum_extension )); - - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_string_piece_extension)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_cord_extension)); - - // has_blah() should also be false for all default fields. - EXPECT_FALSE(message.HasExtension(unittest::default_int32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_int64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_uint32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_uint64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_sint32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_sint64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_fixed32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_fixed64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_sfixed32_extension)); - EXPECT_FALSE(message.HasExtension(unittest::default_sfixed64_extension)); - EXPECT_FALSE(message.HasExtension(unittest::default_float_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_double_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_bool_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_string_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_bytes_extension )); - - EXPECT_FALSE(message.HasExtension(unittest::default_nested_enum_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_foreign_enum_extension)); - EXPECT_FALSE(message.HasExtension(unittest::default_import_enum_extension )); - - EXPECT_FALSE(message.HasExtension(unittest::default_string_piece_extension)); - EXPECT_FALSE(message.HasExtension(unittest::default_cord_extension)); - - // Fields with defaults have their default values (duh). - EXPECT_EQ( 41 , message.GetExtension(unittest::default_int32_extension )); - EXPECT_EQ( 42 , message.GetExtension(unittest::default_int64_extension )); - EXPECT_EQ( 43 , message.GetExtension(unittest::default_uint32_extension )); - EXPECT_EQ( 44 , message.GetExtension(unittest::default_uint64_extension )); - EXPECT_EQ(-45 , message.GetExtension(unittest::default_sint32_extension )); - EXPECT_EQ( 46 , message.GetExtension(unittest::default_sint64_extension )); - EXPECT_EQ( 47 , message.GetExtension(unittest::default_fixed32_extension )); - EXPECT_EQ( 48 , message.GetExtension(unittest::default_fixed64_extension )); - EXPECT_EQ( 49 , message.GetExtension(unittest::default_sfixed32_extension)); - EXPECT_EQ(-50 , message.GetExtension(unittest::default_sfixed64_extension)); - EXPECT_EQ( 51.5 , message.GetExtension(unittest::default_float_extension )); - EXPECT_EQ( 52e3 , message.GetExtension(unittest::default_double_extension )); - EXPECT_TRUE( message.GetExtension(unittest::default_bool_extension )); - EXPECT_EQ("hello", message.GetExtension(unittest::default_string_extension )); - EXPECT_EQ("world", message.GetExtension(unittest::default_bytes_extension )); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::default_nested_enum_extension )); - EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::default_foreign_enum_extension)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::default_import_enum_extension )); - - EXPECT_EQ("abc", message.GetExtension(unittest::default_string_piece_extension)); - EXPECT_EQ("123", message.GetExtension(unittest::default_cord_extension)); - - EXPECT_FALSE(message.HasExtension(unittest::oneof_uint32_extension)); - EXPECT_FALSE(message.GetExtension(unittest::oneof_nested_message_extension).has_bb()); - EXPECT_FALSE(message.HasExtension(unittest::oneof_string_extension)); - EXPECT_FALSE(message.HasExtension(unittest::oneof_bytes_extension)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectRepeatedExtensionsModified( - const unittest::TestAllExtensions& message) { - // ModifyRepeatedFields only sets the second repeated element of each - // field. In addition to verifying this, we also verify that the first - // element and size were *not* modified. - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed32_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed64_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_float_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_double_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bool_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bytes_extension )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeatedgroup_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_message_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_lazy_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_enum_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_enum_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_enum_extension )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_piece_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_cord_extension)); - - EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension , 0)); - EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension , 0)); - EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension , 0)); - EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension , 0)); - EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension , 0)); - EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension , 0)); - EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension , 0)); - EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension , 0)); - EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension, 0)); - EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension, 0)); - EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension , 0)); - EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension , 0)); - EXPECT_TRUE( message.GetExtension(unittest::repeated_bool_extension , 0)); - EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension , 0)); - EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension , 0)); - - EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 0).a()); - EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb()); - EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c()); - EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 0).d()); - EXPECT_EQ(227, message.GetExtension(unittest::repeated_lazy_message_extension , 0).bb()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::repeated_nested_enum_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension, 0)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::repeated_import_enum_extension , 0)); - - EXPECT_EQ("224", message.GetExtension(unittest::repeated_string_piece_extension, 0)); - EXPECT_EQ("225", message.GetExtension(unittest::repeated_cord_extension, 0)); - - // Actually verify the second (modified) elements now. - EXPECT_EQ(501 , message.GetExtension(unittest::repeated_int32_extension , 1)); - EXPECT_EQ(502 , message.GetExtension(unittest::repeated_int64_extension , 1)); - EXPECT_EQ(503 , message.GetExtension(unittest::repeated_uint32_extension , 1)); - EXPECT_EQ(504 , message.GetExtension(unittest::repeated_uint64_extension , 1)); - EXPECT_EQ(505 , message.GetExtension(unittest::repeated_sint32_extension , 1)); - EXPECT_EQ(506 , message.GetExtension(unittest::repeated_sint64_extension , 1)); - EXPECT_EQ(507 , message.GetExtension(unittest::repeated_fixed32_extension , 1)); - EXPECT_EQ(508 , message.GetExtension(unittest::repeated_fixed64_extension , 1)); - EXPECT_EQ(509 , message.GetExtension(unittest::repeated_sfixed32_extension, 1)); - EXPECT_EQ(510 , message.GetExtension(unittest::repeated_sfixed64_extension, 1)); - EXPECT_EQ(511 , message.GetExtension(unittest::repeated_float_extension , 1)); - EXPECT_EQ(512 , message.GetExtension(unittest::repeated_double_extension , 1)); - EXPECT_TRUE( message.GetExtension(unittest::repeated_bool_extension , 1)); - EXPECT_EQ("515", message.GetExtension(unittest::repeated_string_extension , 1)); - EXPECT_EQ("516", message.GetExtension(unittest::repeated_bytes_extension , 1)); - - EXPECT_EQ(517, message.GetExtension(unittest::repeatedgroup_extension , 1).a()); - EXPECT_EQ(518, message.GetExtension(unittest::repeated_nested_message_extension , 1).bb()); - EXPECT_EQ(519, message.GetExtension(unittest::repeated_foreign_message_extension, 1).c()); - EXPECT_EQ(520, message.GetExtension(unittest::repeated_import_message_extension , 1).d()); - EXPECT_EQ(527, message.GetExtension(unittest::repeated_lazy_message_extension , 1).bb()); - - EXPECT_EQ(unittest::TestAllTypes::FOO, message.GetExtension(unittest::repeated_nested_enum_extension , 1)); - EXPECT_EQ(unittest::FOREIGN_FOO , message.GetExtension(unittest::repeated_foreign_enum_extension, 1)); - EXPECT_EQ(unittest_import::IMPORT_FOO, message.GetExtension(unittest::repeated_import_enum_extension , 1)); - - EXPECT_EQ("524", message.GetExtension(unittest::repeated_string_piece_extension, 1)); - EXPECT_EQ("525", message.GetExtension(unittest::repeated_cord_extension, 1)); -} - -// ------------------------------------------------------------------- - -void TestUtil::SetPackedExtensions(unittest::TestPackedExtensions* message) { - message->AddExtension(unittest::packed_int32_extension , 601); - message->AddExtension(unittest::packed_int64_extension , 602); - message->AddExtension(unittest::packed_uint32_extension , 603); - message->AddExtension(unittest::packed_uint64_extension , 604); - message->AddExtension(unittest::packed_sint32_extension , 605); - message->AddExtension(unittest::packed_sint64_extension , 606); - message->AddExtension(unittest::packed_fixed32_extension , 607); - message->AddExtension(unittest::packed_fixed64_extension , 608); - message->AddExtension(unittest::packed_sfixed32_extension, 609); - message->AddExtension(unittest::packed_sfixed64_extension, 610); - message->AddExtension(unittest::packed_float_extension , 611); - message->AddExtension(unittest::packed_double_extension , 612); - message->AddExtension(unittest::packed_bool_extension , true); - message->AddExtension(unittest::packed_enum_extension, unittest::FOREIGN_BAR); - // add a second one of each field - message->AddExtension(unittest::packed_int32_extension , 701); - message->AddExtension(unittest::packed_int64_extension , 702); - message->AddExtension(unittest::packed_uint32_extension , 703); - message->AddExtension(unittest::packed_uint64_extension , 704); - message->AddExtension(unittest::packed_sint32_extension , 705); - message->AddExtension(unittest::packed_sint64_extension , 706); - message->AddExtension(unittest::packed_fixed32_extension , 707); - message->AddExtension(unittest::packed_fixed64_extension , 708); - message->AddExtension(unittest::packed_sfixed32_extension, 709); - message->AddExtension(unittest::packed_sfixed64_extension, 710); - message->AddExtension(unittest::packed_float_extension , 711); - message->AddExtension(unittest::packed_double_extension , 712); - message->AddExtension(unittest::packed_bool_extension , false); - message->AddExtension(unittest::packed_enum_extension, unittest::FOREIGN_BAZ); -} - -// ------------------------------------------------------------------- - -void TestUtil::ModifyPackedExtensions(unittest::TestPackedExtensions* message) { - message->SetExtension(unittest::packed_int32_extension , 1, 801); - message->SetExtension(unittest::packed_int64_extension , 1, 802); - message->SetExtension(unittest::packed_uint32_extension , 1, 803); - message->SetExtension(unittest::packed_uint64_extension , 1, 804); - message->SetExtension(unittest::packed_sint32_extension , 1, 805); - message->SetExtension(unittest::packed_sint64_extension , 1, 806); - message->SetExtension(unittest::packed_fixed32_extension , 1, 807); - message->SetExtension(unittest::packed_fixed64_extension , 1, 808); - message->SetExtension(unittest::packed_sfixed32_extension, 1, 809); - message->SetExtension(unittest::packed_sfixed64_extension, 1, 810); - message->SetExtension(unittest::packed_float_extension , 1, 811); - message->SetExtension(unittest::packed_double_extension , 1, 812); - message->SetExtension(unittest::packed_bool_extension , 1, true); - message->SetExtension(unittest::packed_enum_extension , 1, - unittest::FOREIGN_FOO); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectPackedExtensionsSet( - const unittest::TestPackedExtensions& message) { - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed32_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed64_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_float_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_double_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_bool_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_enum_extension )); - - EXPECT_EQ(601 , message.GetExtension(unittest::packed_int32_extension , 0)); - EXPECT_EQ(602 , message.GetExtension(unittest::packed_int64_extension , 0)); - EXPECT_EQ(603 , message.GetExtension(unittest::packed_uint32_extension , 0)); - EXPECT_EQ(604 , message.GetExtension(unittest::packed_uint64_extension , 0)); - EXPECT_EQ(605 , message.GetExtension(unittest::packed_sint32_extension , 0)); - EXPECT_EQ(606 , message.GetExtension(unittest::packed_sint64_extension , 0)); - EXPECT_EQ(607 , message.GetExtension(unittest::packed_fixed32_extension , 0)); - EXPECT_EQ(608 , message.GetExtension(unittest::packed_fixed64_extension , 0)); - EXPECT_EQ(609 , message.GetExtension(unittest::packed_sfixed32_extension, 0)); - EXPECT_EQ(610 , message.GetExtension(unittest::packed_sfixed64_extension, 0)); - EXPECT_EQ(611 , message.GetExtension(unittest::packed_float_extension , 0)); - EXPECT_EQ(612 , message.GetExtension(unittest::packed_double_extension , 0)); - EXPECT_TRUE( message.GetExtension(unittest::packed_bool_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAR, - message.GetExtension(unittest::packed_enum_extension, 0)); - EXPECT_EQ(701 , message.GetExtension(unittest::packed_int32_extension , 1)); - EXPECT_EQ(702 , message.GetExtension(unittest::packed_int64_extension , 1)); - EXPECT_EQ(703 , message.GetExtension(unittest::packed_uint32_extension , 1)); - EXPECT_EQ(704 , message.GetExtension(unittest::packed_uint64_extension , 1)); - EXPECT_EQ(705 , message.GetExtension(unittest::packed_sint32_extension , 1)); - EXPECT_EQ(706 , message.GetExtension(unittest::packed_sint64_extension , 1)); - EXPECT_EQ(707 , message.GetExtension(unittest::packed_fixed32_extension , 1)); - EXPECT_EQ(708 , message.GetExtension(unittest::packed_fixed64_extension , 1)); - EXPECT_EQ(709 , message.GetExtension(unittest::packed_sfixed32_extension, 1)); - EXPECT_EQ(710 , message.GetExtension(unittest::packed_sfixed64_extension, 1)); - EXPECT_EQ(711 , message.GetExtension(unittest::packed_float_extension , 1)); - EXPECT_EQ(712 , message.GetExtension(unittest::packed_double_extension , 1)); - EXPECT_FALSE( message.GetExtension(unittest::packed_bool_extension , 1)); - EXPECT_EQ(unittest::FOREIGN_BAZ, - message.GetExtension(unittest::packed_enum_extension, 1)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectPackedExtensionsClear( - const unittest::TestPackedExtensions& message) { - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_int32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_int64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_uint32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_uint64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sint32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sint64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_fixed32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_fixed64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sfixed32_extension)); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sfixed64_extension)); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_float_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_double_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_bool_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_enum_extension )); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectPackedExtensionsModified( - const unittest::TestPackedExtensions& message) { - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed32_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed64_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_float_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_double_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_bool_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_enum_extension )); - EXPECT_EQ(601 , message.GetExtension(unittest::packed_int32_extension , 0)); - EXPECT_EQ(602 , message.GetExtension(unittest::packed_int64_extension , 0)); - EXPECT_EQ(603 , message.GetExtension(unittest::packed_uint32_extension , 0)); - EXPECT_EQ(604 , message.GetExtension(unittest::packed_uint64_extension , 0)); - EXPECT_EQ(605 , message.GetExtension(unittest::packed_sint32_extension , 0)); - EXPECT_EQ(606 , message.GetExtension(unittest::packed_sint64_extension , 0)); - EXPECT_EQ(607 , message.GetExtension(unittest::packed_fixed32_extension , 0)); - EXPECT_EQ(608 , message.GetExtension(unittest::packed_fixed64_extension , 0)); - EXPECT_EQ(609 , message.GetExtension(unittest::packed_sfixed32_extension, 0)); - EXPECT_EQ(610 , message.GetExtension(unittest::packed_sfixed64_extension, 0)); - EXPECT_EQ(611 , message.GetExtension(unittest::packed_float_extension , 0)); - EXPECT_EQ(612 , message.GetExtension(unittest::packed_double_extension , 0)); - EXPECT_TRUE( message.GetExtension(unittest::packed_bool_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAR, - message.GetExtension(unittest::packed_enum_extension, 0)); - - // Actually verify the second (modified) elements now. - EXPECT_EQ(801 , message.GetExtension(unittest::packed_int32_extension , 1)); - EXPECT_EQ(802 , message.GetExtension(unittest::packed_int64_extension , 1)); - EXPECT_EQ(803 , message.GetExtension(unittest::packed_uint32_extension , 1)); - EXPECT_EQ(804 , message.GetExtension(unittest::packed_uint64_extension , 1)); - EXPECT_EQ(805 , message.GetExtension(unittest::packed_sint32_extension , 1)); - EXPECT_EQ(806 , message.GetExtension(unittest::packed_sint64_extension , 1)); - EXPECT_EQ(807 , message.GetExtension(unittest::packed_fixed32_extension , 1)); - EXPECT_EQ(808 , message.GetExtension(unittest::packed_fixed64_extension , 1)); - EXPECT_EQ(809 , message.GetExtension(unittest::packed_sfixed32_extension, 1)); - EXPECT_EQ(810 , message.GetExtension(unittest::packed_sfixed64_extension, 1)); - EXPECT_EQ(811 , message.GetExtension(unittest::packed_float_extension , 1)); - EXPECT_EQ(812 , message.GetExtension(unittest::packed_double_extension , 1)); - EXPECT_TRUE( message.GetExtension(unittest::packed_bool_extension , 1)); - EXPECT_EQ(unittest::FOREIGN_FOO, - message.GetExtension(unittest::packed_enum_extension, 1)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectUnpackedExtensionsSet( - const unittest::TestUnpackedExtensions& message) { - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_int32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_int64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_uint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_uint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_sint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_sint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_fixed32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_fixed64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_sfixed32_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_sfixed64_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_float_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_double_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_bool_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_enum_extension )); - - EXPECT_EQ(601 , message.GetExtension(unittest::unpacked_int32_extension , 0)); - EXPECT_EQ(602 , message.GetExtension(unittest::unpacked_int64_extension , 0)); - EXPECT_EQ(603 , message.GetExtension(unittest::unpacked_uint32_extension , 0)); - EXPECT_EQ(604 , message.GetExtension(unittest::unpacked_uint64_extension , 0)); - EXPECT_EQ(605 , message.GetExtension(unittest::unpacked_sint32_extension , 0)); - EXPECT_EQ(606 , message.GetExtension(unittest::unpacked_sint64_extension , 0)); - EXPECT_EQ(607 , message.GetExtension(unittest::unpacked_fixed32_extension , 0)); - EXPECT_EQ(608 , message.GetExtension(unittest::unpacked_fixed64_extension , 0)); - EXPECT_EQ(609 , message.GetExtension(unittest::unpacked_sfixed32_extension, 0)); - EXPECT_EQ(610 , message.GetExtension(unittest::unpacked_sfixed64_extension, 0)); - EXPECT_EQ(611 , message.GetExtension(unittest::unpacked_float_extension , 0)); - EXPECT_EQ(612 , message.GetExtension(unittest::unpacked_double_extension , 0)); - EXPECT_EQ(true , message.GetExtension(unittest::unpacked_bool_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAR, - message.GetExtension(unittest::unpacked_enum_extension, 0)); - EXPECT_EQ(701 , message.GetExtension(unittest::unpacked_int32_extension , 1)); - EXPECT_EQ(702 , message.GetExtension(unittest::unpacked_int64_extension , 1)); - EXPECT_EQ(703 , message.GetExtension(unittest::unpacked_uint32_extension , 1)); - EXPECT_EQ(704 , message.GetExtension(unittest::unpacked_uint64_extension , 1)); - EXPECT_EQ(705 , message.GetExtension(unittest::unpacked_sint32_extension , 1)); - EXPECT_EQ(706 , message.GetExtension(unittest::unpacked_sint64_extension , 1)); - EXPECT_EQ(707 , message.GetExtension(unittest::unpacked_fixed32_extension , 1)); - EXPECT_EQ(708 , message.GetExtension(unittest::unpacked_fixed64_extension , 1)); - EXPECT_EQ(709 , message.GetExtension(unittest::unpacked_sfixed32_extension, 1)); - EXPECT_EQ(710 , message.GetExtension(unittest::unpacked_sfixed64_extension, 1)); - EXPECT_EQ(711 , message.GetExtension(unittest::unpacked_float_extension , 1)); - EXPECT_EQ(712 , message.GetExtension(unittest::unpacked_double_extension , 1)); - EXPECT_EQ(false, message.GetExtension(unittest::unpacked_bool_extension , 1)); - EXPECT_EQ(unittest::FOREIGN_BAZ, - message.GetExtension(unittest::unpacked_enum_extension, 1)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectAllFieldsAndExtensionsInOrder(const string& serialized) { - // We set each field individually, serialize separately, and concatenate all - // the strings in canonical order to determine the expected serialization. - string expected; - unittest::TestFieldOrderings message; - message.set_my_int(1); // Field 1. - message.AppendToString(&expected); - message.Clear(); - message.SetExtension(unittest::my_extension_int, 23); // Field 5. - message.AppendToString(&expected); - message.Clear(); - message.set_my_string("foo"); // Field 11. - message.AppendToString(&expected); - message.Clear(); - message.SetExtension(unittest::my_extension_string, "bar"); // Field 50. - message.AppendToString(&expected); - message.Clear(); - message.set_my_float(1.0); // Field 101. - message.AppendToString(&expected); - message.Clear(); - - // We don't EXPECT_EQ() since we don't want to print raw bytes to stdout. - EXPECT_TRUE(serialized == expected); -} - -void TestUtil::ExpectLastRepeatedsRemoved( - const unittest::TestAllTypes& message) { - ASSERT_EQ(1, message.repeated_int32_size ()); - ASSERT_EQ(1, message.repeated_int64_size ()); - ASSERT_EQ(1, message.repeated_uint32_size ()); - ASSERT_EQ(1, message.repeated_uint64_size ()); - ASSERT_EQ(1, message.repeated_sint32_size ()); - ASSERT_EQ(1, message.repeated_sint64_size ()); - ASSERT_EQ(1, message.repeated_fixed32_size ()); - ASSERT_EQ(1, message.repeated_fixed64_size ()); - ASSERT_EQ(1, message.repeated_sfixed32_size()); - ASSERT_EQ(1, message.repeated_sfixed64_size()); - ASSERT_EQ(1, message.repeated_float_size ()); - ASSERT_EQ(1, message.repeated_double_size ()); - ASSERT_EQ(1, message.repeated_bool_size ()); - ASSERT_EQ(1, message.repeated_string_size ()); - ASSERT_EQ(1, message.repeated_bytes_size ()); - - ASSERT_EQ(1, message.repeatedgroup_size ()); - ASSERT_EQ(1, message.repeated_nested_message_size ()); - ASSERT_EQ(1, message.repeated_foreign_message_size()); - ASSERT_EQ(1, message.repeated_import_message_size ()); - ASSERT_EQ(1, message.repeated_import_message_size ()); - ASSERT_EQ(1, message.repeated_nested_enum_size ()); - ASSERT_EQ(1, message.repeated_foreign_enum_size ()); - ASSERT_EQ(1, message.repeated_import_enum_size ()); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - ASSERT_EQ(1, message.repeated_string_piece_size()); - ASSERT_EQ(1, message.repeated_cord_size()); -#endif - - // Test that the remaining element is the correct one. - EXPECT_EQ(201 , message.repeated_int32 (0)); - EXPECT_EQ(202 , message.repeated_int64 (0)); - EXPECT_EQ(203 , message.repeated_uint32 (0)); - EXPECT_EQ(204 , message.repeated_uint64 (0)); - EXPECT_EQ(205 , message.repeated_sint32 (0)); - EXPECT_EQ(206 , message.repeated_sint64 (0)); - EXPECT_EQ(207 , message.repeated_fixed32 (0)); - EXPECT_EQ(208 , message.repeated_fixed64 (0)); - EXPECT_EQ(209 , message.repeated_sfixed32(0)); - EXPECT_EQ(210 , message.repeated_sfixed64(0)); - EXPECT_EQ(211 , message.repeated_float (0)); - EXPECT_EQ(212 , message.repeated_double (0)); - EXPECT_TRUE( message.repeated_bool (0)); - EXPECT_EQ("215", message.repeated_string (0)); - EXPECT_EQ("216", message.repeated_bytes (0)); - - EXPECT_EQ(217, message.repeatedgroup (0).a()); - EXPECT_EQ(218, message.repeated_nested_message (0).bb()); - EXPECT_EQ(219, message.repeated_foreign_message(0).c()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.repeated_nested_enum (0)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.repeated_foreign_enum(0)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.repeated_import_enum (0)); -} - -void TestUtil::ExpectLastRepeatedExtensionsRemoved( - const unittest::TestAllExtensions& message) { - - // Test that one element was removed. - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_int32_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_int64_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_uint32_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_uint64_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_sint32_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_sint64_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_fixed32_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_fixed64_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_sfixed32_extension)); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_sfixed64_extension)); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_float_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_double_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_bool_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_string_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_bytes_extension )); - - ASSERT_EQ(1, message.ExtensionSize(unittest::repeatedgroup_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_nested_message_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_foreign_message_extension)); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_import_message_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_lazy_message_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_nested_enum_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_foreign_enum_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_import_enum_extension )); - - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_string_piece_extension)); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_cord_extension)); - - // Test that the remaining element is the correct one. - EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension , 0)); - EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension , 0)); - EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension , 0)); - EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension , 0)); - EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension , 0)); - EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension , 0)); - EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension , 0)); - EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension , 0)); - EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension, 0)); - EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension, 0)); - EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension , 0)); - EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension , 0)); - EXPECT_TRUE( message.GetExtension(unittest::repeated_bool_extension , 0)); - EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension , 0)); - EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension , 0)); - - EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 0).a()); - EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb()); - EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c()); - EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 0).d()); - EXPECT_EQ(227, message.GetExtension(unittest::repeated_lazy_message_extension , 0).bb()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::repeated_nested_enum_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension, 0)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::repeated_import_enum_extension , 0)); - - EXPECT_EQ("224", message.GetExtension(unittest::repeated_string_piece_extension, 0)); - EXPECT_EQ("225", message.GetExtension(unittest::repeated_cord_extension, 0)); -} - -void TestUtil::ExpectLastRepeatedsReleased( - const unittest::TestAllTypes& message) { - ASSERT_EQ(1, message.repeatedgroup_size ()); - ASSERT_EQ(1, message.repeated_nested_message_size ()); - ASSERT_EQ(1, message.repeated_foreign_message_size()); - ASSERT_EQ(1, message.repeated_import_message_size ()); - ASSERT_EQ(1, message.repeated_import_message_size ()); - - EXPECT_EQ(217, message.repeatedgroup (0).a()); - EXPECT_EQ(218, message.repeated_nested_message (0).bb()); - EXPECT_EQ(219, message.repeated_foreign_message(0).c()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); -} - -void TestUtil::ExpectLastRepeatedExtensionsReleased( - const unittest::TestAllExtensions& message) { - ASSERT_EQ(1, message.ExtensionSize(unittest::repeatedgroup_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_nested_message_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_foreign_message_extension)); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_import_message_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_lazy_message_extension )); - - EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 0).a()); - EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb()); - EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c()); - EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 0).d()); - EXPECT_EQ(227, message.GetExtension(unittest::repeated_lazy_message_extension , 0).bb()); -} - -void TestUtil::ExpectRepeatedsSwapped( - const unittest::TestAllTypes& message) { - ASSERT_EQ(2, message.repeated_int32_size ()); - ASSERT_EQ(2, message.repeated_int64_size ()); - ASSERT_EQ(2, message.repeated_uint32_size ()); - ASSERT_EQ(2, message.repeated_uint64_size ()); - ASSERT_EQ(2, message.repeated_sint32_size ()); - ASSERT_EQ(2, message.repeated_sint64_size ()); - ASSERT_EQ(2, message.repeated_fixed32_size ()); - ASSERT_EQ(2, message.repeated_fixed64_size ()); - ASSERT_EQ(2, message.repeated_sfixed32_size()); - ASSERT_EQ(2, message.repeated_sfixed64_size()); - ASSERT_EQ(2, message.repeated_float_size ()); - ASSERT_EQ(2, message.repeated_double_size ()); - ASSERT_EQ(2, message.repeated_bool_size ()); - ASSERT_EQ(2, message.repeated_string_size ()); - ASSERT_EQ(2, message.repeated_bytes_size ()); - - ASSERT_EQ(2, message.repeatedgroup_size ()); - ASSERT_EQ(2, message.repeated_nested_message_size ()); - ASSERT_EQ(2, message.repeated_foreign_message_size()); - ASSERT_EQ(2, message.repeated_import_message_size ()); - ASSERT_EQ(2, message.repeated_import_message_size ()); - ASSERT_EQ(2, message.repeated_nested_enum_size ()); - ASSERT_EQ(2, message.repeated_foreign_enum_size ()); - ASSERT_EQ(2, message.repeated_import_enum_size ()); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - ASSERT_EQ(2, message.repeated_string_piece_size()); - ASSERT_EQ(2, message.repeated_cord_size()); -#endif - - // Test that the first element and second element are flipped. - EXPECT_EQ(201 , message.repeated_int32 (1)); - EXPECT_EQ(202 , message.repeated_int64 (1)); - EXPECT_EQ(203 , message.repeated_uint32 (1)); - EXPECT_EQ(204 , message.repeated_uint64 (1)); - EXPECT_EQ(205 , message.repeated_sint32 (1)); - EXPECT_EQ(206 , message.repeated_sint64 (1)); - EXPECT_EQ(207 , message.repeated_fixed32 (1)); - EXPECT_EQ(208 , message.repeated_fixed64 (1)); - EXPECT_EQ(209 , message.repeated_sfixed32(1)); - EXPECT_EQ(210 , message.repeated_sfixed64(1)); - EXPECT_EQ(211 , message.repeated_float (1)); - EXPECT_EQ(212 , message.repeated_double (1)); - EXPECT_TRUE( message.repeated_bool (1)); - EXPECT_EQ("215", message.repeated_string (1)); - EXPECT_EQ("216", message.repeated_bytes (1)); - - EXPECT_EQ(217, message.repeatedgroup (1).a()); - EXPECT_EQ(218, message.repeated_nested_message (1).bb()); - EXPECT_EQ(219, message.repeated_foreign_message(1).c()); - EXPECT_EQ(220, message.repeated_import_message (1).d()); - EXPECT_EQ(220, message.repeated_import_message (1).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.repeated_nested_enum (1)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.repeated_foreign_enum(1)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.repeated_import_enum (1)); - - EXPECT_EQ(301 , message.repeated_int32 (0)); - EXPECT_EQ(302 , message.repeated_int64 (0)); - EXPECT_EQ(303 , message.repeated_uint32 (0)); - EXPECT_EQ(304 , message.repeated_uint64 (0)); - EXPECT_EQ(305 , message.repeated_sint32 (0)); - EXPECT_EQ(306 , message.repeated_sint64 (0)); - EXPECT_EQ(307 , message.repeated_fixed32 (0)); - EXPECT_EQ(308 , message.repeated_fixed64 (0)); - EXPECT_EQ(309 , message.repeated_sfixed32(0)); - EXPECT_EQ(310 , message.repeated_sfixed64(0)); - EXPECT_EQ(311 , message.repeated_float (0)); - EXPECT_EQ(312 , message.repeated_double (0)); - EXPECT_FALSE( message.repeated_bool (0)); - EXPECT_EQ("315", message.repeated_string (0)); - EXPECT_EQ("316", message.repeated_bytes (0)); - - EXPECT_EQ(317, message.repeatedgroup (0).a()); - EXPECT_EQ(318, message.repeated_nested_message (0).bb()); - EXPECT_EQ(319, message.repeated_foreign_message(0).c()); - EXPECT_EQ(320, message.repeated_import_message (0).d()); - EXPECT_EQ(320, message.repeated_import_message (0).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAZ, message.repeated_nested_enum (0)); - EXPECT_EQ(unittest::FOREIGN_BAZ , message.repeated_foreign_enum(0)); - EXPECT_EQ(unittest_import::IMPORT_BAZ, message.repeated_import_enum (0)); -} - -void TestUtil::ExpectRepeatedExtensionsSwapped( - const unittest::TestAllExtensions& message) { - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed32_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed64_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_float_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_double_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bool_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bytes_extension )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeatedgroup_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_message_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_lazy_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_enum_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_enum_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_enum_extension )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_piece_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_cord_extension)); - - EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension , 1)); - EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension , 1)); - EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension , 1)); - EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension , 1)); - EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension , 1)); - EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension , 1)); - EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension , 1)); - EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension , 1)); - EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension, 1)); - EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension, 1)); - EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension , 1)); - EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension , 1)); - EXPECT_TRUE( message.GetExtension(unittest::repeated_bool_extension , 1)); - EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension , 1)); - EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension , 1)); - - EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 1).a()); - EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 1).bb()); - EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 1).c()); - EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 1).d()); - EXPECT_EQ(227, message.GetExtension(unittest::repeated_lazy_message_extension , 1).bb()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::repeated_nested_enum_extension , 1)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension, 1)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::repeated_import_enum_extension , 1)); - - EXPECT_EQ("224", message.GetExtension(unittest::repeated_string_piece_extension, 1)); - EXPECT_EQ("225", message.GetExtension(unittest::repeated_cord_extension, 1)); - - EXPECT_EQ(301 , message.GetExtension(unittest::repeated_int32_extension , 0)); - EXPECT_EQ(302 , message.GetExtension(unittest::repeated_int64_extension , 0)); - EXPECT_EQ(303 , message.GetExtension(unittest::repeated_uint32_extension , 0)); - EXPECT_EQ(304 , message.GetExtension(unittest::repeated_uint64_extension , 0)); - EXPECT_EQ(305 , message.GetExtension(unittest::repeated_sint32_extension , 0)); - EXPECT_EQ(306 , message.GetExtension(unittest::repeated_sint64_extension , 0)); - EXPECT_EQ(307 , message.GetExtension(unittest::repeated_fixed32_extension , 0)); - EXPECT_EQ(308 , message.GetExtension(unittest::repeated_fixed64_extension , 0)); - EXPECT_EQ(309 , message.GetExtension(unittest::repeated_sfixed32_extension, 0)); - EXPECT_EQ(310 , message.GetExtension(unittest::repeated_sfixed64_extension, 0)); - EXPECT_EQ(311 , message.GetExtension(unittest::repeated_float_extension , 0)); - EXPECT_EQ(312 , message.GetExtension(unittest::repeated_double_extension , 0)); - EXPECT_FALSE( message.GetExtension(unittest::repeated_bool_extension , 0)); - EXPECT_EQ("315", message.GetExtension(unittest::repeated_string_extension , 0)); - EXPECT_EQ("316", message.GetExtension(unittest::repeated_bytes_extension , 0)); - - EXPECT_EQ(317, message.GetExtension(unittest::repeatedgroup_extension , 0).a()); - EXPECT_EQ(318, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb()); - EXPECT_EQ(319, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c()); - EXPECT_EQ(320, message.GetExtension(unittest::repeated_import_message_extension , 0).d()); - EXPECT_EQ(327, message.GetExtension(unittest::repeated_lazy_message_extension , 0).bb()); - - EXPECT_EQ(unittest::TestAllTypes::BAZ, message.GetExtension(unittest::repeated_nested_enum_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAZ , message.GetExtension(unittest::repeated_foreign_enum_extension, 0)); - EXPECT_EQ(unittest_import::IMPORT_BAZ, message.GetExtension(unittest::repeated_import_enum_extension , 0)); - - EXPECT_EQ("324", message.GetExtension(unittest::repeated_string_piece_extension, 0)); - EXPECT_EQ("325", message.GetExtension(unittest::repeated_cord_extension, 0)); -} - -void TestUtil::SetOneof1(unittest::TestOneof2* message) { - message->mutable_foo_lazy_message()->set_qux_int(100); - message->set_bar_string("101"); - message->set_baz_int(102); - message->set_baz_string("103"); -} - -void TestUtil::SetOneof2(unittest::TestOneof2* message) { - message->set_foo_int(200); - message->set_bar_enum(unittest::TestOneof2::BAZ); - message->set_baz_int(202); - message->set_baz_string("203"); -} - -void TestUtil::ExpectOneofSet1(const unittest::TestOneof2& message) { - ExpectAtMostOneFieldSetInOneof(message); - - EXPECT_TRUE(message.has_foo_lazy_message ()); - EXPECT_TRUE(message.foo_lazy_message().has_qux_int()); - - EXPECT_TRUE(message.has_bar_string()); - EXPECT_TRUE(message.has_baz_int ()); - EXPECT_TRUE(message.has_baz_string()); - - ASSERT_EQ(0, message.foo_lazy_message().corge_int_size()); - - EXPECT_EQ(100 , message.foo_lazy_message().qux_int()); - EXPECT_EQ("101", message.bar_string ()); - EXPECT_EQ(102 , message.baz_int ()); - EXPECT_EQ("103", message.baz_string ()); -} - -void TestUtil::ExpectOneofSet2(const unittest::TestOneof2& message) { - ExpectAtMostOneFieldSetInOneof(message); - - EXPECT_TRUE(message.has_foo_int ()); - EXPECT_TRUE(message.has_bar_enum ()); - EXPECT_TRUE(message.has_baz_int ()); - EXPECT_TRUE(message.has_baz_string()); - - EXPECT_EQ(200 , message.foo_int ()); - EXPECT_EQ(unittest::TestOneof2::BAZ, message.bar_enum ()); - EXPECT_EQ(202 , message.baz_int ()); - EXPECT_EQ("203" , message.baz_string()); -} - -void TestUtil::ExpectOneofClear(const unittest::TestOneof2& message) { - EXPECT_FALSE(message.has_foo_int()); - EXPECT_FALSE(message.has_foo_string()); - EXPECT_FALSE(message.has_foo_bytes()); - EXPECT_FALSE(message.has_foo_enum()); - EXPECT_FALSE(message.has_foo_message()); - EXPECT_FALSE(message.has_foogroup()); - EXPECT_FALSE(message.has_foo_lazy_message()); - - EXPECT_FALSE(message.has_bar_int()); - EXPECT_FALSE(message.has_bar_string()); - EXPECT_FALSE(message.has_bar_bytes()); - EXPECT_FALSE(message.has_bar_enum()); - - EXPECT_FALSE(message.has_baz_int()); - EXPECT_FALSE(message.has_baz_string()); - - EXPECT_EQ(unittest::TestOneof2::FOO_NOT_SET, message.foo_case()); - EXPECT_EQ(unittest::TestOneof2::BAR_NOT_SET, message.bar_case()); -} - -void TestUtil::ExpectAtMostOneFieldSetInOneof( - const unittest::TestOneof2& message) { - int count = 0; - if (message.has_foo_int()) count++; - if (message.has_foo_string()) count++; - if (message.has_foo_bytes()) count++; - if (message.has_foo_enum()) count++; - if (message.has_foo_message()) count++; - if (message.has_foogroup()) count++; - if (message.has_foo_lazy_message()) count++; - EXPECT_LE(count, 1); - count = 0; - if (message.has_bar_int()) count++; - if (message.has_bar_string()) count++; - if (message.has_bar_bytes()) count++; - if (message.has_bar_enum()) count++; - EXPECT_TRUE(count == 0 || count == 1); -} - -// =================================================================== - -TestUtil::ReflectionTester::ReflectionTester( - const Descriptor* base_descriptor) - : base_descriptor_(base_descriptor) { - - const DescriptorPool* pool = base_descriptor->file()->pool(); - - nested_b_ = - pool->FindFieldByName("protobuf_unittest.TestAllTypes.NestedMessage.bb"); - foreign_c_ = - pool->FindFieldByName("protobuf_unittest.ForeignMessage.c"); - import_d_ = - pool->FindFieldByName("protobuf_unittest_import.ImportMessage.d"); - import_e_ = - pool->FindFieldByName("protobuf_unittest_import.PublicImportMessage.e"); - nested_foo_ = - pool->FindEnumValueByName("protobuf_unittest.TestAllTypes.FOO"); - nested_bar_ = - pool->FindEnumValueByName("protobuf_unittest.TestAllTypes.BAR"); - nested_baz_ = - pool->FindEnumValueByName("protobuf_unittest.TestAllTypes.BAZ"); - foreign_foo_ = - pool->FindEnumValueByName("protobuf_unittest.FOREIGN_FOO"); - foreign_bar_ = - pool->FindEnumValueByName("protobuf_unittest.FOREIGN_BAR"); - foreign_baz_ = - pool->FindEnumValueByName("protobuf_unittest.FOREIGN_BAZ"); - import_foo_ = - pool->FindEnumValueByName("protobuf_unittest_import.IMPORT_FOO"); - import_bar_ = - pool->FindEnumValueByName("protobuf_unittest_import.IMPORT_BAR"); - import_baz_ = - pool->FindEnumValueByName("protobuf_unittest_import.IMPORT_BAZ"); - - if (base_descriptor_->name() == "TestAllExtensions") { - group_a_ = - pool->FindFieldByName("protobuf_unittest.OptionalGroup_extension.a"); - repeated_group_a_ = - pool->FindFieldByName("protobuf_unittest.RepeatedGroup_extension.a"); - } else { - group_a_ = - pool->FindFieldByName("protobuf_unittest.TestAllTypes.OptionalGroup.a"); - repeated_group_a_ = - pool->FindFieldByName("protobuf_unittest.TestAllTypes.RepeatedGroup.a"); - } - - EXPECT_TRUE(group_a_ != NULL); - EXPECT_TRUE(repeated_group_a_ != NULL); - EXPECT_TRUE(nested_b_ != NULL); - EXPECT_TRUE(foreign_c_ != NULL); - EXPECT_TRUE(import_d_ != NULL); - EXPECT_TRUE(import_e_ != NULL); - EXPECT_TRUE(nested_foo_ != NULL); - EXPECT_TRUE(nested_bar_ != NULL); - EXPECT_TRUE(nested_baz_ != NULL); - EXPECT_TRUE(foreign_foo_ != NULL); - EXPECT_TRUE(foreign_bar_ != NULL); - EXPECT_TRUE(foreign_baz_ != NULL); - EXPECT_TRUE(import_foo_ != NULL); - EXPECT_TRUE(import_bar_ != NULL); - EXPECT_TRUE(import_baz_ != NULL); -} - -// Shorthand to get a FieldDescriptor for a field of unittest::TestAllTypes. -const FieldDescriptor* TestUtil::ReflectionTester::F(const string& name) { - const FieldDescriptor* result = NULL; - if (base_descriptor_->name() == "TestAllExtensions" || - base_descriptor_->name() == "TestPackedExtensions") { - result = base_descriptor_->file()->FindExtensionByName(name + "_extension"); - } else { - result = base_descriptor_->FindFieldByName(name); - } - GOOGLE_CHECK(result != NULL); - return result; -} - -// ------------------------------------------------------------------- - -void TestUtil::ReflectionTester::SetAllFieldsViaReflection(Message* message) { - const Reflection* reflection = message->GetReflection(); - Message* sub_message; - - reflection->SetInt32 (message, F("optional_int32" ), 101); - reflection->SetInt64 (message, F("optional_int64" ), 102); - reflection->SetUInt32(message, F("optional_uint32" ), 103); - reflection->SetUInt64(message, F("optional_uint64" ), 104); - reflection->SetInt32 (message, F("optional_sint32" ), 105); - reflection->SetInt64 (message, F("optional_sint64" ), 106); - reflection->SetUInt32(message, F("optional_fixed32" ), 107); - reflection->SetUInt64(message, F("optional_fixed64" ), 108); - reflection->SetInt32 (message, F("optional_sfixed32"), 109); - reflection->SetInt64 (message, F("optional_sfixed64"), 110); - reflection->SetFloat (message, F("optional_float" ), 111); - reflection->SetDouble(message, F("optional_double" ), 112); - reflection->SetBool (message, F("optional_bool" ), true); - reflection->SetString(message, F("optional_string" ), "115"); - reflection->SetString(message, F("optional_bytes" ), "116"); - - sub_message = reflection->MutableMessage(message, F("optionalgroup")); - sub_message->GetReflection()->SetInt32(sub_message, group_a_, 117); - sub_message = reflection->MutableMessage(message, F("optional_nested_message")); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 118); - sub_message = reflection->MutableMessage(message, F("optional_foreign_message")); - sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 119); - sub_message = reflection->MutableMessage(message, F("optional_import_message")); - sub_message->GetReflection()->SetInt32(sub_message, import_d_, 120); - - reflection->SetEnum(message, F("optional_nested_enum" ), nested_baz_); - reflection->SetEnum(message, F("optional_foreign_enum"), foreign_baz_); - reflection->SetEnum(message, F("optional_import_enum" ), import_baz_); - - reflection->SetString(message, F("optional_string_piece"), "124"); - reflection->SetString(message, F("optional_cord"), "125"); - - sub_message = reflection->MutableMessage(message, F("optional_public_import_message")); - sub_message->GetReflection()->SetInt32(sub_message, import_e_, 126); - - sub_message = reflection->MutableMessage(message, F("optional_lazy_message")); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 127); - - // ----------------------------------------------------------------- - - reflection->AddInt32 (message, F("repeated_int32" ), 201); - reflection->AddInt64 (message, F("repeated_int64" ), 202); - reflection->AddUInt32(message, F("repeated_uint32" ), 203); - reflection->AddUInt64(message, F("repeated_uint64" ), 204); - reflection->AddInt32 (message, F("repeated_sint32" ), 205); - reflection->AddInt64 (message, F("repeated_sint64" ), 206); - reflection->AddUInt32(message, F("repeated_fixed32" ), 207); - reflection->AddUInt64(message, F("repeated_fixed64" ), 208); - reflection->AddInt32 (message, F("repeated_sfixed32"), 209); - reflection->AddInt64 (message, F("repeated_sfixed64"), 210); - reflection->AddFloat (message, F("repeated_float" ), 211); - reflection->AddDouble(message, F("repeated_double" ), 212); - reflection->AddBool (message, F("repeated_bool" ), true); - reflection->AddString(message, F("repeated_string" ), "215"); - reflection->AddString(message, F("repeated_bytes" ), "216"); - - sub_message = reflection->AddMessage(message, F("repeatedgroup")); - sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 217); - sub_message = reflection->AddMessage(message, F("repeated_nested_message")); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 218); - sub_message = reflection->AddMessage(message, F("repeated_foreign_message")); - sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 219); - sub_message = reflection->AddMessage(message, F("repeated_import_message")); - sub_message->GetReflection()->SetInt32(sub_message, import_d_, 220); - sub_message = reflection->AddMessage(message, F("repeated_lazy_message")); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 227); - - reflection->AddEnum(message, F("repeated_nested_enum" ), nested_bar_); - reflection->AddEnum(message, F("repeated_foreign_enum"), foreign_bar_); - reflection->AddEnum(message, F("repeated_import_enum" ), import_bar_); - - reflection->AddString(message, F("repeated_string_piece"), "224"); - reflection->AddString(message, F("repeated_cord"), "225"); - - // Add a second one of each field. - reflection->AddInt32 (message, F("repeated_int32" ), 301); - reflection->AddInt64 (message, F("repeated_int64" ), 302); - reflection->AddUInt32(message, F("repeated_uint32" ), 303); - reflection->AddUInt64(message, F("repeated_uint64" ), 304); - reflection->AddInt32 (message, F("repeated_sint32" ), 305); - reflection->AddInt64 (message, F("repeated_sint64" ), 306); - reflection->AddUInt32(message, F("repeated_fixed32" ), 307); - reflection->AddUInt64(message, F("repeated_fixed64" ), 308); - reflection->AddInt32 (message, F("repeated_sfixed32"), 309); - reflection->AddInt64 (message, F("repeated_sfixed64"), 310); - reflection->AddFloat (message, F("repeated_float" ), 311); - reflection->AddDouble(message, F("repeated_double" ), 312); - reflection->AddBool (message, F("repeated_bool" ), false); - reflection->AddString(message, F("repeated_string" ), "315"); - reflection->AddString(message, F("repeated_bytes" ), "316"); - - sub_message = reflection->AddMessage(message, F("repeatedgroup")); - sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 317); - sub_message = reflection->AddMessage(message, F("repeated_nested_message")); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 318); - sub_message = reflection->AddMessage(message, F("repeated_foreign_message")); - sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 319); - sub_message = reflection->AddMessage(message, F("repeated_import_message")); - sub_message->GetReflection()->SetInt32(sub_message, import_d_, 320); - sub_message = reflection->AddMessage(message, F("repeated_lazy_message")); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 327); - - reflection->AddEnum(message, F("repeated_nested_enum" ), nested_baz_); - reflection->AddEnum(message, F("repeated_foreign_enum"), foreign_baz_); - reflection->AddEnum(message, F("repeated_import_enum" ), import_baz_); - - reflection->AddString(message, F("repeated_string_piece"), "324"); - reflection->AddString(message, F("repeated_cord"), "325"); - - // ----------------------------------------------------------------- - - reflection->SetInt32 (message, F("default_int32" ), 401); - reflection->SetInt64 (message, F("default_int64" ), 402); - reflection->SetUInt32(message, F("default_uint32" ), 403); - reflection->SetUInt64(message, F("default_uint64" ), 404); - reflection->SetInt32 (message, F("default_sint32" ), 405); - reflection->SetInt64 (message, F("default_sint64" ), 406); - reflection->SetUInt32(message, F("default_fixed32" ), 407); - reflection->SetUInt64(message, F("default_fixed64" ), 408); - reflection->SetInt32 (message, F("default_sfixed32"), 409); - reflection->SetInt64 (message, F("default_sfixed64"), 410); - reflection->SetFloat (message, F("default_float" ), 411); - reflection->SetDouble(message, F("default_double" ), 412); - reflection->SetBool (message, F("default_bool" ), false); - reflection->SetString(message, F("default_string" ), "415"); - reflection->SetString(message, F("default_bytes" ), "416"); - - reflection->SetEnum(message, F("default_nested_enum" ), nested_foo_); - reflection->SetEnum(message, F("default_foreign_enum"), foreign_foo_); - reflection->SetEnum(message, F("default_import_enum" ), import_foo_); - - reflection->SetString(message, F("default_string_piece"), "424"); - reflection->SetString(message, F("default_cord"), "425"); - - reflection->SetUInt32(message, F("oneof_uint32" ), 601); - sub_message = reflection->MutableMessage(message, F("oneof_nested_message")); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 602); - reflection->SetString(message, F("oneof_string"), "603"); - reflection->SetString(message, F("oneof_bytes" ), "604"); -} - -void TestUtil::ReflectionTester::SetOneofViaReflection(Message* message) { - const Descriptor* descriptor = message->GetDescriptor(); - const Reflection* reflection = message->GetReflection(); - Message* sub_message = reflection->MutableMessage( - message, descriptor->FindFieldByName("foo_lazy_message")); - sub_message->GetReflection()->SetInt64( - sub_message, - descriptor->file()->pool()->FindFieldByName( - "protobuf_unittest.TestOneof2.NestedMessage.qux_int"), - 100); - - reflection->SetString(message, - descriptor->FindFieldByName("bar_cord"), - "101"); - reflection->SetInt32(message, - descriptor->FindFieldByName("baz_int"), - 102); - reflection->SetString(message, - descriptor->FindFieldByName("baz_string"), - "103"); -} - -void TestUtil::ReflectionTester::ExpectOneofSetViaReflection( - const Message& message) { - const Descriptor* descriptor = message.GetDescriptor(); - const Reflection* reflection = message.GetReflection(); - string scratch; - EXPECT_TRUE(reflection->HasField( - message, descriptor->FindFieldByName("foo_lazy_message"))); - EXPECT_TRUE(reflection->HasField( - message, descriptor->FindFieldByName("bar_cord"))); - EXPECT_TRUE(reflection->HasField( - message, descriptor->FindFieldByName("baz_int"))); - EXPECT_TRUE(reflection->HasField( - message, descriptor->FindFieldByName("baz_string"))); - - const Message* sub_message = &reflection->GetMessage( - message, descriptor->FindFieldByName("foo_lazy_message")); - EXPECT_EQ(100, sub_message->GetReflection()->GetInt64( - *sub_message, - descriptor->file()->pool()->FindFieldByName( - "protobuf_unittest.TestOneof2.NestedMessage.qux_int"))); - - EXPECT_EQ("101", reflection->GetString( - message, descriptor->FindFieldByName("bar_cord"))); - EXPECT_EQ("101", reflection->GetStringReference( - message, descriptor->FindFieldByName("bar_cord"), &scratch)); - - EXPECT_EQ(102, reflection->GetInt32( - message, descriptor->FindFieldByName("baz_int"))); - - EXPECT_EQ("103", reflection->GetString( - message, descriptor->FindFieldByName("baz_string"))); - EXPECT_EQ("103", reflection->GetStringReference( - message, descriptor->FindFieldByName("baz_string"), &scratch)); -} - -void TestUtil::ReflectionTester::SetPackedFieldsViaReflection( - Message* message) { - const Reflection* reflection = message->GetReflection(); - reflection->AddInt32 (message, F("packed_int32" ), 601); - reflection->AddInt64 (message, F("packed_int64" ), 602); - reflection->AddUInt32(message, F("packed_uint32" ), 603); - reflection->AddUInt64(message, F("packed_uint64" ), 604); - reflection->AddInt32 (message, F("packed_sint32" ), 605); - reflection->AddInt64 (message, F("packed_sint64" ), 606); - reflection->AddUInt32(message, F("packed_fixed32" ), 607); - reflection->AddUInt64(message, F("packed_fixed64" ), 608); - reflection->AddInt32 (message, F("packed_sfixed32"), 609); - reflection->AddInt64 (message, F("packed_sfixed64"), 610); - reflection->AddFloat (message, F("packed_float" ), 611); - reflection->AddDouble(message, F("packed_double" ), 612); - reflection->AddBool (message, F("packed_bool" ), true); - reflection->AddEnum (message, F("packed_enum" ), foreign_bar_); - - reflection->AddInt32 (message, F("packed_int32" ), 701); - reflection->AddInt64 (message, F("packed_int64" ), 702); - reflection->AddUInt32(message, F("packed_uint32" ), 703); - reflection->AddUInt64(message, F("packed_uint64" ), 704); - reflection->AddInt32 (message, F("packed_sint32" ), 705); - reflection->AddInt64 (message, F("packed_sint64" ), 706); - reflection->AddUInt32(message, F("packed_fixed32" ), 707); - reflection->AddUInt64(message, F("packed_fixed64" ), 708); - reflection->AddInt32 (message, F("packed_sfixed32"), 709); - reflection->AddInt64 (message, F("packed_sfixed64"), 710); - reflection->AddFloat (message, F("packed_float" ), 711); - reflection->AddDouble(message, F("packed_double" ), 712); - reflection->AddBool (message, F("packed_bool" ), false); - reflection->AddEnum (message, F("packed_enum" ), foreign_baz_); -} - -// ------------------------------------------------------------------- - -void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection( - const Message& message) { - // We have to split this into three function otherwise it creates a stack - // frame so large that it triggers a warning. - ExpectAllFieldsSetViaReflection1(message); - ExpectAllFieldsSetViaReflection2(message); - ExpectAllFieldsSetViaReflection3(message); -} - -void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection1( - const Message& message) { - const Reflection* reflection = message.GetReflection(); - string scratch; - const Message* sub_message; - - EXPECT_TRUE(reflection->HasField(message, F("optional_int32" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_int64" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_uint32" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_uint64" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_sint32" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_sint64" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_fixed32" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_fixed64" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_sfixed32"))); - EXPECT_TRUE(reflection->HasField(message, F("optional_sfixed64"))); - EXPECT_TRUE(reflection->HasField(message, F("optional_float" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_double" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_bool" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_string" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_bytes" ))); - - EXPECT_TRUE(reflection->HasField(message, F("optionalgroup" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_nested_message" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_foreign_message" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_import_message" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_public_import_message"))); - EXPECT_TRUE(reflection->HasField(message, F("optional_lazy_message" ))); - - sub_message = &reflection->GetMessage(message, F("optionalgroup")); - EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, group_a_)); - sub_message = &reflection->GetMessage(message, F("optional_nested_message")); - EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); - sub_message = &reflection->GetMessage(message, F("optional_foreign_message")); - EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, foreign_c_)); - sub_message = &reflection->GetMessage(message, F("optional_import_message")); - EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, import_d_)); - sub_message = &reflection->GetMessage(message, F("optional_public_import_message")); - EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, import_e_)); - sub_message = &reflection->GetMessage(message, F("optional_lazy_message")); - EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); - - EXPECT_TRUE(reflection->HasField(message, F("optional_nested_enum" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_foreign_enum"))); - EXPECT_TRUE(reflection->HasField(message, F("optional_import_enum" ))); - - EXPECT_TRUE(reflection->HasField(message, F("optional_string_piece"))); - EXPECT_TRUE(reflection->HasField(message, F("optional_cord"))); - - EXPECT_EQ(101 , reflection->GetInt32 (message, F("optional_int32" ))); - EXPECT_EQ(102 , reflection->GetInt64 (message, F("optional_int64" ))); - EXPECT_EQ(103 , reflection->GetUInt32(message, F("optional_uint32" ))); - EXPECT_EQ(104 , reflection->GetUInt64(message, F("optional_uint64" ))); - EXPECT_EQ(105 , reflection->GetInt32 (message, F("optional_sint32" ))); - EXPECT_EQ(106 , reflection->GetInt64 (message, F("optional_sint64" ))); - EXPECT_EQ(107 , reflection->GetUInt32(message, F("optional_fixed32" ))); - EXPECT_EQ(108 , reflection->GetUInt64(message, F("optional_fixed64" ))); - EXPECT_EQ(109 , reflection->GetInt32 (message, F("optional_sfixed32"))); - EXPECT_EQ(110 , reflection->GetInt64 (message, F("optional_sfixed64"))); - EXPECT_EQ(111 , reflection->GetFloat (message, F("optional_float" ))); - EXPECT_EQ(112 , reflection->GetDouble(message, F("optional_double" ))); - EXPECT_TRUE( reflection->GetBool (message, F("optional_bool" ))); - EXPECT_EQ("115", reflection->GetString(message, F("optional_string" ))); - EXPECT_EQ("116", reflection->GetString(message, F("optional_bytes" ))); - - EXPECT_EQ("115", reflection->GetStringReference(message, F("optional_string"), &scratch)); - EXPECT_EQ("116", reflection->GetStringReference(message, F("optional_bytes" ), &scratch)); - - sub_message = &reflection->GetMessage(message, F("optionalgroup")); - EXPECT_EQ(117, sub_message->GetReflection()->GetInt32(*sub_message, group_a_)); - sub_message = &reflection->GetMessage(message, F("optional_nested_message")); - EXPECT_EQ(118, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - sub_message = &reflection->GetMessage(message, F("optional_foreign_message")); - EXPECT_EQ(119, sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); - sub_message = &reflection->GetMessage(message, F("optional_import_message")); - EXPECT_EQ(120, sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); - sub_message = &reflection->GetMessage(message, F("optional_public_import_message")); - EXPECT_EQ(126, sub_message->GetReflection()->GetInt32(*sub_message, import_e_)); - sub_message = &reflection->GetMessage(message, F("optional_lazy_message")); - EXPECT_EQ(127, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - - EXPECT_EQ( nested_baz_, reflection->GetEnum(message, F("optional_nested_enum" ))); - EXPECT_EQ(foreign_baz_, reflection->GetEnum(message, F("optional_foreign_enum"))); - EXPECT_EQ( import_baz_, reflection->GetEnum(message, F("optional_import_enum" ))); - - EXPECT_EQ("124", reflection->GetString(message, F("optional_string_piece"))); - EXPECT_EQ("124", reflection->GetStringReference(message, F("optional_string_piece"), &scratch)); - - EXPECT_EQ("125", reflection->GetString(message, F("optional_cord"))); - EXPECT_EQ("125", reflection->GetStringReference(message, F("optional_cord"), &scratch)); - - EXPECT_TRUE(reflection->HasField(message, F("oneof_bytes" ))); - EXPECT_EQ("604", reflection->GetString(message, F("oneof_bytes" ))); - - if (base_descriptor_->name() == "TestAllTypes") { - EXPECT_FALSE(reflection->HasField(message, F("oneof_uint32"))); - EXPECT_FALSE(reflection->HasField(message, F("oneof_string"))); - } else { - EXPECT_TRUE(reflection->HasField(message, F("oneof_uint32"))); - EXPECT_TRUE(reflection->HasField(message, F("oneof_string"))); - EXPECT_EQ(601 , reflection->GetUInt32(message, F("oneof_uint32"))); - EXPECT_EQ("603", reflection->GetString(message, F("oneof_string"))); - sub_message = &reflection->GetMessage(message, F("oneof_nested_message")); - EXPECT_EQ(602, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - } -} - -void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection2( - const Message& message) { - const Reflection* reflection = message.GetReflection(); - string scratch; - const Message* sub_message; - - // ----------------------------------------------------------------- - - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_int32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_int64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_uint32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_uint64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sint32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sint64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_fixed32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_fixed64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sfixed32"))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sfixed64"))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_float" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_double" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_bool" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_string" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_bytes" ))); - - ASSERT_EQ(2, reflection->FieldSize(message, F("repeatedgroup" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_nested_message" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_foreign_message"))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_import_message" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_lazy_message" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_nested_enum" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_foreign_enum" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_import_enum" ))); - - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_string_piece"))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_cord"))); - - EXPECT_EQ(201 , reflection->GetRepeatedInt32 (message, F("repeated_int32" ), 0)); - EXPECT_EQ(202 , reflection->GetRepeatedInt64 (message, F("repeated_int64" ), 0)); - EXPECT_EQ(203 , reflection->GetRepeatedUInt32(message, F("repeated_uint32" ), 0)); - EXPECT_EQ(204 , reflection->GetRepeatedUInt64(message, F("repeated_uint64" ), 0)); - EXPECT_EQ(205 , reflection->GetRepeatedInt32 (message, F("repeated_sint32" ), 0)); - EXPECT_EQ(206 , reflection->GetRepeatedInt64 (message, F("repeated_sint64" ), 0)); - EXPECT_EQ(207 , reflection->GetRepeatedUInt32(message, F("repeated_fixed32" ), 0)); - EXPECT_EQ(208 , reflection->GetRepeatedUInt64(message, F("repeated_fixed64" ), 0)); - EXPECT_EQ(209 , reflection->GetRepeatedInt32 (message, F("repeated_sfixed32"), 0)); - EXPECT_EQ(210 , reflection->GetRepeatedInt64 (message, F("repeated_sfixed64"), 0)); - EXPECT_EQ(211 , reflection->GetRepeatedFloat (message, F("repeated_float" ), 0)); - EXPECT_EQ(212 , reflection->GetRepeatedDouble(message, F("repeated_double" ), 0)); - EXPECT_TRUE( reflection->GetRepeatedBool (message, F("repeated_bool" ), 0)); - EXPECT_EQ("215", reflection->GetRepeatedString(message, F("repeated_string" ), 0)); - EXPECT_EQ("216", reflection->GetRepeatedString(message, F("repeated_bytes" ), 0)); - - EXPECT_EQ("215", reflection->GetRepeatedStringReference(message, F("repeated_string"), 0, &scratch)); - EXPECT_EQ("216", reflection->GetRepeatedStringReference(message, F("repeated_bytes"), 0, &scratch)); - - sub_message = &reflection->GetRepeatedMessage(message, F("repeatedgroup"), 0); - EXPECT_EQ(217, sub_message->GetReflection()->GetInt32(*sub_message, repeated_group_a_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_nested_message"), 0); - EXPECT_EQ(218, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_foreign_message"), 0); - EXPECT_EQ(219, sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_import_message"), 0); - EXPECT_EQ(220, sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_lazy_message"), 0); - EXPECT_EQ(227, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - - EXPECT_EQ( nested_bar_, reflection->GetRepeatedEnum(message, F("repeated_nested_enum" ),0)); - EXPECT_EQ(foreign_bar_, reflection->GetRepeatedEnum(message, F("repeated_foreign_enum"),0)); - EXPECT_EQ( import_bar_, reflection->GetRepeatedEnum(message, F("repeated_import_enum" ),0)); - - EXPECT_EQ("224", reflection->GetRepeatedString(message, F("repeated_string_piece"), 0)); - EXPECT_EQ("224", reflection->GetRepeatedStringReference( - message, F("repeated_string_piece"), 0, &scratch)); - - EXPECT_EQ("225", reflection->GetRepeatedString(message, F("repeated_cord"), 0)); - EXPECT_EQ("225", reflection->GetRepeatedStringReference( - message, F("repeated_cord"), 0, &scratch)); - - EXPECT_EQ(301 , reflection->GetRepeatedInt32 (message, F("repeated_int32" ), 1)); - EXPECT_EQ(302 , reflection->GetRepeatedInt64 (message, F("repeated_int64" ), 1)); - EXPECT_EQ(303 , reflection->GetRepeatedUInt32(message, F("repeated_uint32" ), 1)); - EXPECT_EQ(304 , reflection->GetRepeatedUInt64(message, F("repeated_uint64" ), 1)); - EXPECT_EQ(305 , reflection->GetRepeatedInt32 (message, F("repeated_sint32" ), 1)); - EXPECT_EQ(306 , reflection->GetRepeatedInt64 (message, F("repeated_sint64" ), 1)); - EXPECT_EQ(307 , reflection->GetRepeatedUInt32(message, F("repeated_fixed32" ), 1)); - EXPECT_EQ(308 , reflection->GetRepeatedUInt64(message, F("repeated_fixed64" ), 1)); - EXPECT_EQ(309 , reflection->GetRepeatedInt32 (message, F("repeated_sfixed32"), 1)); - EXPECT_EQ(310 , reflection->GetRepeatedInt64 (message, F("repeated_sfixed64"), 1)); - EXPECT_EQ(311 , reflection->GetRepeatedFloat (message, F("repeated_float" ), 1)); - EXPECT_EQ(312 , reflection->GetRepeatedDouble(message, F("repeated_double" ), 1)); - EXPECT_FALSE( reflection->GetRepeatedBool (message, F("repeated_bool" ), 1)); - EXPECT_EQ("315", reflection->GetRepeatedString(message, F("repeated_string" ), 1)); - EXPECT_EQ("316", reflection->GetRepeatedString(message, F("repeated_bytes" ), 1)); - - EXPECT_EQ("315", reflection->GetRepeatedStringReference(message, F("repeated_string"), - 1, &scratch)); - EXPECT_EQ("316", reflection->GetRepeatedStringReference(message, F("repeated_bytes"), - 1, &scratch)); - - sub_message = &reflection->GetRepeatedMessage(message, F("repeatedgroup"), 1); - EXPECT_EQ(317, sub_message->GetReflection()->GetInt32(*sub_message, repeated_group_a_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_nested_message"), 1); - EXPECT_EQ(318, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_foreign_message"), 1); - EXPECT_EQ(319, sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_import_message"), 1); - EXPECT_EQ(320, sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_lazy_message"), 1); - EXPECT_EQ(327, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - - EXPECT_EQ( nested_baz_, reflection->GetRepeatedEnum(message, F("repeated_nested_enum" ),1)); - EXPECT_EQ(foreign_baz_, reflection->GetRepeatedEnum(message, F("repeated_foreign_enum"),1)); - EXPECT_EQ( import_baz_, reflection->GetRepeatedEnum(message, F("repeated_import_enum" ),1)); - - EXPECT_EQ("324", reflection->GetRepeatedString(message, F("repeated_string_piece"), 1)); - EXPECT_EQ("324", reflection->GetRepeatedStringReference( - message, F("repeated_string_piece"), 1, &scratch)); - - EXPECT_EQ("325", reflection->GetRepeatedString(message, F("repeated_cord"), 1)); - EXPECT_EQ("325", reflection->GetRepeatedStringReference( - message, F("repeated_cord"), 1, &scratch)); -} - -void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection3( - const Message& message) { - const Reflection* reflection = message.GetReflection(); - string scratch; - - // ----------------------------------------------------------------- - - EXPECT_TRUE(reflection->HasField(message, F("default_int32" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_int64" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_uint32" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_uint64" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_sint32" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_sint64" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_fixed32" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_fixed64" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_sfixed32"))); - EXPECT_TRUE(reflection->HasField(message, F("default_sfixed64"))); - EXPECT_TRUE(reflection->HasField(message, F("default_float" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_double" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_bool" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_string" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_bytes" ))); - - EXPECT_TRUE(reflection->HasField(message, F("default_nested_enum" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_foreign_enum"))); - EXPECT_TRUE(reflection->HasField(message, F("default_import_enum" ))); - - EXPECT_TRUE(reflection->HasField(message, F("default_string_piece"))); - EXPECT_TRUE(reflection->HasField(message, F("default_cord"))); - - EXPECT_EQ(401 , reflection->GetInt32 (message, F("default_int32" ))); - EXPECT_EQ(402 , reflection->GetInt64 (message, F("default_int64" ))); - EXPECT_EQ(403 , reflection->GetUInt32(message, F("default_uint32" ))); - EXPECT_EQ(404 , reflection->GetUInt64(message, F("default_uint64" ))); - EXPECT_EQ(405 , reflection->GetInt32 (message, F("default_sint32" ))); - EXPECT_EQ(406 , reflection->GetInt64 (message, F("default_sint64" ))); - EXPECT_EQ(407 , reflection->GetUInt32(message, F("default_fixed32" ))); - EXPECT_EQ(408 , reflection->GetUInt64(message, F("default_fixed64" ))); - EXPECT_EQ(409 , reflection->GetInt32 (message, F("default_sfixed32"))); - EXPECT_EQ(410 , reflection->GetInt64 (message, F("default_sfixed64"))); - EXPECT_EQ(411 , reflection->GetFloat (message, F("default_float" ))); - EXPECT_EQ(412 , reflection->GetDouble(message, F("default_double" ))); - EXPECT_FALSE( reflection->GetBool (message, F("default_bool" ))); - EXPECT_EQ("415", reflection->GetString(message, F("default_string" ))); - EXPECT_EQ("416", reflection->GetString(message, F("default_bytes" ))); - - EXPECT_EQ("415", reflection->GetStringReference(message, F("default_string"), &scratch)); - EXPECT_EQ("416", reflection->GetStringReference(message, F("default_bytes" ), &scratch)); - - EXPECT_EQ( nested_foo_, reflection->GetEnum(message, F("default_nested_enum" ))); - EXPECT_EQ(foreign_foo_, reflection->GetEnum(message, F("default_foreign_enum"))); - EXPECT_EQ( import_foo_, reflection->GetEnum(message, F("default_import_enum" ))); - - EXPECT_EQ("424", reflection->GetString(message, F("default_string_piece"))); - EXPECT_EQ("424", reflection->GetStringReference(message, F("default_string_piece"), - &scratch)); - - EXPECT_EQ("425", reflection->GetString(message, F("default_cord"))); - EXPECT_EQ("425", reflection->GetStringReference(message, F("default_cord"), &scratch)); -} - -void TestUtil::ReflectionTester::ExpectPackedFieldsSetViaReflection( - const Message& message) { - const Reflection* reflection = message.GetReflection(); - - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_int32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_int64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_uint32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_uint64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sint32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sint64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_fixed32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_fixed64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sfixed32"))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sfixed64"))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_float" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_double" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_bool" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_enum" ))); - - EXPECT_EQ(601 , reflection->GetRepeatedInt32 (message, F("packed_int32" ), 0)); - EXPECT_EQ(602 , reflection->GetRepeatedInt64 (message, F("packed_int64" ), 0)); - EXPECT_EQ(603 , reflection->GetRepeatedUInt32(message, F("packed_uint32" ), 0)); - EXPECT_EQ(604 , reflection->GetRepeatedUInt64(message, F("packed_uint64" ), 0)); - EXPECT_EQ(605 , reflection->GetRepeatedInt32 (message, F("packed_sint32" ), 0)); - EXPECT_EQ(606 , reflection->GetRepeatedInt64 (message, F("packed_sint64" ), 0)); - EXPECT_EQ(607 , reflection->GetRepeatedUInt32(message, F("packed_fixed32" ), 0)); - EXPECT_EQ(608 , reflection->GetRepeatedUInt64(message, F("packed_fixed64" ), 0)); - EXPECT_EQ(609 , reflection->GetRepeatedInt32 (message, F("packed_sfixed32"), 0)); - EXPECT_EQ(610 , reflection->GetRepeatedInt64 (message, F("packed_sfixed64"), 0)); - EXPECT_EQ(611 , reflection->GetRepeatedFloat (message, F("packed_float" ), 0)); - EXPECT_EQ(612 , reflection->GetRepeatedDouble(message, F("packed_double" ), 0)); - EXPECT_TRUE( reflection->GetRepeatedBool (message, F("packed_bool" ), 0)); - EXPECT_EQ(foreign_bar_, - reflection->GetRepeatedEnum(message, F("packed_enum"), 0)); - - EXPECT_EQ(701 , reflection->GetRepeatedInt32 (message, F("packed_int32" ), 1)); - EXPECT_EQ(702 , reflection->GetRepeatedInt64 (message, F("packed_int64" ), 1)); - EXPECT_EQ(703 , reflection->GetRepeatedUInt32(message, F("packed_uint32" ), 1)); - EXPECT_EQ(704 , reflection->GetRepeatedUInt64(message, F("packed_uint64" ), 1)); - EXPECT_EQ(705 , reflection->GetRepeatedInt32 (message, F("packed_sint32" ), 1)); - EXPECT_EQ(706 , reflection->GetRepeatedInt64 (message, F("packed_sint64" ), 1)); - EXPECT_EQ(707 , reflection->GetRepeatedUInt32(message, F("packed_fixed32" ), 1)); - EXPECT_EQ(708 , reflection->GetRepeatedUInt64(message, F("packed_fixed64" ), 1)); - EXPECT_EQ(709 , reflection->GetRepeatedInt32 (message, F("packed_sfixed32"), 1)); - EXPECT_EQ(710 , reflection->GetRepeatedInt64 (message, F("packed_sfixed64"), 1)); - EXPECT_EQ(711 , reflection->GetRepeatedFloat (message, F("packed_float" ), 1)); - EXPECT_EQ(712 , reflection->GetRepeatedDouble(message, F("packed_double" ), 1)); - EXPECT_FALSE( reflection->GetRepeatedBool (message, F("packed_bool" ), 1)); - EXPECT_EQ(foreign_baz_, - reflection->GetRepeatedEnum(message, F("packed_enum"), 1)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ReflectionTester::ExpectClearViaReflection( - const Message& message) { - const Reflection* reflection = message.GetReflection(); - string scratch; - const Message* sub_message; - - // has_blah() should initially be false for all optional fields. - EXPECT_FALSE(reflection->HasField(message, F("optional_int32" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_int64" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_uint32" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_uint64" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_sint32" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_sint64" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_fixed32" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_fixed64" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_sfixed32"))); - EXPECT_FALSE(reflection->HasField(message, F("optional_sfixed64"))); - EXPECT_FALSE(reflection->HasField(message, F("optional_float" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_double" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_bool" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_string" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_bytes" ))); - - EXPECT_FALSE(reflection->HasField(message, F("optionalgroup" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_nested_message" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_foreign_message"))); - EXPECT_FALSE(reflection->HasField(message, F("optional_import_message" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_public_import_message"))); - EXPECT_FALSE(reflection->HasField(message, F("optional_lazy_message"))); - - EXPECT_FALSE(reflection->HasField(message, F("optional_nested_enum" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_foreign_enum"))); - EXPECT_FALSE(reflection->HasField(message, F("optional_import_enum" ))); - - EXPECT_FALSE(reflection->HasField(message, F("optional_string_piece"))); - EXPECT_FALSE(reflection->HasField(message, F("optional_cord"))); - - // Optional fields without defaults are set to zero or something like it. - EXPECT_EQ(0 , reflection->GetInt32 (message, F("optional_int32" ))); - EXPECT_EQ(0 , reflection->GetInt64 (message, F("optional_int64" ))); - EXPECT_EQ(0 , reflection->GetUInt32(message, F("optional_uint32" ))); - EXPECT_EQ(0 , reflection->GetUInt64(message, F("optional_uint64" ))); - EXPECT_EQ(0 , reflection->GetInt32 (message, F("optional_sint32" ))); - EXPECT_EQ(0 , reflection->GetInt64 (message, F("optional_sint64" ))); - EXPECT_EQ(0 , reflection->GetUInt32(message, F("optional_fixed32" ))); - EXPECT_EQ(0 , reflection->GetUInt64(message, F("optional_fixed64" ))); - EXPECT_EQ(0 , reflection->GetInt32 (message, F("optional_sfixed32"))); - EXPECT_EQ(0 , reflection->GetInt64 (message, F("optional_sfixed64"))); - EXPECT_EQ(0 , reflection->GetFloat (message, F("optional_float" ))); - EXPECT_EQ(0 , reflection->GetDouble(message, F("optional_double" ))); - EXPECT_FALSE( reflection->GetBool (message, F("optional_bool" ))); - EXPECT_EQ("" , reflection->GetString(message, F("optional_string" ))); - EXPECT_EQ("" , reflection->GetString(message, F("optional_bytes" ))); - - EXPECT_EQ("", reflection->GetStringReference(message, F("optional_string"), &scratch)); - EXPECT_EQ("", reflection->GetStringReference(message, F("optional_bytes" ), &scratch)); - - // Embedded messages should also be clear. - sub_message = &reflection->GetMessage(message, F("optionalgroup")); - EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, group_a_)); - EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, group_a_)); - sub_message = &reflection->GetMessage(message, F("optional_nested_message")); - EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); - EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - sub_message = &reflection->GetMessage(message, F("optional_foreign_message")); - EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, foreign_c_)); - EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); - sub_message = &reflection->GetMessage(message, F("optional_import_message")); - EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, import_d_)); - EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); - sub_message = &reflection->GetMessage(message, F("optional_public_import_message")); - EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, import_e_)); - EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, import_e_)); - sub_message = &reflection->GetMessage(message, F("optional_lazy_message")); - EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); - EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - - // Enums without defaults are set to the first value in the enum. - EXPECT_EQ( nested_foo_, reflection->GetEnum(message, F("optional_nested_enum" ))); - EXPECT_EQ(foreign_foo_, reflection->GetEnum(message, F("optional_foreign_enum"))); - EXPECT_EQ( import_foo_, reflection->GetEnum(message, F("optional_import_enum" ))); - - EXPECT_EQ("", reflection->GetString(message, F("optional_string_piece"))); - EXPECT_EQ("", reflection->GetStringReference(message, F("optional_string_piece"), &scratch)); - - EXPECT_EQ("", reflection->GetString(message, F("optional_cord"))); - EXPECT_EQ("", reflection->GetStringReference(message, F("optional_cord"), &scratch)); - - // Repeated fields are empty. - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_int32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_int64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_uint32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_uint64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sint32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sint64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_fixed32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_fixed64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sfixed32"))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sfixed64"))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_float" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_double" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_bool" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_string" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_bytes" ))); - - EXPECT_EQ(0, reflection->FieldSize(message, F("repeatedgroup" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_nested_message" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_foreign_message"))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_import_message" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_lazy_message" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_nested_enum" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_foreign_enum" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_import_enum" ))); - - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_string_piece"))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_cord"))); - - // has_blah() should also be false for all default fields. - EXPECT_FALSE(reflection->HasField(message, F("default_int32" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_int64" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_uint32" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_uint64" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_sint32" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_sint64" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_fixed32" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_fixed64" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_sfixed32"))); - EXPECT_FALSE(reflection->HasField(message, F("default_sfixed64"))); - EXPECT_FALSE(reflection->HasField(message, F("default_float" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_double" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_bool" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_string" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_bytes" ))); - - EXPECT_FALSE(reflection->HasField(message, F("default_nested_enum" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_foreign_enum"))); - EXPECT_FALSE(reflection->HasField(message, F("default_import_enum" ))); - - EXPECT_FALSE(reflection->HasField(message, F("default_string_piece"))); - EXPECT_FALSE(reflection->HasField(message, F("default_cord"))); - - // Fields with defaults have their default values (duh). - EXPECT_EQ( 41 , reflection->GetInt32 (message, F("default_int32" ))); - EXPECT_EQ( 42 , reflection->GetInt64 (message, F("default_int64" ))); - EXPECT_EQ( 43 , reflection->GetUInt32(message, F("default_uint32" ))); - EXPECT_EQ( 44 , reflection->GetUInt64(message, F("default_uint64" ))); - EXPECT_EQ(-45 , reflection->GetInt32 (message, F("default_sint32" ))); - EXPECT_EQ( 46 , reflection->GetInt64 (message, F("default_sint64" ))); - EXPECT_EQ( 47 , reflection->GetUInt32(message, F("default_fixed32" ))); - EXPECT_EQ( 48 , reflection->GetUInt64(message, F("default_fixed64" ))); - EXPECT_EQ( 49 , reflection->GetInt32 (message, F("default_sfixed32"))); - EXPECT_EQ(-50 , reflection->GetInt64 (message, F("default_sfixed64"))); - EXPECT_EQ( 51.5 , reflection->GetFloat (message, F("default_float" ))); - EXPECT_EQ( 52e3 , reflection->GetDouble(message, F("default_double" ))); - EXPECT_TRUE( reflection->GetBool (message, F("default_bool" ))); - EXPECT_EQ("hello", reflection->GetString(message, F("default_string" ))); - EXPECT_EQ("world", reflection->GetString(message, F("default_bytes" ))); - - EXPECT_EQ("hello", reflection->GetStringReference(message, F("default_string"), &scratch)); - EXPECT_EQ("world", reflection->GetStringReference(message, F("default_bytes" ), &scratch)); - - EXPECT_EQ( nested_bar_, reflection->GetEnum(message, F("default_nested_enum" ))); - EXPECT_EQ(foreign_bar_, reflection->GetEnum(message, F("default_foreign_enum"))); - EXPECT_EQ( import_bar_, reflection->GetEnum(message, F("default_import_enum" ))); - - EXPECT_EQ("abc", reflection->GetString(message, F("default_string_piece"))); - EXPECT_EQ("abc", reflection->GetStringReference(message, F("default_string_piece"), &scratch)); - - EXPECT_EQ("123", reflection->GetString(message, F("default_cord"))); - EXPECT_EQ("123", reflection->GetStringReference(message, F("default_cord"), &scratch)); -} - -void TestUtil::ReflectionTester::ExpectPackedClearViaReflection( - const Message& message) { - const Reflection* reflection = message.GetReflection(); - - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_int32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_int64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_uint32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_uint64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sint32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sint64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_fixed32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_fixed64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sfixed32"))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sfixed64"))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_float" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_double" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_bool" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_enum" ))); -} - -// ------------------------------------------------------------------- - -void TestUtil::ReflectionTester::ModifyRepeatedFieldsViaReflection( - Message* message) { - const Reflection* reflection = message->GetReflection(); - Message* sub_message; - - reflection->SetRepeatedInt32 (message, F("repeated_int32" ), 1, 501); - reflection->SetRepeatedInt64 (message, F("repeated_int64" ), 1, 502); - reflection->SetRepeatedUInt32(message, F("repeated_uint32" ), 1, 503); - reflection->SetRepeatedUInt64(message, F("repeated_uint64" ), 1, 504); - reflection->SetRepeatedInt32 (message, F("repeated_sint32" ), 1, 505); - reflection->SetRepeatedInt64 (message, F("repeated_sint64" ), 1, 506); - reflection->SetRepeatedUInt32(message, F("repeated_fixed32" ), 1, 507); - reflection->SetRepeatedUInt64(message, F("repeated_fixed64" ), 1, 508); - reflection->SetRepeatedInt32 (message, F("repeated_sfixed32"), 1, 509); - reflection->SetRepeatedInt64 (message, F("repeated_sfixed64"), 1, 510); - reflection->SetRepeatedFloat (message, F("repeated_float" ), 1, 511); - reflection->SetRepeatedDouble(message, F("repeated_double" ), 1, 512); - reflection->SetRepeatedBool (message, F("repeated_bool" ), 1, true); - reflection->SetRepeatedString(message, F("repeated_string" ), 1, "515"); - reflection->SetRepeatedString(message, F("repeated_bytes" ), 1, "516"); - - sub_message = reflection->MutableRepeatedMessage(message, F("repeatedgroup"), 1); - sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 517); - sub_message = reflection->MutableRepeatedMessage(message, F("repeated_nested_message"), 1); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 518); - sub_message = reflection->MutableRepeatedMessage(message, F("repeated_foreign_message"), 1); - sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 519); - sub_message = reflection->MutableRepeatedMessage(message, F("repeated_import_message"), 1); - sub_message->GetReflection()->SetInt32(sub_message, import_d_, 520); - sub_message = reflection->MutableRepeatedMessage(message, F("repeated_lazy_message"), 1); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 527); - - reflection->SetRepeatedEnum(message, F("repeated_nested_enum" ), 1, nested_foo_); - reflection->SetRepeatedEnum(message, F("repeated_foreign_enum"), 1, foreign_foo_); - reflection->SetRepeatedEnum(message, F("repeated_import_enum" ), 1, import_foo_); - - reflection->SetRepeatedString(message, F("repeated_string_piece"), 1, "524"); - reflection->SetRepeatedString(message, F("repeated_cord"), 1, "525"); -} - -void TestUtil::ReflectionTester::ModifyPackedFieldsViaReflection( - Message* message) { - const Reflection* reflection = message->GetReflection(); - reflection->SetRepeatedInt32 (message, F("packed_int32" ), 1, 801); - reflection->SetRepeatedInt64 (message, F("packed_int64" ), 1, 802); - reflection->SetRepeatedUInt32(message, F("packed_uint32" ), 1, 803); - reflection->SetRepeatedUInt64(message, F("packed_uint64" ), 1, 804); - reflection->SetRepeatedInt32 (message, F("packed_sint32" ), 1, 805); - reflection->SetRepeatedInt64 (message, F("packed_sint64" ), 1, 806); - reflection->SetRepeatedUInt32(message, F("packed_fixed32" ), 1, 807); - reflection->SetRepeatedUInt64(message, F("packed_fixed64" ), 1, 808); - reflection->SetRepeatedInt32 (message, F("packed_sfixed32"), 1, 809); - reflection->SetRepeatedInt64 (message, F("packed_sfixed64"), 1, 810); - reflection->SetRepeatedFloat (message, F("packed_float" ), 1, 811); - reflection->SetRepeatedDouble(message, F("packed_double" ), 1, 812); - reflection->SetRepeatedBool (message, F("packed_bool" ), 1, true); - reflection->SetRepeatedEnum (message, F("packed_enum" ), 1, foreign_foo_); -} - -void TestUtil::ReflectionTester::RemoveLastRepeatedsViaReflection( - Message* message) { - const Reflection* reflection = message->GetReflection(); - - std::vector<const FieldDescriptor*> output; - reflection->ListFields(*message, &output); - for (int i=0; i<output.size(); ++i) { - const FieldDescriptor* field = output[i]; - if (!field->is_repeated()) continue; - - reflection->RemoveLast(message, field); - } -} - -void TestUtil::ReflectionTester::ReleaseLastRepeatedsViaReflection( - Message* message, bool expect_extensions_notnull) { - const Reflection* reflection = message->GetReflection(); - - std::vector<const FieldDescriptor*> output; - reflection->ListFields(*message, &output); - for (int i=0; i<output.size(); ++i) { - const FieldDescriptor* field = output[i]; - if (!field->is_repeated()) continue; - if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) continue; - - Message* released = reflection->ReleaseLast(message, field); - if (!field->is_extension() || expect_extensions_notnull) { - ASSERT_TRUE(released != NULL) << "ReleaseLast returned NULL for: " - << field->name(); - } - delete released; - } -} - -void TestUtil::ReflectionTester::SwapRepeatedsViaReflection(Message* message) { - const Reflection* reflection = message->GetReflection(); - - std::vector<const FieldDescriptor*> output; - reflection->ListFields(*message, &output); - for (int i=0; i<output.size(); ++i) { - const FieldDescriptor* field = output[i]; - if (!field->is_repeated()) continue; - - reflection->SwapElements(message, field, 0, 1); - } -} - -void TestUtil::ReflectionTester:: -SetAllocatedOptionalMessageFieldsToNullViaReflection( - Message* message) { - const Reflection* reflection = message->GetReflection(); - - std::vector<const FieldDescriptor*> fields; - reflection->ListFields(*message, &fields); - - for (int i = 0; i < fields.size(); ++i) { - const FieldDescriptor* field = fields[i]; - if (!field->is_optional() || - field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) continue; - - reflection->SetAllocatedMessage(message, NULL, field); - } -} - -void TestUtil::ReflectionTester:: -SetAllocatedOptionalMessageFieldsToMessageViaReflection( - Message* from_message, - Message* to_message) { - EXPECT_EQ(from_message->GetDescriptor(), to_message->GetDescriptor()); - const Reflection* from_reflection = from_message->GetReflection(); - const Reflection* to_reflection = to_message->GetReflection(); - - std::vector<const FieldDescriptor*> fields; - from_reflection->ListFields(*from_message, &fields); - - for (int i = 0; i < fields.size(); ++i) { - const FieldDescriptor* field = fields[i]; - if (!field->is_optional() || - field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) continue; - - Message* sub_message = - from_reflection->ReleaseMessage(from_message, field); - to_reflection->SetAllocatedMessage(to_message, sub_message, field); - } -} - -void TestUtil::ReflectionTester::ExpectMessagesReleasedViaReflection( - Message* message, - TestUtil::ReflectionTester::MessageReleaseState expected_release_state) { - const Reflection* reflection = message->GetReflection(); - - static const char* fields[] = { - "optionalgroup", - "optional_nested_message", - "optional_foreign_message", - "optional_import_message", - }; - for (int i = 0; i < GOOGLE_ARRAYSIZE(fields); i++) { - const Message& sub_message = reflection->GetMessage(*message, F(fields[i])); - Message* released = reflection->ReleaseMessage(message, F(fields[i])); - switch (expected_release_state) { - case IS_NULL: - EXPECT_TRUE(released == NULL); - break; - case NOT_NULL: - EXPECT_TRUE(released != NULL); - if (message->GetArena() == NULL) { - // released message must be same as sub_message if source message is - // not on arena. - EXPECT_EQ(&sub_message, released); - } - break; - case CAN_BE_NULL: - break; - } - delete released; - EXPECT_FALSE(reflection->HasField(*message, F(fields[i]))); - } -} - } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/test_util.h b/src/google/protobuf/test_util.h index 1c13a1a7..b9abb671 100644 --- a/src/google/protobuf/test_util.h +++ b/src/google/protobuf/test_util.h @@ -35,180 +35,1266 @@ #ifndef GOOGLE_PROTOBUF_TEST_UTIL_H__ #define GOOGLE_PROTOBUF_TEST_UTIL_H__ -#include <stack> -#include <string> -#include <google/protobuf/message.h> #include <google/protobuf/unittest.pb.h> +#define UNITTEST ::protobuf_unittest +#define UNITTEST_IMPORT ::protobuf_unittest_import +// Must be included when the preprocessor symbols above are defined. +#include <google/protobuf/test_util.inc> +#undef UNITTEST +#undef UNITTEST_IMPORT + + namespace google { namespace protobuf { - +// This file doesn't use these declarations, but some .cc files do. namespace unittest = ::protobuf_unittest; -namespace unittest_import = protobuf_unittest_import; +namespace unittest_import = ::protobuf_unittest_import; -class TestUtil { +namespace TestUtil { + +class ReflectionTester { public: - // Set every field in the message to a unique value. - static void SetAllFields(unittest::TestAllTypes* message); - static void SetOptionalFields(unittest::TestAllTypes* message); - static void AddRepeatedFields1(unittest::TestAllTypes* message); - static void AddRepeatedFields2(unittest::TestAllTypes* message); - static void SetDefaultFields(unittest::TestAllTypes* message); - static void SetOneofFields(unittest::TestAllTypes* message); - static void SetAllExtensions(unittest::TestAllExtensions* message); - static void SetOneofFields(unittest::TestAllExtensions* message); - static void SetAllFieldsAndExtensions(unittest::TestFieldOrderings* message); - static void SetPackedFields(unittest::TestPackedTypes* message); - static void SetPackedExtensions(unittest::TestPackedExtensions* message); - static void SetUnpackedFields(unittest::TestUnpackedTypes* message); - static void SetOneof1(unittest::TestOneof2* message); - static void SetOneof2(unittest::TestOneof2* message); - - // Use the repeated versions of the set_*() accessors to modify all the - // repeated fields of the message (which should already have been - // initialized with Set*Fields()). Set*Fields() itself only tests - // the add_*() accessors. - static void ModifyRepeatedFields(unittest::TestAllTypes* message); - static void ModifyRepeatedExtensions(unittest::TestAllExtensions* message); - static void ModifyPackedFields(unittest::TestPackedTypes* message); - static void ModifyPackedExtensions(unittest::TestPackedExtensions* message); - - // Check that all fields have the values that they should have after - // Set*Fields() is called. - static void ExpectAllFieldsSet(const unittest::TestAllTypes& message); - static void ExpectAllExtensionsSet( - const unittest::TestAllExtensions& message); - static void ExpectPackedFieldsSet(const unittest::TestPackedTypes& message); - static void ExpectPackedExtensionsSet( - const unittest::TestPackedExtensions& message); - static void ExpectUnpackedFieldsSet( - const unittest::TestUnpackedTypes& message); - static void ExpectUnpackedExtensionsSet( - const unittest::TestUnpackedExtensions& message); - static void ExpectOneofSet1(const unittest::TestOneof2& message); - static void ExpectOneofSet2(const unittest::TestOneof2& message); - - // Expect that the message is modified as would be expected from - // Modify*Fields(). - static void ExpectRepeatedFieldsModified( - const unittest::TestAllTypes& message); - static void ExpectRepeatedExtensionsModified( - const unittest::TestAllExtensions& message); - static void ExpectPackedFieldsModified( - const unittest::TestPackedTypes& message); - static void ExpectPackedExtensionsModified( - const unittest::TestPackedExtensions& message); - - // Check that all fields have their default values. - static void ExpectClear(const unittest::TestAllTypes& message); - static void ExpectExtensionsClear(const unittest::TestAllExtensions& message); - static void ExpectPackedClear(const unittest::TestPackedTypes& message); - static void ExpectPackedExtensionsClear( - const unittest::TestPackedExtensions& message); - static void ExpectOneofClear(const unittest::TestOneof2& message); - - // Check that the passed-in serialization is the canonical serialization we - // expect for a TestFieldOrderings message filled in by - // SetAllFieldsAndExtensions(). - static void ExpectAllFieldsAndExtensionsInOrder(const string& serialized); - - // Check that all repeated fields have had their last elements removed. - static void ExpectLastRepeatedsRemoved( - const unittest::TestAllTypes& message); - static void ExpectLastRepeatedExtensionsRemoved( - const unittest::TestAllExtensions& message); - static void ExpectLastRepeatedsReleased( - const unittest::TestAllTypes& message); - static void ExpectLastRepeatedExtensionsReleased( - const unittest::TestAllExtensions& message); - - // Check that all repeated fields have had their first and last elements - // swapped. - static void ExpectRepeatedsSwapped(const unittest::TestAllTypes& message); - static void ExpectRepeatedExtensionsSwapped( - const unittest::TestAllExtensions& message); - - static void ExpectAtMostOneFieldSetInOneof( - const unittest::TestOneof2 &message); - - // Like above, but use the reflection interface. - class ReflectionTester { - public: - // base_descriptor must be a descriptor for TestAllTypes or - // TestAllExtensions. In the former case, ReflectionTester fetches from - // it the FieldDescriptors needed to use the reflection interface. In - // the latter case, ReflectionTester searches for extension fields in - // its file. - explicit ReflectionTester(const Descriptor* base_descriptor); - - void SetAllFieldsViaReflection(Message* message); - void ModifyRepeatedFieldsViaReflection(Message* message); - void ExpectAllFieldsSetViaReflection(const Message& message); - void ExpectClearViaReflection(const Message& message); - - void SetPackedFieldsViaReflection(Message* message); - void ModifyPackedFieldsViaReflection(Message* message); - void ExpectPackedFieldsSetViaReflection(const Message& message); - void ExpectPackedClearViaReflection(const Message& message); - - void RemoveLastRepeatedsViaReflection(Message* message); - void ReleaseLastRepeatedsViaReflection( - Message* message, bool expect_extensions_notnull); - void SwapRepeatedsViaReflection(Message* message); - void SetAllocatedOptionalMessageFieldsToNullViaReflection( - Message* message); - static void SetAllocatedOptionalMessageFieldsToMessageViaReflection( - Message* from_message, - Message* to_message); - - enum MessageReleaseState { - IS_NULL, - CAN_BE_NULL, - NOT_NULL, - }; - void ExpectMessagesReleasedViaReflection( - Message* message, MessageReleaseState expected_release_state); - - // Set and check functions for TestOneof2 messages. No need to construct - // the ReflectionTester by TestAllTypes nor TestAllExtensions. - static void SetOneofViaReflection(Message* message); - static void ExpectOneofSetViaReflection(const Message& message); - - private: - const FieldDescriptor* F(const string& name); - - const Descriptor* base_descriptor_; - - const FieldDescriptor* group_a_; - const FieldDescriptor* repeated_group_a_; - const FieldDescriptor* nested_b_; - const FieldDescriptor* foreign_c_; - const FieldDescriptor* import_d_; - const FieldDescriptor* import_e_; - - const EnumValueDescriptor* nested_foo_; - const EnumValueDescriptor* nested_bar_; - const EnumValueDescriptor* nested_baz_; - const EnumValueDescriptor* foreign_foo_; - const EnumValueDescriptor* foreign_bar_; - const EnumValueDescriptor* foreign_baz_; - const EnumValueDescriptor* import_foo_; - const EnumValueDescriptor* import_bar_; - const EnumValueDescriptor* import_baz_; - - // We have to split this into three function otherwise it creates a stack - // frame so large that it triggers a warning. - void ExpectAllFieldsSetViaReflection1(const Message& message); - void ExpectAllFieldsSetViaReflection2(const Message& message); - void ExpectAllFieldsSetViaReflection3(const Message& message); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ReflectionTester); + // base_descriptor must be a descriptor for TestAllTypes or + // TestAllExtensions. In the former case, ReflectionTester fetches from + // it the FieldDescriptors needed to use the reflection interface. In + // the latter case, ReflectionTester searches for extension fields in + // its file. + explicit ReflectionTester(const Descriptor* base_descriptor); + + void SetAllFieldsViaReflection(Message* message); + void ModifyRepeatedFieldsViaReflection(Message* message); + void ExpectAllFieldsSetViaReflection(const Message& message); + void ExpectClearViaReflection(const Message& message); + + void SetPackedFieldsViaReflection(Message* message); + void ModifyPackedFieldsViaReflection(Message* message); + void ExpectPackedFieldsSetViaReflection(const Message& message); + void ExpectPackedClearViaReflection(const Message& message); + + void RemoveLastRepeatedsViaReflection(Message* message); + void ReleaseLastRepeatedsViaReflection(Message* message, + bool expect_extensions_notnull); + void SwapRepeatedsViaReflection(Message* message); + void SetAllocatedOptionalMessageFieldsToNullViaReflection(Message* message); + static void SetAllocatedOptionalMessageFieldsToMessageViaReflection( + Message* from_message, Message* to_message); + + enum MessageReleaseState { + IS_NULL, + CAN_BE_NULL, + NOT_NULL, }; + void ExpectMessagesReleasedViaReflection( + Message* message, MessageReleaseState expected_release_state); + + // Set and check functions for TestOneof2 messages. No need to construct + // the ReflectionTester by TestAllTypes nor TestAllExtensions. + static void SetOneofViaReflection(Message* message); + static void ExpectOneofSetViaReflection(const Message& message); private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TestUtil); + const FieldDescriptor* F(const string& name); + + const Descriptor* base_descriptor_; + + const FieldDescriptor* group_a_; + const FieldDescriptor* repeated_group_a_; + const FieldDescriptor* nested_b_; + const FieldDescriptor* foreign_c_; + const FieldDescriptor* import_d_; + const FieldDescriptor* import_e_; + + const EnumValueDescriptor* nested_foo_; + const EnumValueDescriptor* nested_bar_; + const EnumValueDescriptor* nested_baz_; + const EnumValueDescriptor* foreign_foo_; + const EnumValueDescriptor* foreign_bar_; + const EnumValueDescriptor* foreign_baz_; + const EnumValueDescriptor* import_foo_; + const EnumValueDescriptor* import_bar_; + const EnumValueDescriptor* import_baz_; + + // We have to split this into three function otherwise it creates a stack + // frame so large that it triggers a warning. + void ExpectAllFieldsSetViaReflection1(const Message& message); + void ExpectAllFieldsSetViaReflection2(const Message& message); + void ExpectAllFieldsSetViaReflection3(const Message& message); + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ReflectionTester); }; +inline TestUtil::ReflectionTester::ReflectionTester( + const Descriptor* base_descriptor) + : base_descriptor_(base_descriptor) { + const DescriptorPool* pool = base_descriptor->file()->pool(); + string package = base_descriptor->file()->package(); + const FieldDescriptor* import_descriptor = + pool->FindFieldByName(package + ".TestAllTypes.optional_import_message"); + string import_package = import_descriptor->message_type()->file()->package(); + + nested_b_ = pool->FindFieldByName(package + ".TestAllTypes.NestedMessage.bb"); + foreign_c_ = pool->FindFieldByName(package + ".ForeignMessage.c"); + import_d_ = pool->FindFieldByName(import_package + ".ImportMessage.d"); + import_e_ = pool->FindFieldByName(import_package + ".PublicImportMessage.e"); + nested_foo_ = pool->FindEnumValueByName(package + ".TestAllTypes.FOO"); + nested_bar_ = pool->FindEnumValueByName(package + ".TestAllTypes.BAR"); + nested_baz_ = pool->FindEnumValueByName(package + ".TestAllTypes.BAZ"); + foreign_foo_ = pool->FindEnumValueByName(package + ".FOREIGN_FOO"); + foreign_bar_ = pool->FindEnumValueByName(package + ".FOREIGN_BAR"); + foreign_baz_ = pool->FindEnumValueByName(package + ".FOREIGN_BAZ"); + import_foo_ = pool->FindEnumValueByName(import_package + ".IMPORT_FOO"); + import_bar_ = pool->FindEnumValueByName(import_package + ".IMPORT_BAR"); + import_baz_ = pool->FindEnumValueByName(import_package + ".IMPORT_BAZ"); + + if (base_descriptor_->name() == "TestAllExtensions") { + group_a_ = pool->FindFieldByName(package + ".OptionalGroup_extension.a"); + repeated_group_a_ = + pool->FindFieldByName(package + ".RepeatedGroup_extension.a"); + } else { + group_a_ = pool->FindFieldByName(package + ".TestAllTypes.OptionalGroup.a"); + repeated_group_a_ = + pool->FindFieldByName(package + ".TestAllTypes.RepeatedGroup.a"); + } + + EXPECT_TRUE(group_a_ != nullptr); + EXPECT_TRUE(repeated_group_a_ != nullptr); + EXPECT_TRUE(nested_b_ != nullptr); + EXPECT_TRUE(foreign_c_ != nullptr); + EXPECT_TRUE(import_d_ != nullptr); + EXPECT_TRUE(import_e_ != nullptr); + EXPECT_TRUE(nested_foo_ != nullptr); + EXPECT_TRUE(nested_bar_ != nullptr); + EXPECT_TRUE(nested_baz_ != nullptr); + EXPECT_TRUE(foreign_foo_ != nullptr); + EXPECT_TRUE(foreign_bar_ != nullptr); + EXPECT_TRUE(foreign_baz_ != nullptr); + EXPECT_TRUE(import_foo_ != nullptr); + EXPECT_TRUE(import_bar_ != nullptr); + EXPECT_TRUE(import_baz_ != nullptr); +} + +// Shorthand to get a FieldDescriptor for a field of TestAllTypes. +inline const FieldDescriptor* TestUtil::ReflectionTester::F( + const string& name) { + const FieldDescriptor* result = nullptr; + if (base_descriptor_->name() == "TestAllExtensions" || + base_descriptor_->name() == "TestPackedExtensions") { + result = base_descriptor_->file()->FindExtensionByName(name + "_extension"); + } else { + result = base_descriptor_->FindFieldByName(name); + } + GOOGLE_CHECK(result != nullptr); + return result; +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ReflectionTester::SetAllFieldsViaReflection( + Message* message) { + const Reflection* reflection = message->GetReflection(); + Message* sub_message; + + reflection->SetInt32(message, F("optional_int32"), 101); + reflection->SetInt64(message, F("optional_int64"), 102); + reflection->SetUInt32(message, F("optional_uint32"), 103); + reflection->SetUInt64(message, F("optional_uint64"), 104); + reflection->SetInt32(message, F("optional_sint32"), 105); + reflection->SetInt64(message, F("optional_sint64"), 106); + reflection->SetUInt32(message, F("optional_fixed32"), 107); + reflection->SetUInt64(message, F("optional_fixed64"), 108); + reflection->SetInt32(message, F("optional_sfixed32"), 109); + reflection->SetInt64(message, F("optional_sfixed64"), 110); + reflection->SetFloat(message, F("optional_float"), 111); + reflection->SetDouble(message, F("optional_double"), 112); + reflection->SetBool(message, F("optional_bool"), true); + reflection->SetString(message, F("optional_string"), "115"); + reflection->SetString(message, F("optional_bytes"), "116"); + + sub_message = reflection->MutableMessage(message, F("optionalgroup")); + sub_message->GetReflection()->SetInt32(sub_message, group_a_, 117); + sub_message = + reflection->MutableMessage(message, F("optional_nested_message")); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 118); + sub_message = + reflection->MutableMessage(message, F("optional_foreign_message")); + sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 119); + sub_message = + reflection->MutableMessage(message, F("optional_import_message")); + sub_message->GetReflection()->SetInt32(sub_message, import_d_, 120); + + reflection->SetEnum(message, F("optional_nested_enum"), nested_baz_); + reflection->SetEnum(message, F("optional_foreign_enum"), foreign_baz_); + reflection->SetEnum(message, F("optional_import_enum"), import_baz_); + + reflection->SetString(message, F("optional_string_piece"), "124"); + reflection->SetString(message, F("optional_cord"), "125"); + + sub_message = + reflection->MutableMessage(message, F("optional_public_import_message")); + sub_message->GetReflection()->SetInt32(sub_message, import_e_, 126); + + sub_message = reflection->MutableMessage(message, F("optional_lazy_message")); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 127); + + // ----------------------------------------------------------------- + + reflection->AddInt32(message, F("repeated_int32"), 201); + reflection->AddInt64(message, F("repeated_int64"), 202); + reflection->AddUInt32(message, F("repeated_uint32"), 203); + reflection->AddUInt64(message, F("repeated_uint64"), 204); + reflection->AddInt32(message, F("repeated_sint32"), 205); + reflection->AddInt64(message, F("repeated_sint64"), 206); + reflection->AddUInt32(message, F("repeated_fixed32"), 207); + reflection->AddUInt64(message, F("repeated_fixed64"), 208); + reflection->AddInt32(message, F("repeated_sfixed32"), 209); + reflection->AddInt64(message, F("repeated_sfixed64"), 210); + reflection->AddFloat(message, F("repeated_float"), 211); + reflection->AddDouble(message, F("repeated_double"), 212); + reflection->AddBool(message, F("repeated_bool"), true); + reflection->AddString(message, F("repeated_string"), "215"); + reflection->AddString(message, F("repeated_bytes"), "216"); + + sub_message = reflection->AddMessage(message, F("repeatedgroup")); + sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 217); + sub_message = reflection->AddMessage(message, F("repeated_nested_message")); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 218); + sub_message = reflection->AddMessage(message, F("repeated_foreign_message")); + sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 219); + sub_message = reflection->AddMessage(message, F("repeated_import_message")); + sub_message->GetReflection()->SetInt32(sub_message, import_d_, 220); + sub_message = reflection->AddMessage(message, F("repeated_lazy_message")); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 227); + + reflection->AddEnum(message, F("repeated_nested_enum"), nested_bar_); + reflection->AddEnum(message, F("repeated_foreign_enum"), foreign_bar_); + reflection->AddEnum(message, F("repeated_import_enum"), import_bar_); + + reflection->AddString(message, F("repeated_string_piece"), "224"); + reflection->AddString(message, F("repeated_cord"), "225"); + + // Add a second one of each field. + reflection->AddInt32(message, F("repeated_int32"), 301); + reflection->AddInt64(message, F("repeated_int64"), 302); + reflection->AddUInt32(message, F("repeated_uint32"), 303); + reflection->AddUInt64(message, F("repeated_uint64"), 304); + reflection->AddInt32(message, F("repeated_sint32"), 305); + reflection->AddInt64(message, F("repeated_sint64"), 306); + reflection->AddUInt32(message, F("repeated_fixed32"), 307); + reflection->AddUInt64(message, F("repeated_fixed64"), 308); + reflection->AddInt32(message, F("repeated_sfixed32"), 309); + reflection->AddInt64(message, F("repeated_sfixed64"), 310); + reflection->AddFloat(message, F("repeated_float"), 311); + reflection->AddDouble(message, F("repeated_double"), 312); + reflection->AddBool(message, F("repeated_bool"), false); + reflection->AddString(message, F("repeated_string"), "315"); + reflection->AddString(message, F("repeated_bytes"), "316"); + + sub_message = reflection->AddMessage(message, F("repeatedgroup")); + sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 317); + sub_message = reflection->AddMessage(message, F("repeated_nested_message")); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 318); + sub_message = reflection->AddMessage(message, F("repeated_foreign_message")); + sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 319); + sub_message = reflection->AddMessage(message, F("repeated_import_message")); + sub_message->GetReflection()->SetInt32(sub_message, import_d_, 320); + sub_message = reflection->AddMessage(message, F("repeated_lazy_message")); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 327); + + reflection->AddEnum(message, F("repeated_nested_enum"), nested_baz_); + reflection->AddEnum(message, F("repeated_foreign_enum"), foreign_baz_); + reflection->AddEnum(message, F("repeated_import_enum"), import_baz_); + + reflection->AddString(message, F("repeated_string_piece"), "324"); + reflection->AddString(message, F("repeated_cord"), "325"); + + // ----------------------------------------------------------------- + + reflection->SetInt32(message, F("default_int32"), 401); + reflection->SetInt64(message, F("default_int64"), 402); + reflection->SetUInt32(message, F("default_uint32"), 403); + reflection->SetUInt64(message, F("default_uint64"), 404); + reflection->SetInt32(message, F("default_sint32"), 405); + reflection->SetInt64(message, F("default_sint64"), 406); + reflection->SetUInt32(message, F("default_fixed32"), 407); + reflection->SetUInt64(message, F("default_fixed64"), 408); + reflection->SetInt32(message, F("default_sfixed32"), 409); + reflection->SetInt64(message, F("default_sfixed64"), 410); + reflection->SetFloat(message, F("default_float"), 411); + reflection->SetDouble(message, F("default_double"), 412); + reflection->SetBool(message, F("default_bool"), false); + reflection->SetString(message, F("default_string"), "415"); + reflection->SetString(message, F("default_bytes"), "416"); + + reflection->SetEnum(message, F("default_nested_enum"), nested_foo_); + reflection->SetEnum(message, F("default_foreign_enum"), foreign_foo_); + reflection->SetEnum(message, F("default_import_enum"), import_foo_); + + reflection->SetString(message, F("default_string_piece"), "424"); + reflection->SetString(message, F("default_cord"), "425"); + + reflection->SetUInt32(message, F("oneof_uint32"), 601); + sub_message = reflection->MutableMessage(message, F("oneof_nested_message")); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 602); + reflection->SetString(message, F("oneof_string"), "603"); + reflection->SetString(message, F("oneof_bytes"), "604"); +} + +inline void TestUtil::ReflectionTester::SetOneofViaReflection( + Message* message) { + const Descriptor* descriptor = message->GetDescriptor(); + const Reflection* reflection = message->GetReflection(); + Message* sub_message = reflection->MutableMessage( + message, descriptor->FindFieldByName("foo_lazy_message")); + sub_message->GetReflection()->SetInt64( + sub_message, sub_message->GetDescriptor()->FindFieldByName("qux_int"), + 100); + + reflection->SetString(message, descriptor->FindFieldByName("bar_cord"), + "101"); + reflection->SetInt32(message, descriptor->FindFieldByName("baz_int"), 102); + reflection->SetString(message, descriptor->FindFieldByName("baz_string"), + "103"); +} + +inline void TestUtil::ReflectionTester::ExpectOneofSetViaReflection( + const Message& message) { + const Descriptor* descriptor = message.GetDescriptor(); + const Reflection* reflection = message.GetReflection(); + string scratch; + EXPECT_TRUE(reflection->HasField( + message, descriptor->FindFieldByName("foo_lazy_message"))); + EXPECT_TRUE( + reflection->HasField(message, descriptor->FindFieldByName("bar_cord"))); + EXPECT_TRUE( + reflection->HasField(message, descriptor->FindFieldByName("baz_int"))); + EXPECT_TRUE( + reflection->HasField(message, descriptor->FindFieldByName("baz_string"))); + + const Message* sub_message = &reflection->GetMessage( + message, descriptor->FindFieldByName("foo_lazy_message")); + EXPECT_EQ(100, sub_message->GetReflection()->GetInt64( + *sub_message, + sub_message->GetDescriptor()->FindFieldByName("qux_int"))); + + EXPECT_EQ("101", reflection->GetString( + message, descriptor->FindFieldByName("bar_cord"))); + EXPECT_EQ("101", + reflection->GetStringReference( + message, descriptor->FindFieldByName("bar_cord"), &scratch)); + + EXPECT_EQ(102, reflection->GetInt32(message, + descriptor->FindFieldByName("baz_int"))); + + EXPECT_EQ("103", reflection->GetString( + message, descriptor->FindFieldByName("baz_string"))); + EXPECT_EQ("103", + reflection->GetStringReference( + message, descriptor->FindFieldByName("baz_string"), &scratch)); +} + +inline void TestUtil::ReflectionTester::SetPackedFieldsViaReflection( + Message* message) { + const Reflection* reflection = message->GetReflection(); + reflection->AddInt32(message, F("packed_int32"), 601); + reflection->AddInt64(message, F("packed_int64"), 602); + reflection->AddUInt32(message, F("packed_uint32"), 603); + reflection->AddUInt64(message, F("packed_uint64"), 604); + reflection->AddInt32(message, F("packed_sint32"), 605); + reflection->AddInt64(message, F("packed_sint64"), 606); + reflection->AddUInt32(message, F("packed_fixed32"), 607); + reflection->AddUInt64(message, F("packed_fixed64"), 608); + reflection->AddInt32(message, F("packed_sfixed32"), 609); + reflection->AddInt64(message, F("packed_sfixed64"), 610); + reflection->AddFloat(message, F("packed_float"), 611); + reflection->AddDouble(message, F("packed_double"), 612); + reflection->AddBool(message, F("packed_bool"), true); + reflection->AddEnum(message, F("packed_enum"), foreign_bar_); + + reflection->AddInt32(message, F("packed_int32"), 701); + reflection->AddInt64(message, F("packed_int64"), 702); + reflection->AddUInt32(message, F("packed_uint32"), 703); + reflection->AddUInt64(message, F("packed_uint64"), 704); + reflection->AddInt32(message, F("packed_sint32"), 705); + reflection->AddInt64(message, F("packed_sint64"), 706); + reflection->AddUInt32(message, F("packed_fixed32"), 707); + reflection->AddUInt64(message, F("packed_fixed64"), 708); + reflection->AddInt32(message, F("packed_sfixed32"), 709); + reflection->AddInt64(message, F("packed_sfixed64"), 710); + reflection->AddFloat(message, F("packed_float"), 711); + reflection->AddDouble(message, F("packed_double"), 712); + reflection->AddBool(message, F("packed_bool"), false); + reflection->AddEnum(message, F("packed_enum"), foreign_baz_); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection( + const Message& message) { + // We have to split this into three function otherwise it creates a stack + // frame so large that it triggers a warning. + ExpectAllFieldsSetViaReflection1(message); + ExpectAllFieldsSetViaReflection2(message); + ExpectAllFieldsSetViaReflection3(message); +} + +inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection1( + const Message& message) { + const Reflection* reflection = message.GetReflection(); + string scratch; + const Message* sub_message; + + EXPECT_TRUE(reflection->HasField(message, F("optional_int32"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_int64"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_uint32"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_uint64"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_sint32"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_sint64"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_fixed32"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_fixed64"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_sfixed32"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_sfixed64"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_float"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_double"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_bool"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_string"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_bytes"))); + + EXPECT_TRUE(reflection->HasField(message, F("optionalgroup"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_nested_message"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_foreign_message"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_import_message"))); + EXPECT_TRUE( + reflection->HasField(message, F("optional_public_import_message"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_lazy_message"))); + + sub_message = &reflection->GetMessage(message, F("optionalgroup")); + EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, group_a_)); + sub_message = &reflection->GetMessage(message, F("optional_nested_message")); + EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); + sub_message = &reflection->GetMessage(message, F("optional_foreign_message")); + EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, foreign_c_)); + sub_message = &reflection->GetMessage(message, F("optional_import_message")); + EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, import_d_)); + sub_message = + &reflection->GetMessage(message, F("optional_public_import_message")); + EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, import_e_)); + sub_message = &reflection->GetMessage(message, F("optional_lazy_message")); + EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); + + EXPECT_TRUE(reflection->HasField(message, F("optional_nested_enum"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_foreign_enum"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_import_enum"))); + + EXPECT_TRUE(reflection->HasField(message, F("optional_string_piece"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_cord"))); + + EXPECT_EQ(101, reflection->GetInt32(message, F("optional_int32"))); + EXPECT_EQ(102, reflection->GetInt64(message, F("optional_int64"))); + EXPECT_EQ(103, reflection->GetUInt32(message, F("optional_uint32"))); + EXPECT_EQ(104, reflection->GetUInt64(message, F("optional_uint64"))); + EXPECT_EQ(105, reflection->GetInt32(message, F("optional_sint32"))); + EXPECT_EQ(106, reflection->GetInt64(message, F("optional_sint64"))); + EXPECT_EQ(107, reflection->GetUInt32(message, F("optional_fixed32"))); + EXPECT_EQ(108, reflection->GetUInt64(message, F("optional_fixed64"))); + EXPECT_EQ(109, reflection->GetInt32(message, F("optional_sfixed32"))); + EXPECT_EQ(110, reflection->GetInt64(message, F("optional_sfixed64"))); + EXPECT_EQ(111, reflection->GetFloat(message, F("optional_float"))); + EXPECT_EQ(112, reflection->GetDouble(message, F("optional_double"))); + EXPECT_TRUE(reflection->GetBool(message, F("optional_bool"))); + EXPECT_EQ("115", reflection->GetString(message, F("optional_string"))); + EXPECT_EQ("116", reflection->GetString(message, F("optional_bytes"))); + + EXPECT_EQ("115", reflection->GetStringReference(message, F("optional_string"), + &scratch)); + EXPECT_EQ("116", reflection->GetStringReference(message, F("optional_bytes"), + &scratch)); + + sub_message = &reflection->GetMessage(message, F("optionalgroup")); + EXPECT_EQ(117, + sub_message->GetReflection()->GetInt32(*sub_message, group_a_)); + sub_message = &reflection->GetMessage(message, F("optional_nested_message")); + EXPECT_EQ(118, + sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + sub_message = &reflection->GetMessage(message, F("optional_foreign_message")); + EXPECT_EQ(119, + sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); + sub_message = &reflection->GetMessage(message, F("optional_import_message")); + EXPECT_EQ(120, + sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); + sub_message = + &reflection->GetMessage(message, F("optional_public_import_message")); + EXPECT_EQ(126, + sub_message->GetReflection()->GetInt32(*sub_message, import_e_)); + sub_message = &reflection->GetMessage(message, F("optional_lazy_message")); + EXPECT_EQ(127, + sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + + EXPECT_EQ(nested_baz_, + reflection->GetEnum(message, F("optional_nested_enum"))); + EXPECT_EQ(foreign_baz_, + reflection->GetEnum(message, F("optional_foreign_enum"))); + EXPECT_EQ(import_baz_, + reflection->GetEnum(message, F("optional_import_enum"))); + + EXPECT_EQ("124", reflection->GetString(message, F("optional_string_piece"))); + EXPECT_EQ("124", reflection->GetStringReference( + message, F("optional_string_piece"), &scratch)); + + EXPECT_EQ("125", reflection->GetString(message, F("optional_cord"))); + EXPECT_EQ("125", reflection->GetStringReference(message, F("optional_cord"), + &scratch)); + + EXPECT_TRUE(reflection->HasField(message, F("oneof_bytes"))); + EXPECT_EQ("604", reflection->GetString(message, F("oneof_bytes"))); + + if (base_descriptor_->name() == "TestAllTypes") { + EXPECT_FALSE(reflection->HasField(message, F("oneof_uint32"))); + EXPECT_FALSE(reflection->HasField(message, F("oneof_string"))); + } else { + EXPECT_TRUE(reflection->HasField(message, F("oneof_uint32"))); + EXPECT_TRUE(reflection->HasField(message, F("oneof_string"))); + EXPECT_EQ(601, reflection->GetUInt32(message, F("oneof_uint32"))); + EXPECT_EQ("603", reflection->GetString(message, F("oneof_string"))); + sub_message = &reflection->GetMessage(message, F("oneof_nested_message")); + EXPECT_EQ(602, + sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + } +} + +inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection2( + const Message& message) { + const Reflection* reflection = message.GetReflection(); + string scratch; + const Message* sub_message; + + // ----------------------------------------------------------------- + + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_int32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_int64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_uint32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_uint64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sint32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sint64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_fixed32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_fixed64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sfixed32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sfixed64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_float"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_double"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_bool"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_string"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_bytes"))); + + ASSERT_EQ(2, reflection->FieldSize(message, F("repeatedgroup"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_nested_message"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_foreign_message"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_import_message"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_lazy_message"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_nested_enum"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_foreign_enum"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_import_enum"))); + + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_string_piece"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_cord"))); + + EXPECT_EQ(201, reflection->GetRepeatedInt32(message, F("repeated_int32"), 0)); + EXPECT_EQ(202, reflection->GetRepeatedInt64(message, F("repeated_int64"), 0)); + EXPECT_EQ(203, + reflection->GetRepeatedUInt32(message, F("repeated_uint32"), 0)); + EXPECT_EQ(204, + reflection->GetRepeatedUInt64(message, F("repeated_uint64"), 0)); + EXPECT_EQ(205, + reflection->GetRepeatedInt32(message, F("repeated_sint32"), 0)); + EXPECT_EQ(206, + reflection->GetRepeatedInt64(message, F("repeated_sint64"), 0)); + EXPECT_EQ(207, + reflection->GetRepeatedUInt32(message, F("repeated_fixed32"), 0)); + EXPECT_EQ(208, + reflection->GetRepeatedUInt64(message, F("repeated_fixed64"), 0)); + EXPECT_EQ(209, + reflection->GetRepeatedInt32(message, F("repeated_sfixed32"), 0)); + EXPECT_EQ(210, + reflection->GetRepeatedInt64(message, F("repeated_sfixed64"), 0)); + EXPECT_EQ(211, reflection->GetRepeatedFloat(message, F("repeated_float"), 0)); + EXPECT_EQ(212, + reflection->GetRepeatedDouble(message, F("repeated_double"), 0)); + EXPECT_TRUE(reflection->GetRepeatedBool(message, F("repeated_bool"), 0)); + EXPECT_EQ("215", + reflection->GetRepeatedString(message, F("repeated_string"), 0)); + EXPECT_EQ("216", + reflection->GetRepeatedString(message, F("repeated_bytes"), 0)); + + EXPECT_EQ("215", reflection->GetRepeatedStringReference( + message, F("repeated_string"), 0, &scratch)); + EXPECT_EQ("216", reflection->GetRepeatedStringReference( + message, F("repeated_bytes"), 0, &scratch)); + + sub_message = &reflection->GetRepeatedMessage(message, F("repeatedgroup"), 0); + EXPECT_EQ(217, sub_message->GetReflection()->GetInt32(*sub_message, + repeated_group_a_)); + sub_message = + &reflection->GetRepeatedMessage(message, F("repeated_nested_message"), 0); + EXPECT_EQ(218, + sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + sub_message = &reflection->GetRepeatedMessage( + message, F("repeated_foreign_message"), 0); + EXPECT_EQ(219, + sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); + sub_message = + &reflection->GetRepeatedMessage(message, F("repeated_import_message"), 0); + EXPECT_EQ(220, + sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); + sub_message = + &reflection->GetRepeatedMessage(message, F("repeated_lazy_message"), 0); + EXPECT_EQ(227, + sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + + EXPECT_EQ(nested_bar_, + reflection->GetRepeatedEnum(message, F("repeated_nested_enum"), 0)); + EXPECT_EQ(foreign_bar_, reflection->GetRepeatedEnum( + message, F("repeated_foreign_enum"), 0)); + EXPECT_EQ(import_bar_, + reflection->GetRepeatedEnum(message, F("repeated_import_enum"), 0)); + + EXPECT_EQ("224", reflection->GetRepeatedString( + message, F("repeated_string_piece"), 0)); + EXPECT_EQ("224", reflection->GetRepeatedStringReference( + message, F("repeated_string_piece"), 0, &scratch)); + + EXPECT_EQ("225", + reflection->GetRepeatedString(message, F("repeated_cord"), 0)); + EXPECT_EQ("225", reflection->GetRepeatedStringReference( + message, F("repeated_cord"), 0, &scratch)); + + EXPECT_EQ(301, reflection->GetRepeatedInt32(message, F("repeated_int32"), 1)); + EXPECT_EQ(302, reflection->GetRepeatedInt64(message, F("repeated_int64"), 1)); + EXPECT_EQ(303, + reflection->GetRepeatedUInt32(message, F("repeated_uint32"), 1)); + EXPECT_EQ(304, + reflection->GetRepeatedUInt64(message, F("repeated_uint64"), 1)); + EXPECT_EQ(305, + reflection->GetRepeatedInt32(message, F("repeated_sint32"), 1)); + EXPECT_EQ(306, + reflection->GetRepeatedInt64(message, F("repeated_sint64"), 1)); + EXPECT_EQ(307, + reflection->GetRepeatedUInt32(message, F("repeated_fixed32"), 1)); + EXPECT_EQ(308, + reflection->GetRepeatedUInt64(message, F("repeated_fixed64"), 1)); + EXPECT_EQ(309, + reflection->GetRepeatedInt32(message, F("repeated_sfixed32"), 1)); + EXPECT_EQ(310, + reflection->GetRepeatedInt64(message, F("repeated_sfixed64"), 1)); + EXPECT_EQ(311, reflection->GetRepeatedFloat(message, F("repeated_float"), 1)); + EXPECT_EQ(312, + reflection->GetRepeatedDouble(message, F("repeated_double"), 1)); + EXPECT_FALSE(reflection->GetRepeatedBool(message, F("repeated_bool"), 1)); + EXPECT_EQ("315", + reflection->GetRepeatedString(message, F("repeated_string"), 1)); + EXPECT_EQ("316", + reflection->GetRepeatedString(message, F("repeated_bytes"), 1)); + + EXPECT_EQ("315", reflection->GetRepeatedStringReference( + message, F("repeated_string"), 1, &scratch)); + EXPECT_EQ("316", reflection->GetRepeatedStringReference( + message, F("repeated_bytes"), 1, &scratch)); + + sub_message = &reflection->GetRepeatedMessage(message, F("repeatedgroup"), 1); + EXPECT_EQ(317, sub_message->GetReflection()->GetInt32(*sub_message, + repeated_group_a_)); + sub_message = + &reflection->GetRepeatedMessage(message, F("repeated_nested_message"), 1); + EXPECT_EQ(318, + sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + sub_message = &reflection->GetRepeatedMessage( + message, F("repeated_foreign_message"), 1); + EXPECT_EQ(319, + sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); + sub_message = + &reflection->GetRepeatedMessage(message, F("repeated_import_message"), 1); + EXPECT_EQ(320, + sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); + sub_message = + &reflection->GetRepeatedMessage(message, F("repeated_lazy_message"), 1); + EXPECT_EQ(327, + sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + + EXPECT_EQ(nested_baz_, + reflection->GetRepeatedEnum(message, F("repeated_nested_enum"), 1)); + EXPECT_EQ(foreign_baz_, reflection->GetRepeatedEnum( + message, F("repeated_foreign_enum"), 1)); + EXPECT_EQ(import_baz_, + reflection->GetRepeatedEnum(message, F("repeated_import_enum"), 1)); + + EXPECT_EQ("324", reflection->GetRepeatedString( + message, F("repeated_string_piece"), 1)); + EXPECT_EQ("324", reflection->GetRepeatedStringReference( + message, F("repeated_string_piece"), 1, &scratch)); + + EXPECT_EQ("325", + reflection->GetRepeatedString(message, F("repeated_cord"), 1)); + EXPECT_EQ("325", reflection->GetRepeatedStringReference( + message, F("repeated_cord"), 1, &scratch)); +} + +inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection3( + const Message& message) { + const Reflection* reflection = message.GetReflection(); + string scratch; + + // ----------------------------------------------------------------- + + EXPECT_TRUE(reflection->HasField(message, F("default_int32"))); + EXPECT_TRUE(reflection->HasField(message, F("default_int64"))); + EXPECT_TRUE(reflection->HasField(message, F("default_uint32"))); + EXPECT_TRUE(reflection->HasField(message, F("default_uint64"))); + EXPECT_TRUE(reflection->HasField(message, F("default_sint32"))); + EXPECT_TRUE(reflection->HasField(message, F("default_sint64"))); + EXPECT_TRUE(reflection->HasField(message, F("default_fixed32"))); + EXPECT_TRUE(reflection->HasField(message, F("default_fixed64"))); + EXPECT_TRUE(reflection->HasField(message, F("default_sfixed32"))); + EXPECT_TRUE(reflection->HasField(message, F("default_sfixed64"))); + EXPECT_TRUE(reflection->HasField(message, F("default_float"))); + EXPECT_TRUE(reflection->HasField(message, F("default_double"))); + EXPECT_TRUE(reflection->HasField(message, F("default_bool"))); + EXPECT_TRUE(reflection->HasField(message, F("default_string"))); + EXPECT_TRUE(reflection->HasField(message, F("default_bytes"))); + + EXPECT_TRUE(reflection->HasField(message, F("default_nested_enum"))); + EXPECT_TRUE(reflection->HasField(message, F("default_foreign_enum"))); + EXPECT_TRUE(reflection->HasField(message, F("default_import_enum"))); + + EXPECT_TRUE(reflection->HasField(message, F("default_string_piece"))); + EXPECT_TRUE(reflection->HasField(message, F("default_cord"))); + + EXPECT_EQ(401, reflection->GetInt32(message, F("default_int32"))); + EXPECT_EQ(402, reflection->GetInt64(message, F("default_int64"))); + EXPECT_EQ(403, reflection->GetUInt32(message, F("default_uint32"))); + EXPECT_EQ(404, reflection->GetUInt64(message, F("default_uint64"))); + EXPECT_EQ(405, reflection->GetInt32(message, F("default_sint32"))); + EXPECT_EQ(406, reflection->GetInt64(message, F("default_sint64"))); + EXPECT_EQ(407, reflection->GetUInt32(message, F("default_fixed32"))); + EXPECT_EQ(408, reflection->GetUInt64(message, F("default_fixed64"))); + EXPECT_EQ(409, reflection->GetInt32(message, F("default_sfixed32"))); + EXPECT_EQ(410, reflection->GetInt64(message, F("default_sfixed64"))); + EXPECT_EQ(411, reflection->GetFloat(message, F("default_float"))); + EXPECT_EQ(412, reflection->GetDouble(message, F("default_double"))); + EXPECT_FALSE(reflection->GetBool(message, F("default_bool"))); + EXPECT_EQ("415", reflection->GetString(message, F("default_string"))); + EXPECT_EQ("416", reflection->GetString(message, F("default_bytes"))); + + EXPECT_EQ("415", reflection->GetStringReference(message, F("default_string"), + &scratch)); + EXPECT_EQ("416", reflection->GetStringReference(message, F("default_bytes"), + &scratch)); + + EXPECT_EQ(nested_foo_, + reflection->GetEnum(message, F("default_nested_enum"))); + EXPECT_EQ(foreign_foo_, + reflection->GetEnum(message, F("default_foreign_enum"))); + EXPECT_EQ(import_foo_, + reflection->GetEnum(message, F("default_import_enum"))); + + EXPECT_EQ("424", reflection->GetString(message, F("default_string_piece"))); + EXPECT_EQ("424", reflection->GetStringReference( + message, F("default_string_piece"), &scratch)); + + EXPECT_EQ("425", reflection->GetString(message, F("default_cord"))); + EXPECT_EQ("425", reflection->GetStringReference(message, F("default_cord"), + &scratch)); +} + +inline void TestUtil::ReflectionTester::ExpectPackedFieldsSetViaReflection( + const Message& message) { + const Reflection* reflection = message.GetReflection(); + + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_int32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_int64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_uint32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_uint64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sint32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sint64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_fixed32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_fixed64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sfixed32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sfixed64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_float"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_double"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_bool"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_enum"))); + + EXPECT_EQ(601, reflection->GetRepeatedInt32(message, F("packed_int32"), 0)); + EXPECT_EQ(602, reflection->GetRepeatedInt64(message, F("packed_int64"), 0)); + EXPECT_EQ(603, reflection->GetRepeatedUInt32(message, F("packed_uint32"), 0)); + EXPECT_EQ(604, reflection->GetRepeatedUInt64(message, F("packed_uint64"), 0)); + EXPECT_EQ(605, reflection->GetRepeatedInt32(message, F("packed_sint32"), 0)); + EXPECT_EQ(606, reflection->GetRepeatedInt64(message, F("packed_sint64"), 0)); + EXPECT_EQ(607, + reflection->GetRepeatedUInt32(message, F("packed_fixed32"), 0)); + EXPECT_EQ(608, + reflection->GetRepeatedUInt64(message, F("packed_fixed64"), 0)); + EXPECT_EQ(609, + reflection->GetRepeatedInt32(message, F("packed_sfixed32"), 0)); + EXPECT_EQ(610, + reflection->GetRepeatedInt64(message, F("packed_sfixed64"), 0)); + EXPECT_EQ(611, reflection->GetRepeatedFloat(message, F("packed_float"), 0)); + EXPECT_EQ(612, reflection->GetRepeatedDouble(message, F("packed_double"), 0)); + EXPECT_TRUE(reflection->GetRepeatedBool(message, F("packed_bool"), 0)); + EXPECT_EQ(foreign_bar_, + reflection->GetRepeatedEnum(message, F("packed_enum"), 0)); + + EXPECT_EQ(701, reflection->GetRepeatedInt32(message, F("packed_int32"), 1)); + EXPECT_EQ(702, reflection->GetRepeatedInt64(message, F("packed_int64"), 1)); + EXPECT_EQ(703, reflection->GetRepeatedUInt32(message, F("packed_uint32"), 1)); + EXPECT_EQ(704, reflection->GetRepeatedUInt64(message, F("packed_uint64"), 1)); + EXPECT_EQ(705, reflection->GetRepeatedInt32(message, F("packed_sint32"), 1)); + EXPECT_EQ(706, reflection->GetRepeatedInt64(message, F("packed_sint64"), 1)); + EXPECT_EQ(707, + reflection->GetRepeatedUInt32(message, F("packed_fixed32"), 1)); + EXPECT_EQ(708, + reflection->GetRepeatedUInt64(message, F("packed_fixed64"), 1)); + EXPECT_EQ(709, + reflection->GetRepeatedInt32(message, F("packed_sfixed32"), 1)); + EXPECT_EQ(710, + reflection->GetRepeatedInt64(message, F("packed_sfixed64"), 1)); + EXPECT_EQ(711, reflection->GetRepeatedFloat(message, F("packed_float"), 1)); + EXPECT_EQ(712, reflection->GetRepeatedDouble(message, F("packed_double"), 1)); + EXPECT_FALSE(reflection->GetRepeatedBool(message, F("packed_bool"), 1)); + EXPECT_EQ(foreign_baz_, + reflection->GetRepeatedEnum(message, F("packed_enum"), 1)); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ReflectionTester::ExpectClearViaReflection( + const Message& message) { + const Reflection* reflection = message.GetReflection(); + string scratch; + const Message* sub_message; + + // has_blah() should initially be false for all optional fields. + EXPECT_FALSE(reflection->HasField(message, F("optional_int32"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_int64"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_uint32"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_uint64"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_sint32"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_sint64"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_fixed32"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_fixed64"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_sfixed32"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_sfixed64"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_float"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_double"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_bool"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_string"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_bytes"))); + + EXPECT_FALSE(reflection->HasField(message, F("optionalgroup"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_nested_message"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_foreign_message"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_import_message"))); + EXPECT_FALSE( + reflection->HasField(message, F("optional_public_import_message"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_lazy_message"))); + + EXPECT_FALSE(reflection->HasField(message, F("optional_nested_enum"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_foreign_enum"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_import_enum"))); + + EXPECT_FALSE(reflection->HasField(message, F("optional_string_piece"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_cord"))); + + // Optional fields without defaults are set to zero or something like it. + EXPECT_EQ(0, reflection->GetInt32(message, F("optional_int32"))); + EXPECT_EQ(0, reflection->GetInt64(message, F("optional_int64"))); + EXPECT_EQ(0, reflection->GetUInt32(message, F("optional_uint32"))); + EXPECT_EQ(0, reflection->GetUInt64(message, F("optional_uint64"))); + EXPECT_EQ(0, reflection->GetInt32(message, F("optional_sint32"))); + EXPECT_EQ(0, reflection->GetInt64(message, F("optional_sint64"))); + EXPECT_EQ(0, reflection->GetUInt32(message, F("optional_fixed32"))); + EXPECT_EQ(0, reflection->GetUInt64(message, F("optional_fixed64"))); + EXPECT_EQ(0, reflection->GetInt32(message, F("optional_sfixed32"))); + EXPECT_EQ(0, reflection->GetInt64(message, F("optional_sfixed64"))); + EXPECT_EQ(0, reflection->GetFloat(message, F("optional_float"))); + EXPECT_EQ(0, reflection->GetDouble(message, F("optional_double"))); + EXPECT_FALSE(reflection->GetBool(message, F("optional_bool"))); + EXPECT_EQ("", reflection->GetString(message, F("optional_string"))); + EXPECT_EQ("", reflection->GetString(message, F("optional_bytes"))); + + EXPECT_EQ("", reflection->GetStringReference(message, F("optional_string"), + &scratch)); + EXPECT_EQ("", reflection->GetStringReference(message, F("optional_bytes"), + &scratch)); + + // Embedded messages should also be clear. + sub_message = &reflection->GetMessage(message, F("optionalgroup")); + EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, group_a_)); + EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, group_a_)); + sub_message = &reflection->GetMessage(message, F("optional_nested_message")); + EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); + EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + sub_message = &reflection->GetMessage(message, F("optional_foreign_message")); + EXPECT_FALSE( + sub_message->GetReflection()->HasField(*sub_message, foreign_c_)); + EXPECT_EQ(0, + sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); + sub_message = &reflection->GetMessage(message, F("optional_import_message")); + EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, import_d_)); + EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); + sub_message = + &reflection->GetMessage(message, F("optional_public_import_message")); + EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, import_e_)); + EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, import_e_)); + sub_message = &reflection->GetMessage(message, F("optional_lazy_message")); + EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); + EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + + // Enums without defaults are set to the first value in the enum. + EXPECT_EQ(nested_foo_, + reflection->GetEnum(message, F("optional_nested_enum"))); + EXPECT_EQ(foreign_foo_, + reflection->GetEnum(message, F("optional_foreign_enum"))); + EXPECT_EQ(import_foo_, + reflection->GetEnum(message, F("optional_import_enum"))); + + EXPECT_EQ("", reflection->GetString(message, F("optional_string_piece"))); + EXPECT_EQ("", reflection->GetStringReference( + message, F("optional_string_piece"), &scratch)); + + EXPECT_EQ("", reflection->GetString(message, F("optional_cord"))); + EXPECT_EQ("", reflection->GetStringReference(message, F("optional_cord"), + &scratch)); + + // Repeated fields are empty. + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_int32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_int64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_uint32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_uint64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sint32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sint64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_fixed32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_fixed64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sfixed32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sfixed64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_float"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_double"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_bool"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_string"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_bytes"))); + + EXPECT_EQ(0, reflection->FieldSize(message, F("repeatedgroup"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_nested_message"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_foreign_message"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_import_message"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_lazy_message"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_nested_enum"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_foreign_enum"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_import_enum"))); + + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_string_piece"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_cord"))); + + // has_blah() should also be false for all default fields. + EXPECT_FALSE(reflection->HasField(message, F("default_int32"))); + EXPECT_FALSE(reflection->HasField(message, F("default_int64"))); + EXPECT_FALSE(reflection->HasField(message, F("default_uint32"))); + EXPECT_FALSE(reflection->HasField(message, F("default_uint64"))); + EXPECT_FALSE(reflection->HasField(message, F("default_sint32"))); + EXPECT_FALSE(reflection->HasField(message, F("default_sint64"))); + EXPECT_FALSE(reflection->HasField(message, F("default_fixed32"))); + EXPECT_FALSE(reflection->HasField(message, F("default_fixed64"))); + EXPECT_FALSE(reflection->HasField(message, F("default_sfixed32"))); + EXPECT_FALSE(reflection->HasField(message, F("default_sfixed64"))); + EXPECT_FALSE(reflection->HasField(message, F("default_float"))); + EXPECT_FALSE(reflection->HasField(message, F("default_double"))); + EXPECT_FALSE(reflection->HasField(message, F("default_bool"))); + EXPECT_FALSE(reflection->HasField(message, F("default_string"))); + EXPECT_FALSE(reflection->HasField(message, F("default_bytes"))); + + EXPECT_FALSE(reflection->HasField(message, F("default_nested_enum"))); + EXPECT_FALSE(reflection->HasField(message, F("default_foreign_enum"))); + EXPECT_FALSE(reflection->HasField(message, F("default_import_enum"))); + + EXPECT_FALSE(reflection->HasField(message, F("default_string_piece"))); + EXPECT_FALSE(reflection->HasField(message, F("default_cord"))); + + // Fields with defaults have their default values (duh). + EXPECT_EQ(41, reflection->GetInt32(message, F("default_int32"))); + EXPECT_EQ(42, reflection->GetInt64(message, F("default_int64"))); + EXPECT_EQ(43, reflection->GetUInt32(message, F("default_uint32"))); + EXPECT_EQ(44, reflection->GetUInt64(message, F("default_uint64"))); + EXPECT_EQ(-45, reflection->GetInt32(message, F("default_sint32"))); + EXPECT_EQ(46, reflection->GetInt64(message, F("default_sint64"))); + EXPECT_EQ(47, reflection->GetUInt32(message, F("default_fixed32"))); + EXPECT_EQ(48, reflection->GetUInt64(message, F("default_fixed64"))); + EXPECT_EQ(49, reflection->GetInt32(message, F("default_sfixed32"))); + EXPECT_EQ(-50, reflection->GetInt64(message, F("default_sfixed64"))); + EXPECT_EQ(51.5, reflection->GetFloat(message, F("default_float"))); + EXPECT_EQ(52e3, reflection->GetDouble(message, F("default_double"))); + EXPECT_TRUE(reflection->GetBool(message, F("default_bool"))); + EXPECT_EQ("hello", reflection->GetString(message, F("default_string"))); + EXPECT_EQ("world", reflection->GetString(message, F("default_bytes"))); + + EXPECT_EQ("hello", reflection->GetStringReference( + message, F("default_string"), &scratch)); + EXPECT_EQ("world", reflection->GetStringReference(message, F("default_bytes"), + &scratch)); + + EXPECT_EQ(nested_bar_, + reflection->GetEnum(message, F("default_nested_enum"))); + EXPECT_EQ(foreign_bar_, + reflection->GetEnum(message, F("default_foreign_enum"))); + EXPECT_EQ(import_bar_, + reflection->GetEnum(message, F("default_import_enum"))); + + EXPECT_EQ("abc", reflection->GetString(message, F("default_string_piece"))); + EXPECT_EQ("abc", reflection->GetStringReference( + message, F("default_string_piece"), &scratch)); + + EXPECT_EQ("123", reflection->GetString(message, F("default_cord"))); + EXPECT_EQ("123", reflection->GetStringReference(message, F("default_cord"), + &scratch)); +} + +inline void TestUtil::ReflectionTester::ExpectPackedClearViaReflection( + const Message& message) { + const Reflection* reflection = message.GetReflection(); + + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_int32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_int64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_uint32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_uint64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sint32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sint64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_fixed32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_fixed64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sfixed32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sfixed64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_float"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_double"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_bool"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_enum"))); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ReflectionTester::ModifyRepeatedFieldsViaReflection( + Message* message) { + const Reflection* reflection = message->GetReflection(); + Message* sub_message; + + reflection->SetRepeatedInt32(message, F("repeated_int32"), 1, 501); + reflection->SetRepeatedInt64(message, F("repeated_int64"), 1, 502); + reflection->SetRepeatedUInt32(message, F("repeated_uint32"), 1, 503); + reflection->SetRepeatedUInt64(message, F("repeated_uint64"), 1, 504); + reflection->SetRepeatedInt32(message, F("repeated_sint32"), 1, 505); + reflection->SetRepeatedInt64(message, F("repeated_sint64"), 1, 506); + reflection->SetRepeatedUInt32(message, F("repeated_fixed32"), 1, 507); + reflection->SetRepeatedUInt64(message, F("repeated_fixed64"), 1, 508); + reflection->SetRepeatedInt32(message, F("repeated_sfixed32"), 1, 509); + reflection->SetRepeatedInt64(message, F("repeated_sfixed64"), 1, 510); + reflection->SetRepeatedFloat(message, F("repeated_float"), 1, 511); + reflection->SetRepeatedDouble(message, F("repeated_double"), 1, 512); + reflection->SetRepeatedBool(message, F("repeated_bool"), 1, true); + reflection->SetRepeatedString(message, F("repeated_string"), 1, "515"); + reflection->SetRepeatedString(message, F("repeated_bytes"), 1, "516"); + + sub_message = + reflection->MutableRepeatedMessage(message, F("repeatedgroup"), 1); + sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 517); + sub_message = reflection->MutableRepeatedMessage( + message, F("repeated_nested_message"), 1); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 518); + sub_message = reflection->MutableRepeatedMessage( + message, F("repeated_foreign_message"), 1); + sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 519); + sub_message = reflection->MutableRepeatedMessage( + message, F("repeated_import_message"), 1); + sub_message->GetReflection()->SetInt32(sub_message, import_d_, 520); + sub_message = reflection->MutableRepeatedMessage( + message, F("repeated_lazy_message"), 1); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 527); + + reflection->SetRepeatedEnum(message, F("repeated_nested_enum"), 1, + nested_foo_); + reflection->SetRepeatedEnum(message, F("repeated_foreign_enum"), 1, + foreign_foo_); + reflection->SetRepeatedEnum(message, F("repeated_import_enum"), 1, + import_foo_); + + reflection->SetRepeatedString(message, F("repeated_string_piece"), 1, "524"); + reflection->SetRepeatedString(message, F("repeated_cord"), 1, "525"); +} + +inline void TestUtil::ReflectionTester::ModifyPackedFieldsViaReflection( + Message* message) { + const Reflection* reflection = message->GetReflection(); + reflection->SetRepeatedInt32(message, F("packed_int32"), 1, 801); + reflection->SetRepeatedInt64(message, F("packed_int64"), 1, 802); + reflection->SetRepeatedUInt32(message, F("packed_uint32"), 1, 803); + reflection->SetRepeatedUInt64(message, F("packed_uint64"), 1, 804); + reflection->SetRepeatedInt32(message, F("packed_sint32"), 1, 805); + reflection->SetRepeatedInt64(message, F("packed_sint64"), 1, 806); + reflection->SetRepeatedUInt32(message, F("packed_fixed32"), 1, 807); + reflection->SetRepeatedUInt64(message, F("packed_fixed64"), 1, 808); + reflection->SetRepeatedInt32(message, F("packed_sfixed32"), 1, 809); + reflection->SetRepeatedInt64(message, F("packed_sfixed64"), 1, 810); + reflection->SetRepeatedFloat(message, F("packed_float"), 1, 811); + reflection->SetRepeatedDouble(message, F("packed_double"), 1, 812); + reflection->SetRepeatedBool(message, F("packed_bool"), 1, true); + reflection->SetRepeatedEnum(message, F("packed_enum"), 1, foreign_foo_); +} + +inline void TestUtil::ReflectionTester::RemoveLastRepeatedsViaReflection( + Message* message) { + const Reflection* reflection = message->GetReflection(); + + std::vector<const FieldDescriptor*> output; + reflection->ListFields(*message, &output); + for (int i = 0; i < output.size(); ++i) { + const FieldDescriptor* field = output[i]; + if (!field->is_repeated()) continue; + + reflection->RemoveLast(message, field); + } +} + +inline void TestUtil::ReflectionTester::ReleaseLastRepeatedsViaReflection( + Message* message, bool expect_extensions_notnull) { + const Reflection* reflection = message->GetReflection(); + + std::vector<const FieldDescriptor*> output; + reflection->ListFields(*message, &output); + for (int i = 0; i < output.size(); ++i) { + const FieldDescriptor* field = output[i]; + if (!field->is_repeated()) continue; + if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) continue; + + Message* released = reflection->ReleaseLast(message, field); + if (!field->is_extension() || expect_extensions_notnull) { + ASSERT_TRUE(released != nullptr) + << "ReleaseLast returned nullptr for: " << field->name(); + } + delete released; + } +} + +inline void TestUtil::ReflectionTester::SwapRepeatedsViaReflection( + Message* message) { + const Reflection* reflection = message->GetReflection(); + + std::vector<const FieldDescriptor*> output; + reflection->ListFields(*message, &output); + for (int i = 0; i < output.size(); ++i) { + const FieldDescriptor* field = output[i]; + if (!field->is_repeated()) continue; + + reflection->SwapElements(message, field, 0, 1); + } +} + +inline void TestUtil::ReflectionTester:: + SetAllocatedOptionalMessageFieldsToNullViaReflection(Message* message) { + const Reflection* reflection = message->GetReflection(); + + std::vector<const FieldDescriptor*> fields; + reflection->ListFields(*message, &fields); + + for (int i = 0; i < fields.size(); ++i) { + const FieldDescriptor* field = fields[i]; + if (!field->is_optional() || + field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) + continue; + + reflection->SetAllocatedMessage(message, nullptr, field); + } +} + +inline void TestUtil::ReflectionTester:: + SetAllocatedOptionalMessageFieldsToMessageViaReflection( + Message* from_message, Message* to_message) { + EXPECT_EQ(from_message->GetDescriptor(), to_message->GetDescriptor()); + const Reflection* from_reflection = from_message->GetReflection(); + const Reflection* to_reflection = to_message->GetReflection(); + + std::vector<const FieldDescriptor*> fields; + from_reflection->ListFields(*from_message, &fields); + + for (int i = 0; i < fields.size(); ++i) { + const FieldDescriptor* field = fields[i]; + if (!field->is_optional() || + field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) + continue; + + Message* sub_message = from_reflection->ReleaseMessage(from_message, field); + to_reflection->SetAllocatedMessage(to_message, sub_message, field); + } +} + +inline void TestUtil::ReflectionTester::ExpectMessagesReleasedViaReflection( + Message* message, + TestUtil::ReflectionTester::MessageReleaseState expected_release_state) { + const Reflection* reflection = message->GetReflection(); + + static const char* fields[] = { + "optionalgroup", + "optional_nested_message", + "optional_foreign_message", + "optional_import_message", + }; + for (int i = 0; i < GOOGLE_ARRAYSIZE(fields); i++) { + const Message& sub_message = reflection->GetMessage(*message, F(fields[i])); + Message* released = reflection->ReleaseMessage(message, F(fields[i])); + switch (expected_release_state) { + case IS_NULL: + EXPECT_TRUE(released == nullptr); + break; + case NOT_NULL: + EXPECT_TRUE(released != nullptr); + if (message->GetArena() == nullptr) { + // released message must be same as sub_message if source message is + // not on arena. + EXPECT_EQ(&sub_message, released); + } + break; + case CAN_BE_NULL: + break; + } + delete released; + EXPECT_FALSE(reflection->HasField(*message, F(fields[i]))); + } +} + +// Check that the passed-in serialization is the canonical serialization we +// expect for a TestFieldOrderings message filled in by +// SetAllFieldsAndExtensions(). +inline void ExpectAllFieldsAndExtensionsInOrder( + const string& serialized) { + // We set each field individually, serialize separately, and concatenate all + // the strings in canonical order to determine the expected serialization. + string expected; + unittest::TestFieldOrderings message; + message.set_my_int(1); // Field 1. + message.AppendToString(&expected); + message.Clear(); + message.SetExtension(unittest::my_extension_int, 23); // Field 5. + message.AppendToString(&expected); + message.Clear(); + message.set_my_string("foo"); // Field 11. + message.AppendToString(&expected); + message.Clear(); + message.SetExtension(unittest::my_extension_string, "bar"); // Field 50. + message.AppendToString(&expected); + message.Clear(); + message.set_my_float(1.0); // Field 101. + message.AppendToString(&expected); + message.Clear(); + + // We don't EXPECT_EQ() since we don't want to print raw bytes to stdout. + EXPECT_TRUE(serialized == expected); +} + +} // namespace TestUtil } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/test_util.inc b/src/google/protobuf/test_util.inc new file mode 100644 index 00000000..185f68d9 --- /dev/null +++ b/src/google/protobuf/test_util.inc @@ -0,0 +1,2600 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. +// +// This file needs to be included as .inc as it depends on the namespaces +// (unittest and unittest_import) being set up properly. It is also included +// within an enclosing namespace and requires header files to be included +// out of this file. + +#include <google/protobuf/stubs/logging.h> +#include <google/protobuf/stubs/common.h> +#include <google/protobuf/descriptor.h> +#include <google/protobuf/message.h> +#include <google/protobuf/testing/googletest.h> +#include <gtest/gtest.h> + +namespace google { +namespace protobuf { +namespace TestUtil { + +// Set every field in the message to a unique value. +inline void SetAllFields(UNITTEST::TestAllTypes* message); +inline void SetOptionalFields(UNITTEST::TestAllTypes* message); +inline void AddRepeatedFields1(UNITTEST::TestAllTypes* message); +inline void AddRepeatedFields2(UNITTEST::TestAllTypes* message); +inline void SetDefaultFields(UNITTEST::TestAllTypes* message); +inline void SetOneofFields(UNITTEST::TestAllTypes* message); +inline void SetAllExtensions(UNITTEST::TestAllExtensions* message); +inline void SetOneofFields(UNITTEST::TestAllExtensions* message); +inline void SetAllFieldsAndExtensions(UNITTEST::TestFieldOrderings* message); +inline void SetPackedFields(UNITTEST::TestPackedTypes* message); +inline void SetPackedExtensions(UNITTEST::TestPackedExtensions* message); +inline void SetUnpackedFields(UNITTEST::TestUnpackedTypes* message); +inline void SetOneof1(UNITTEST::TestOneof2* message); +inline void SetOneof2(UNITTEST::TestOneof2* message); + +// Use the repeated versions of the set_*() accessors to modify all the +// repeated fields of the message (which should already have been +// initialized with Set*Fields()). Set*Fields() itself only tests +// the add_*() accessors. +inline void ModifyRepeatedFields(UNITTEST::TestAllTypes* message); +inline void ModifyRepeatedExtensions(UNITTEST::TestAllExtensions* message); +inline void ModifyPackedFields(UNITTEST::TestPackedTypes* message); +inline void ModifyPackedExtensions(UNITTEST::TestPackedExtensions* message); + +// Check that all fields have the values that they should have after +// Set*Fields() is called. +inline void ExpectAllFieldsSet(const UNITTEST::TestAllTypes& message); +inline void ExpectAllExtensionsSet(const UNITTEST::TestAllExtensions& message); +inline void ExpectPackedFieldsSet(const UNITTEST::TestPackedTypes& message); +inline void ExpectPackedExtensionsSet( + const UNITTEST::TestPackedExtensions& message); +inline void ExpectUnpackedFieldsSet(const UNITTEST::TestUnpackedTypes& message); +inline void ExpectUnpackedExtensionsSet( + const UNITTEST::TestUnpackedExtensions& message); +inline void ExpectOneofSet1(const UNITTEST::TestOneof2& message); +inline void ExpectOneofSet2(const UNITTEST::TestOneof2& message); + +// Expect that the message is modified as would be expected from +// Modify*Fields(). +inline void ExpectRepeatedFieldsModified(const UNITTEST::TestAllTypes& message); +inline void ExpectRepeatedExtensionsModified( + const UNITTEST::TestAllExtensions& message); +inline void ExpectPackedFieldsModified( + const UNITTEST::TestPackedTypes& message); +inline void ExpectPackedExtensionsModified( + const UNITTEST::TestPackedExtensions& message); + +// Check that all fields have their default values. +inline void ExpectClear(const UNITTEST::TestAllTypes& message); +inline void ExpectExtensionsClear(const UNITTEST::TestAllExtensions& message); +inline void ExpectPackedClear(const UNITTEST::TestPackedTypes& message); +inline void ExpectPackedExtensionsClear( + const UNITTEST::TestPackedExtensions& message); +inline void ExpectOneofClear(const UNITTEST::TestOneof2& message); + +// Check that all repeated fields have had their last elements removed. +inline void ExpectLastRepeatedsRemoved(const UNITTEST::TestAllTypes& message); +inline void ExpectLastRepeatedExtensionsRemoved( + const UNITTEST::TestAllExtensions& message); +inline void ExpectLastRepeatedsReleased(const UNITTEST::TestAllTypes& message); +inline void ExpectLastRepeatedExtensionsReleased( + const UNITTEST::TestAllExtensions& message); + +// Check that all repeated fields have had their first and last elements +// swapped. +inline void ExpectRepeatedsSwapped(const UNITTEST::TestAllTypes& message); +inline void ExpectRepeatedExtensionsSwapped( + const UNITTEST::TestAllExtensions& message); + +inline void ExpectAtMostOneFieldSetInOneof(const UNITTEST::TestOneof2& message); + +} // namespace TestUtil + +inline void TestUtil::SetAllFields(UNITTEST::TestAllTypes* message) { + SetOptionalFields(message); + AddRepeatedFields1(message); + AddRepeatedFields2(message); + SetDefaultFields(message); + SetOneofFields(message); +} + +inline void TestUtil::SetOptionalFields(UNITTEST::TestAllTypes* message) { + message->set_optional_int32(101); + message->set_optional_int64(102); + message->set_optional_uint32(103); + message->set_optional_uint64(104); + message->set_optional_sint32(105); + message->set_optional_sint64(106); + message->set_optional_fixed32(107); + message->set_optional_fixed64(108); + message->set_optional_sfixed32(109); + message->set_optional_sfixed64(110); + message->set_optional_float(111); + message->set_optional_double(112); + message->set_optional_bool(true); + message->set_optional_string("115"); + message->set_optional_bytes("116"); + + message->mutable_optionalgroup()->set_a(117); + message->mutable_optional_nested_message()->set_bb(118); + message->mutable_optional_foreign_message()->set_c(119); + message->mutable_optional_import_message()->set_d(120); + message->mutable_optional_public_import_message()->set_e(126); + message->mutable_optional_lazy_message()->set_bb(127); + + message->set_optional_nested_enum(UNITTEST::TestAllTypes::BAZ); + message->set_optional_foreign_enum(UNITTEST::FOREIGN_BAZ); + message->set_optional_import_enum(UNITTEST_IMPORT::IMPORT_BAZ); + + // StringPiece and Cord fields are only accessible via reflection in the + // open source release; see comments in compiler/cpp/string_field.cc. +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + message->GetReflection()->SetString( + message, + message->GetDescriptor()->FindFieldByName("optional_string_piece"), + "124"); + message->GetReflection()->SetString( + message, message->GetDescriptor()->FindFieldByName("optional_cord"), + "125"); +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS +} + +// ------------------------------------------------------------------- + +inline void TestUtil::AddRepeatedFields1(UNITTEST::TestAllTypes* message) { + message->add_repeated_int32(201); + message->add_repeated_int64(202); + message->add_repeated_uint32(203); + message->add_repeated_uint64(204); + message->add_repeated_sint32(205); + message->add_repeated_sint64(206); + message->add_repeated_fixed32(207); + message->add_repeated_fixed64(208); + message->add_repeated_sfixed32(209); + message->add_repeated_sfixed64(210); + message->add_repeated_float(211); + message->add_repeated_double(212); + message->add_repeated_bool(true); + message->add_repeated_string("215"); + message->add_repeated_bytes("216"); + + message->add_repeatedgroup()->set_a(217); + message->add_repeated_nested_message()->set_bb(218); + message->add_repeated_foreign_message()->set_c(219); + message->add_repeated_import_message()->set_d(220); + message->add_repeated_lazy_message()->set_bb(227); + + message->add_repeated_nested_enum(UNITTEST::TestAllTypes::BAR); + message->add_repeated_foreign_enum(UNITTEST::FOREIGN_BAR); + message->add_repeated_import_enum(UNITTEST_IMPORT::IMPORT_BAR); + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + message->GetReflection()->AddString( + message, + message->GetDescriptor()->FindFieldByName("repeated_string_piece"), + "224"); + message->GetReflection()->AddString( + message, message->GetDescriptor()->FindFieldByName("repeated_cord"), + "225"); +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS +} + +inline void TestUtil::AddRepeatedFields2(UNITTEST::TestAllTypes* message) { + // Add a second one of each field. + message->add_repeated_int32(301); + message->add_repeated_int64(302); + message->add_repeated_uint32(303); + message->add_repeated_uint64(304); + message->add_repeated_sint32(305); + message->add_repeated_sint64(306); + message->add_repeated_fixed32(307); + message->add_repeated_fixed64(308); + message->add_repeated_sfixed32(309); + message->add_repeated_sfixed64(310); + message->add_repeated_float(311); + message->add_repeated_double(312); + message->add_repeated_bool(false); + message->add_repeated_string("315"); + message->add_repeated_bytes("316"); + + message->add_repeatedgroup()->set_a(317); + message->add_repeated_nested_message()->set_bb(318); + message->add_repeated_foreign_message()->set_c(319); + message->add_repeated_import_message()->set_d(320); + message->add_repeated_lazy_message()->set_bb(327); + + message->add_repeated_nested_enum(UNITTEST::TestAllTypes::BAZ); + message->add_repeated_foreign_enum(UNITTEST::FOREIGN_BAZ); + message->add_repeated_import_enum(UNITTEST_IMPORT::IMPORT_BAZ); + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + message->GetReflection()->AddString( + message, + message->GetDescriptor()->FindFieldByName("repeated_string_piece"), + "324"); + message->GetReflection()->AddString( + message, message->GetDescriptor()->FindFieldByName("repeated_cord"), + "325"); +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS +} + +// ------------------------------------------------------------------- + +inline void TestUtil::SetDefaultFields(UNITTEST::TestAllTypes* message) { + message->set_default_int32(401); + message->set_default_int64(402); + message->set_default_uint32(403); + message->set_default_uint64(404); + message->set_default_sint32(405); + message->set_default_sint64(406); + message->set_default_fixed32(407); + message->set_default_fixed64(408); + message->set_default_sfixed32(409); + message->set_default_sfixed64(410); + message->set_default_float(411); + message->set_default_double(412); + message->set_default_bool(false); + message->set_default_string("415"); + message->set_default_bytes("416"); + + message->set_default_nested_enum(UNITTEST::TestAllTypes::FOO); + message->set_default_foreign_enum(UNITTEST::FOREIGN_FOO); + message->set_default_import_enum(UNITTEST_IMPORT::IMPORT_FOO); + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + message->GetReflection()->SetString( + message, + message->GetDescriptor()->FindFieldByName("default_string_piece"), "424"); + message->GetReflection()->SetString( + message, message->GetDescriptor()->FindFieldByName("default_cord"), + "425"); +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ModifyRepeatedFields(UNITTEST::TestAllTypes* message) { + message->set_repeated_int32(1, 501); + message->set_repeated_int64(1, 502); + message->set_repeated_uint32(1, 503); + message->set_repeated_uint64(1, 504); + message->set_repeated_sint32(1, 505); + message->set_repeated_sint64(1, 506); + message->set_repeated_fixed32(1, 507); + message->set_repeated_fixed64(1, 508); + message->set_repeated_sfixed32(1, 509); + message->set_repeated_sfixed64(1, 510); + message->set_repeated_float(1, 511); + message->set_repeated_double(1, 512); + message->set_repeated_bool(1, true); + message->set_repeated_string(1, "515"); + message->set_repeated_bytes(1, "516"); + + message->mutable_repeatedgroup(1)->set_a(517); + message->mutable_repeated_nested_message(1)->set_bb(518); + message->mutable_repeated_foreign_message(1)->set_c(519); + message->mutable_repeated_import_message(1)->set_d(520); + message->mutable_repeated_lazy_message(1)->set_bb(527); + + message->set_repeated_nested_enum(1, UNITTEST::TestAllTypes::FOO); + message->set_repeated_foreign_enum(1, UNITTEST::FOREIGN_FOO); + message->set_repeated_import_enum(1, UNITTEST_IMPORT::IMPORT_FOO); + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + message->GetReflection()->SetRepeatedString( + message, + message->GetDescriptor()->FindFieldByName("repeated_string_piece"), 1, + "524"); + message->GetReflection()->SetRepeatedString( + message, message->GetDescriptor()->FindFieldByName("repeated_cord"), 1, + "525"); +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS +} + +// ------------------------------------------------------------------ +inline void TestUtil::SetOneofFields(UNITTEST::TestAllTypes* message) { + message->set_oneof_uint32(601); + message->mutable_oneof_nested_message()->set_bb(602); + message->set_oneof_string("603"); + message->set_oneof_bytes("604"); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectAllFieldsSet( + const UNITTEST::TestAllTypes& message) { + EXPECT_TRUE(message.has_optional_int32()); + EXPECT_TRUE(message.has_optional_int64()); + EXPECT_TRUE(message.has_optional_uint32()); + EXPECT_TRUE(message.has_optional_uint64()); + EXPECT_TRUE(message.has_optional_sint32()); + EXPECT_TRUE(message.has_optional_sint64()); + EXPECT_TRUE(message.has_optional_fixed32()); + EXPECT_TRUE(message.has_optional_fixed64()); + EXPECT_TRUE(message.has_optional_sfixed32()); + EXPECT_TRUE(message.has_optional_sfixed64()); + EXPECT_TRUE(message.has_optional_float()); + EXPECT_TRUE(message.has_optional_double()); + EXPECT_TRUE(message.has_optional_bool()); + EXPECT_TRUE(message.has_optional_string()); + EXPECT_TRUE(message.has_optional_bytes()); + + EXPECT_TRUE(message.has_optionalgroup()); + EXPECT_TRUE(message.has_optional_nested_message()); + EXPECT_TRUE(message.has_optional_foreign_message()); + EXPECT_TRUE(message.has_optional_import_message()); + EXPECT_TRUE(message.has_optional_public_import_message()); + EXPECT_TRUE(message.has_optional_lazy_message()); + + EXPECT_TRUE(message.optionalgroup().has_a()); + EXPECT_TRUE(message.optional_nested_message().has_bb()); + EXPECT_TRUE(message.optional_foreign_message().has_c()); + EXPECT_TRUE(message.optional_import_message().has_d()); + EXPECT_TRUE(message.optional_public_import_message().has_e()); + EXPECT_TRUE(message.optional_lazy_message().has_bb()); + + EXPECT_TRUE(message.has_optional_nested_enum()); + EXPECT_TRUE(message.has_optional_foreign_enum()); + EXPECT_TRUE(message.has_optional_import_enum()); + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + EXPECT_TRUE(message.has_optional_string_piece()); + EXPECT_TRUE(message.has_optional_cord()); +#endif + + EXPECT_EQ(101, message.optional_int32()); + EXPECT_EQ(102, message.optional_int64()); + EXPECT_EQ(103, message.optional_uint32()); + EXPECT_EQ(104, message.optional_uint64()); + EXPECT_EQ(105, message.optional_sint32()); + EXPECT_EQ(106, message.optional_sint64()); + EXPECT_EQ(107, message.optional_fixed32()); + EXPECT_EQ(108, message.optional_fixed64()); + EXPECT_EQ(109, message.optional_sfixed32()); + EXPECT_EQ(110, message.optional_sfixed64()); + EXPECT_EQ(111, message.optional_float()); + EXPECT_EQ(112, message.optional_double()); + EXPECT_TRUE(message.optional_bool()); + EXPECT_EQ("115", message.optional_string()); + EXPECT_EQ("116", message.optional_bytes()); + + EXPECT_EQ(117, message.optionalgroup().a()); + EXPECT_EQ(118, message.optional_nested_message().bb()); + EXPECT_EQ(119, message.optional_foreign_message().c()); + EXPECT_EQ(120, message.optional_import_message().d()); + EXPECT_EQ(126, message.optional_public_import_message().e()); + EXPECT_EQ(127, message.optional_lazy_message().bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, message.optional_nested_enum()); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, message.optional_foreign_enum()); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAZ, message.optional_import_enum()); + + + // ----------------------------------------------------------------- + + ASSERT_EQ(2, message.repeated_int32_size()); + ASSERT_EQ(2, message.repeated_int64_size()); + ASSERT_EQ(2, message.repeated_uint32_size()); + ASSERT_EQ(2, message.repeated_uint64_size()); + ASSERT_EQ(2, message.repeated_sint32_size()); + ASSERT_EQ(2, message.repeated_sint64_size()); + ASSERT_EQ(2, message.repeated_fixed32_size()); + ASSERT_EQ(2, message.repeated_fixed64_size()); + ASSERT_EQ(2, message.repeated_sfixed32_size()); + ASSERT_EQ(2, message.repeated_sfixed64_size()); + ASSERT_EQ(2, message.repeated_float_size()); + ASSERT_EQ(2, message.repeated_double_size()); + ASSERT_EQ(2, message.repeated_bool_size()); + ASSERT_EQ(2, message.repeated_string_size()); + ASSERT_EQ(2, message.repeated_bytes_size()); + + ASSERT_EQ(2, message.repeatedgroup_size()); + ASSERT_EQ(2, message.repeated_nested_message_size()); + ASSERT_EQ(2, message.repeated_foreign_message_size()); + ASSERT_EQ(2, message.repeated_import_message_size()); + ASSERT_EQ(2, message.repeated_lazy_message_size()); + ASSERT_EQ(2, message.repeated_nested_enum_size()); + ASSERT_EQ(2, message.repeated_foreign_enum_size()); + ASSERT_EQ(2, message.repeated_import_enum_size()); + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + ASSERT_EQ(2, message.repeated_string_piece_size()); + ASSERT_EQ(2, message.repeated_cord_size()); +#endif + + EXPECT_EQ(201, message.repeated_int32(0)); + EXPECT_EQ(202, message.repeated_int64(0)); + EXPECT_EQ(203, message.repeated_uint32(0)); + EXPECT_EQ(204, message.repeated_uint64(0)); + EXPECT_EQ(205, message.repeated_sint32(0)); + EXPECT_EQ(206, message.repeated_sint64(0)); + EXPECT_EQ(207, message.repeated_fixed32(0)); + EXPECT_EQ(208, message.repeated_fixed64(0)); + EXPECT_EQ(209, message.repeated_sfixed32(0)); + EXPECT_EQ(210, message.repeated_sfixed64(0)); + EXPECT_EQ(211, message.repeated_float(0)); + EXPECT_EQ(212, message.repeated_double(0)); + EXPECT_TRUE(message.repeated_bool(0)); + EXPECT_EQ("215", message.repeated_string(0)); + EXPECT_EQ("216", message.repeated_bytes(0)); + + EXPECT_EQ(217, message.repeatedgroup(0).a()); + EXPECT_EQ(218, message.repeated_nested_message(0).bb()); + EXPECT_EQ(219, message.repeated_foreign_message(0).c()); + EXPECT_EQ(220, message.repeated_import_message(0).d()); + EXPECT_EQ(227, message.repeated_lazy_message(0).bb()); + + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message.repeated_nested_enum(0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.repeated_foreign_enum(0)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, message.repeated_import_enum(0)); + + EXPECT_EQ(301, message.repeated_int32(1)); + EXPECT_EQ(302, message.repeated_int64(1)); + EXPECT_EQ(303, message.repeated_uint32(1)); + EXPECT_EQ(304, message.repeated_uint64(1)); + EXPECT_EQ(305, message.repeated_sint32(1)); + EXPECT_EQ(306, message.repeated_sint64(1)); + EXPECT_EQ(307, message.repeated_fixed32(1)); + EXPECT_EQ(308, message.repeated_fixed64(1)); + EXPECT_EQ(309, message.repeated_sfixed32(1)); + EXPECT_EQ(310, message.repeated_sfixed64(1)); + EXPECT_EQ(311, message.repeated_float(1)); + EXPECT_EQ(312, message.repeated_double(1)); + EXPECT_FALSE(message.repeated_bool(1)); + EXPECT_EQ("315", message.repeated_string(1)); + EXPECT_EQ("316", message.repeated_bytes(1)); + + EXPECT_EQ(317, message.repeatedgroup(1).a()); + EXPECT_EQ(318, message.repeated_nested_message(1).bb()); + EXPECT_EQ(319, message.repeated_foreign_message(1).c()); + EXPECT_EQ(320, message.repeated_import_message(1).d()); + EXPECT_EQ(327, message.repeated_lazy_message(1).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, message.repeated_nested_enum(1)); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, message.repeated_foreign_enum(1)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAZ, message.repeated_import_enum(1)); + + + // ----------------------------------------------------------------- + + EXPECT_TRUE(message.has_default_int32()); + EXPECT_TRUE(message.has_default_int64()); + EXPECT_TRUE(message.has_default_uint32()); + EXPECT_TRUE(message.has_default_uint64()); + EXPECT_TRUE(message.has_default_sint32()); + EXPECT_TRUE(message.has_default_sint64()); + EXPECT_TRUE(message.has_default_fixed32()); + EXPECT_TRUE(message.has_default_fixed64()); + EXPECT_TRUE(message.has_default_sfixed32()); + EXPECT_TRUE(message.has_default_sfixed64()); + EXPECT_TRUE(message.has_default_float()); + EXPECT_TRUE(message.has_default_double()); + EXPECT_TRUE(message.has_default_bool()); + EXPECT_TRUE(message.has_default_string()); + EXPECT_TRUE(message.has_default_bytes()); + + EXPECT_TRUE(message.has_default_nested_enum()); + EXPECT_TRUE(message.has_default_foreign_enum()); + EXPECT_TRUE(message.has_default_import_enum()); + + + EXPECT_EQ(401, message.default_int32()); + EXPECT_EQ(402, message.default_int64()); + EXPECT_EQ(403, message.default_uint32()); + EXPECT_EQ(404, message.default_uint64()); + EXPECT_EQ(405, message.default_sint32()); + EXPECT_EQ(406, message.default_sint64()); + EXPECT_EQ(407, message.default_fixed32()); + EXPECT_EQ(408, message.default_fixed64()); + EXPECT_EQ(409, message.default_sfixed32()); + EXPECT_EQ(410, message.default_sfixed64()); + EXPECT_EQ(411, message.default_float()); + EXPECT_EQ(412, message.default_double()); + EXPECT_FALSE(message.default_bool()); + EXPECT_EQ("415", message.default_string()); + EXPECT_EQ("416", message.default_bytes()); + + EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message.default_nested_enum()); + EXPECT_EQ(UNITTEST::FOREIGN_FOO, message.default_foreign_enum()); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_FOO, message.default_import_enum()); + + + EXPECT_FALSE(message.has_oneof_uint32()); + EXPECT_FALSE(message.has_oneof_nested_message()); + EXPECT_FALSE(message.has_oneof_string()); + EXPECT_TRUE(message.has_oneof_bytes()); + + EXPECT_EQ("604", message.oneof_bytes()); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectClear(const UNITTEST::TestAllTypes& message) { + // has_blah() should initially be false for all optional fields. + EXPECT_FALSE(message.has_optional_int32()); + EXPECT_FALSE(message.has_optional_int64()); + EXPECT_FALSE(message.has_optional_uint32()); + EXPECT_FALSE(message.has_optional_uint64()); + EXPECT_FALSE(message.has_optional_sint32()); + EXPECT_FALSE(message.has_optional_sint64()); + EXPECT_FALSE(message.has_optional_fixed32()); + EXPECT_FALSE(message.has_optional_fixed64()); + EXPECT_FALSE(message.has_optional_sfixed32()); + EXPECT_FALSE(message.has_optional_sfixed64()); + EXPECT_FALSE(message.has_optional_float()); + EXPECT_FALSE(message.has_optional_double()); + EXPECT_FALSE(message.has_optional_bool()); + EXPECT_FALSE(message.has_optional_string()); + EXPECT_FALSE(message.has_optional_bytes()); + + EXPECT_FALSE(message.has_optionalgroup()); + EXPECT_FALSE(message.has_optional_nested_message()); + EXPECT_FALSE(message.has_optional_foreign_message()); + EXPECT_FALSE(message.has_optional_import_message()); + EXPECT_FALSE(message.has_optional_public_import_message()); + EXPECT_FALSE(message.has_optional_lazy_message()); + + EXPECT_FALSE(message.has_optional_nested_enum()); + EXPECT_FALSE(message.has_optional_foreign_enum()); + EXPECT_FALSE(message.has_optional_import_enum()); + + EXPECT_FALSE(message.has_optional_string_piece()); + EXPECT_FALSE(message.has_optional_cord()); + + // Optional fields without defaults are set to zero or something like it. + EXPECT_EQ(0, message.optional_int32()); + EXPECT_EQ(0, message.optional_int64()); + EXPECT_EQ(0, message.optional_uint32()); + EXPECT_EQ(0, message.optional_uint64()); + EXPECT_EQ(0, message.optional_sint32()); + EXPECT_EQ(0, message.optional_sint64()); + EXPECT_EQ(0, message.optional_fixed32()); + EXPECT_EQ(0, message.optional_fixed64()); + EXPECT_EQ(0, message.optional_sfixed32()); + EXPECT_EQ(0, message.optional_sfixed64()); + EXPECT_EQ(0, message.optional_float()); + EXPECT_EQ(0, message.optional_double()); + EXPECT_FALSE(message.optional_bool()); + EXPECT_EQ("", message.optional_string()); + EXPECT_EQ("", message.optional_bytes()); + + // Embedded messages should also be clear. + EXPECT_FALSE(message.optionalgroup().has_a()); + EXPECT_FALSE(message.optional_nested_message().has_bb()); + EXPECT_FALSE(message.optional_foreign_message().has_c()); + EXPECT_FALSE(message.optional_import_message().has_d()); + EXPECT_FALSE(message.optional_public_import_message().has_e()); + EXPECT_FALSE(message.optional_lazy_message().has_bb()); + + EXPECT_EQ(0, message.optionalgroup().a()); + EXPECT_EQ(0, message.optional_nested_message().bb()); + EXPECT_EQ(0, message.optional_foreign_message().c()); + EXPECT_EQ(0, message.optional_import_message().d()); + EXPECT_EQ(0, message.optional_public_import_message().e()); + EXPECT_EQ(0, message.optional_lazy_message().bb()); + + // Enums without defaults are set to the first value in the enum. + EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message.optional_nested_enum()); + EXPECT_EQ(UNITTEST::FOREIGN_FOO, message.optional_foreign_enum()); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_FOO, message.optional_import_enum()); + + + // Repeated fields are empty. + EXPECT_EQ(0, message.repeated_int32_size()); + EXPECT_EQ(0, message.repeated_int64_size()); + EXPECT_EQ(0, message.repeated_uint32_size()); + EXPECT_EQ(0, message.repeated_uint64_size()); + EXPECT_EQ(0, message.repeated_sint32_size()); + EXPECT_EQ(0, message.repeated_sint64_size()); + EXPECT_EQ(0, message.repeated_fixed32_size()); + EXPECT_EQ(0, message.repeated_fixed64_size()); + EXPECT_EQ(0, message.repeated_sfixed32_size()); + EXPECT_EQ(0, message.repeated_sfixed64_size()); + EXPECT_EQ(0, message.repeated_float_size()); + EXPECT_EQ(0, message.repeated_double_size()); + EXPECT_EQ(0, message.repeated_bool_size()); + EXPECT_EQ(0, message.repeated_string_size()); + EXPECT_EQ(0, message.repeated_bytes_size()); + + EXPECT_EQ(0, message.repeatedgroup_size()); + EXPECT_EQ(0, message.repeated_nested_message_size()); + EXPECT_EQ(0, message.repeated_foreign_message_size()); + EXPECT_EQ(0, message.repeated_import_message_size()); + EXPECT_EQ(0, message.repeated_lazy_message_size()); + EXPECT_EQ(0, message.repeated_nested_enum_size()); + EXPECT_EQ(0, message.repeated_foreign_enum_size()); + EXPECT_EQ(0, message.repeated_import_enum_size()); + + EXPECT_EQ(0, message.repeated_string_piece_size()); + EXPECT_EQ(0, message.repeated_cord_size()); + + // has_blah() should also be false for all default fields. + EXPECT_FALSE(message.has_default_int32()); + EXPECT_FALSE(message.has_default_int64()); + EXPECT_FALSE(message.has_default_uint32()); + EXPECT_FALSE(message.has_default_uint64()); + EXPECT_FALSE(message.has_default_sint32()); + EXPECT_FALSE(message.has_default_sint64()); + EXPECT_FALSE(message.has_default_fixed32()); + EXPECT_FALSE(message.has_default_fixed64()); + EXPECT_FALSE(message.has_default_sfixed32()); + EXPECT_FALSE(message.has_default_sfixed64()); + EXPECT_FALSE(message.has_default_float()); + EXPECT_FALSE(message.has_default_double()); + EXPECT_FALSE(message.has_default_bool()); + EXPECT_FALSE(message.has_default_string()); + EXPECT_FALSE(message.has_default_bytes()); + + EXPECT_FALSE(message.has_default_nested_enum()); + EXPECT_FALSE(message.has_default_foreign_enum()); + EXPECT_FALSE(message.has_default_import_enum()); + + + // Fields with defaults have their default values (duh). + EXPECT_EQ(41, message.default_int32()); + EXPECT_EQ(42, message.default_int64()); + EXPECT_EQ(43, message.default_uint32()); + EXPECT_EQ(44, message.default_uint64()); + EXPECT_EQ(-45, message.default_sint32()); + EXPECT_EQ(46, message.default_sint64()); + EXPECT_EQ(47, message.default_fixed32()); + EXPECT_EQ(48, message.default_fixed64()); + EXPECT_EQ(49, message.default_sfixed32()); + EXPECT_EQ(-50, message.default_sfixed64()); + EXPECT_EQ(51.5, message.default_float()); + EXPECT_EQ(52e3, message.default_double()); + EXPECT_TRUE(message.default_bool()); + EXPECT_EQ("hello", message.default_string()); + EXPECT_EQ("world", message.default_bytes()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message.default_nested_enum()); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.default_foreign_enum()); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, message.default_import_enum()); + + + EXPECT_FALSE(message.has_oneof_uint32()); + EXPECT_FALSE(message.has_oneof_nested_message()); + EXPECT_FALSE(message.has_oneof_string()); + EXPECT_FALSE(message.has_oneof_bytes()); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectRepeatedFieldsModified( + const UNITTEST::TestAllTypes& message) { + // ModifyRepeatedFields only sets the second repeated element of each + // field. In addition to verifying this, we also verify that the first + // element and size were *not* modified. + ASSERT_EQ(2, message.repeated_int32_size()); + ASSERT_EQ(2, message.repeated_int64_size()); + ASSERT_EQ(2, message.repeated_uint32_size()); + ASSERT_EQ(2, message.repeated_uint64_size()); + ASSERT_EQ(2, message.repeated_sint32_size()); + ASSERT_EQ(2, message.repeated_sint64_size()); + ASSERT_EQ(2, message.repeated_fixed32_size()); + ASSERT_EQ(2, message.repeated_fixed64_size()); + ASSERT_EQ(2, message.repeated_sfixed32_size()); + ASSERT_EQ(2, message.repeated_sfixed64_size()); + ASSERT_EQ(2, message.repeated_float_size()); + ASSERT_EQ(2, message.repeated_double_size()); + ASSERT_EQ(2, message.repeated_bool_size()); + ASSERT_EQ(2, message.repeated_string_size()); + ASSERT_EQ(2, message.repeated_bytes_size()); + + ASSERT_EQ(2, message.repeatedgroup_size()); + ASSERT_EQ(2, message.repeated_nested_message_size()); + ASSERT_EQ(2, message.repeated_foreign_message_size()); + ASSERT_EQ(2, message.repeated_import_message_size()); + ASSERT_EQ(2, message.repeated_lazy_message_size()); + ASSERT_EQ(2, message.repeated_nested_enum_size()); + ASSERT_EQ(2, message.repeated_foreign_enum_size()); + ASSERT_EQ(2, message.repeated_import_enum_size()); + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + ASSERT_EQ(2, message.repeated_string_piece_size()); + ASSERT_EQ(2, message.repeated_cord_size()); +#endif + + EXPECT_EQ(201, message.repeated_int32(0)); + EXPECT_EQ(202, message.repeated_int64(0)); + EXPECT_EQ(203, message.repeated_uint32(0)); + EXPECT_EQ(204, message.repeated_uint64(0)); + EXPECT_EQ(205, message.repeated_sint32(0)); + EXPECT_EQ(206, message.repeated_sint64(0)); + EXPECT_EQ(207, message.repeated_fixed32(0)); + EXPECT_EQ(208, message.repeated_fixed64(0)); + EXPECT_EQ(209, message.repeated_sfixed32(0)); + EXPECT_EQ(210, message.repeated_sfixed64(0)); + EXPECT_EQ(211, message.repeated_float(0)); + EXPECT_EQ(212, message.repeated_double(0)); + EXPECT_TRUE(message.repeated_bool(0)); + EXPECT_EQ("215", message.repeated_string(0)); + EXPECT_EQ("216", message.repeated_bytes(0)); + + EXPECT_EQ(217, message.repeatedgroup(0).a()); + EXPECT_EQ(218, message.repeated_nested_message(0).bb()); + EXPECT_EQ(219, message.repeated_foreign_message(0).c()); + EXPECT_EQ(220, message.repeated_import_message(0).d()); + EXPECT_EQ(227, message.repeated_lazy_message(0).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message.repeated_nested_enum(0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.repeated_foreign_enum(0)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, message.repeated_import_enum(0)); + + + // Actually verify the second (modified) elements now. + EXPECT_EQ(501, message.repeated_int32(1)); + EXPECT_EQ(502, message.repeated_int64(1)); + EXPECT_EQ(503, message.repeated_uint32(1)); + EXPECT_EQ(504, message.repeated_uint64(1)); + EXPECT_EQ(505, message.repeated_sint32(1)); + EXPECT_EQ(506, message.repeated_sint64(1)); + EXPECT_EQ(507, message.repeated_fixed32(1)); + EXPECT_EQ(508, message.repeated_fixed64(1)); + EXPECT_EQ(509, message.repeated_sfixed32(1)); + EXPECT_EQ(510, message.repeated_sfixed64(1)); + EXPECT_EQ(511, message.repeated_float(1)); + EXPECT_EQ(512, message.repeated_double(1)); + EXPECT_TRUE(message.repeated_bool(1)); + EXPECT_EQ("515", message.repeated_string(1)); + EXPECT_EQ("516", message.repeated_bytes(1)); + + EXPECT_EQ(517, message.repeatedgroup(1).a()); + EXPECT_EQ(518, message.repeated_nested_message(1).bb()); + EXPECT_EQ(519, message.repeated_foreign_message(1).c()); + EXPECT_EQ(520, message.repeated_import_message(1).d()); + EXPECT_EQ(527, message.repeated_lazy_message(1).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message.repeated_nested_enum(1)); + EXPECT_EQ(UNITTEST::FOREIGN_FOO, message.repeated_foreign_enum(1)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_FOO, message.repeated_import_enum(1)); + +} + +// ------------------------------------------------------------------- + +inline void TestUtil::SetPackedFields(UNITTEST::TestPackedTypes* message) { + message->add_packed_int32(601); + message->add_packed_int64(602); + message->add_packed_uint32(603); + message->add_packed_uint64(604); + message->add_packed_sint32(605); + message->add_packed_sint64(606); + message->add_packed_fixed32(607); + message->add_packed_fixed64(608); + message->add_packed_sfixed32(609); + message->add_packed_sfixed64(610); + message->add_packed_float(611); + message->add_packed_double(612); + message->add_packed_bool(true); + message->add_packed_enum(UNITTEST::FOREIGN_BAR); + // add a second one of each field + message->add_packed_int32(701); + message->add_packed_int64(702); + message->add_packed_uint32(703); + message->add_packed_uint64(704); + message->add_packed_sint32(705); + message->add_packed_sint64(706); + message->add_packed_fixed32(707); + message->add_packed_fixed64(708); + message->add_packed_sfixed32(709); + message->add_packed_sfixed64(710); + message->add_packed_float(711); + message->add_packed_double(712); + message->add_packed_bool(false); + message->add_packed_enum(UNITTEST::FOREIGN_BAZ); +} + +inline void TestUtil::SetUnpackedFields(UNITTEST::TestUnpackedTypes* message) { + // The values applied here must match those of SetPackedFields. + + message->add_unpacked_int32(601); + message->add_unpacked_int64(602); + message->add_unpacked_uint32(603); + message->add_unpacked_uint64(604); + message->add_unpacked_sint32(605); + message->add_unpacked_sint64(606); + message->add_unpacked_fixed32(607); + message->add_unpacked_fixed64(608); + message->add_unpacked_sfixed32(609); + message->add_unpacked_sfixed64(610); + message->add_unpacked_float(611); + message->add_unpacked_double(612); + message->add_unpacked_bool(true); + message->add_unpacked_enum(UNITTEST::FOREIGN_BAR); + // add a second one of each field + message->add_unpacked_int32(701); + message->add_unpacked_int64(702); + message->add_unpacked_uint32(703); + message->add_unpacked_uint64(704); + message->add_unpacked_sint32(705); + message->add_unpacked_sint64(706); + message->add_unpacked_fixed32(707); + message->add_unpacked_fixed64(708); + message->add_unpacked_sfixed32(709); + message->add_unpacked_sfixed64(710); + message->add_unpacked_float(711); + message->add_unpacked_double(712); + message->add_unpacked_bool(false); + message->add_unpacked_enum(UNITTEST::FOREIGN_BAZ); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ModifyPackedFields(UNITTEST::TestPackedTypes* message) { + message->set_packed_int32(1, 801); + message->set_packed_int64(1, 802); + message->set_packed_uint32(1, 803); + message->set_packed_uint64(1, 804); + message->set_packed_sint32(1, 805); + message->set_packed_sint64(1, 806); + message->set_packed_fixed32(1, 807); + message->set_packed_fixed64(1, 808); + message->set_packed_sfixed32(1, 809); + message->set_packed_sfixed64(1, 810); + message->set_packed_float(1, 811); + message->set_packed_double(1, 812); + message->set_packed_bool(1, true); + message->set_packed_enum(1, UNITTEST::FOREIGN_FOO); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectPackedFieldsSet( + const UNITTEST::TestPackedTypes& message) { + ASSERT_EQ(2, message.packed_int32_size()); + ASSERT_EQ(2, message.packed_int64_size()); + ASSERT_EQ(2, message.packed_uint32_size()); + ASSERT_EQ(2, message.packed_uint64_size()); + ASSERT_EQ(2, message.packed_sint32_size()); + ASSERT_EQ(2, message.packed_sint64_size()); + ASSERT_EQ(2, message.packed_fixed32_size()); + ASSERT_EQ(2, message.packed_fixed64_size()); + ASSERT_EQ(2, message.packed_sfixed32_size()); + ASSERT_EQ(2, message.packed_sfixed64_size()); + ASSERT_EQ(2, message.packed_float_size()); + ASSERT_EQ(2, message.packed_double_size()); + ASSERT_EQ(2, message.packed_bool_size()); + ASSERT_EQ(2, message.packed_enum_size()); + + EXPECT_EQ(601, message.packed_int32(0)); + EXPECT_EQ(602, message.packed_int64(0)); + EXPECT_EQ(603, message.packed_uint32(0)); + EXPECT_EQ(604, message.packed_uint64(0)); + EXPECT_EQ(605, message.packed_sint32(0)); + EXPECT_EQ(606, message.packed_sint64(0)); + EXPECT_EQ(607, message.packed_fixed32(0)); + EXPECT_EQ(608, message.packed_fixed64(0)); + EXPECT_EQ(609, message.packed_sfixed32(0)); + EXPECT_EQ(610, message.packed_sfixed64(0)); + EXPECT_EQ(611, message.packed_float(0)); + EXPECT_EQ(612, message.packed_double(0)); + EXPECT_TRUE(message.packed_bool(0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.packed_enum(0)); + + EXPECT_EQ(701, message.packed_int32(1)); + EXPECT_EQ(702, message.packed_int64(1)); + EXPECT_EQ(703, message.packed_uint32(1)); + EXPECT_EQ(704, message.packed_uint64(1)); + EXPECT_EQ(705, message.packed_sint32(1)); + EXPECT_EQ(706, message.packed_sint64(1)); + EXPECT_EQ(707, message.packed_fixed32(1)); + EXPECT_EQ(708, message.packed_fixed64(1)); + EXPECT_EQ(709, message.packed_sfixed32(1)); + EXPECT_EQ(710, message.packed_sfixed64(1)); + EXPECT_EQ(711, message.packed_float(1)); + EXPECT_EQ(712, message.packed_double(1)); + EXPECT_FALSE(message.packed_bool(1)); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, message.packed_enum(1)); +} + +inline void TestUtil::ExpectUnpackedFieldsSet( + const UNITTEST::TestUnpackedTypes& message) { + // The values expected here must match those of ExpectPackedFieldsSet. + + ASSERT_EQ(2, message.unpacked_int32_size()); + ASSERT_EQ(2, message.unpacked_int64_size()); + ASSERT_EQ(2, message.unpacked_uint32_size()); + ASSERT_EQ(2, message.unpacked_uint64_size()); + ASSERT_EQ(2, message.unpacked_sint32_size()); + ASSERT_EQ(2, message.unpacked_sint64_size()); + ASSERT_EQ(2, message.unpacked_fixed32_size()); + ASSERT_EQ(2, message.unpacked_fixed64_size()); + ASSERT_EQ(2, message.unpacked_sfixed32_size()); + ASSERT_EQ(2, message.unpacked_sfixed64_size()); + ASSERT_EQ(2, message.unpacked_float_size()); + ASSERT_EQ(2, message.unpacked_double_size()); + ASSERT_EQ(2, message.unpacked_bool_size()); + ASSERT_EQ(2, message.unpacked_enum_size()); + + EXPECT_EQ(601, message.unpacked_int32(0)); + EXPECT_EQ(602, message.unpacked_int64(0)); + EXPECT_EQ(603, message.unpacked_uint32(0)); + EXPECT_EQ(604, message.unpacked_uint64(0)); + EXPECT_EQ(605, message.unpacked_sint32(0)); + EXPECT_EQ(606, message.unpacked_sint64(0)); + EXPECT_EQ(607, message.unpacked_fixed32(0)); + EXPECT_EQ(608, message.unpacked_fixed64(0)); + EXPECT_EQ(609, message.unpacked_sfixed32(0)); + EXPECT_EQ(610, message.unpacked_sfixed64(0)); + EXPECT_EQ(611, message.unpacked_float(0)); + EXPECT_EQ(612, message.unpacked_double(0)); + EXPECT_TRUE(message.unpacked_bool(0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.unpacked_enum(0)); + + EXPECT_EQ(701, message.unpacked_int32(1)); + EXPECT_EQ(702, message.unpacked_int64(1)); + EXPECT_EQ(703, message.unpacked_uint32(1)); + EXPECT_EQ(704, message.unpacked_uint64(1)); + EXPECT_EQ(705, message.unpacked_sint32(1)); + EXPECT_EQ(706, message.unpacked_sint64(1)); + EXPECT_EQ(707, message.unpacked_fixed32(1)); + EXPECT_EQ(708, message.unpacked_fixed64(1)); + EXPECT_EQ(709, message.unpacked_sfixed32(1)); + EXPECT_EQ(710, message.unpacked_sfixed64(1)); + EXPECT_EQ(711, message.unpacked_float(1)); + EXPECT_EQ(712, message.unpacked_double(1)); + EXPECT_FALSE(message.unpacked_bool(1)); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, message.unpacked_enum(1)); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectPackedClear( + const UNITTEST::TestPackedTypes& message) { + // Packed repeated fields are empty. + EXPECT_EQ(0, message.packed_int32_size()); + EXPECT_EQ(0, message.packed_int64_size()); + EXPECT_EQ(0, message.packed_uint32_size()); + EXPECT_EQ(0, message.packed_uint64_size()); + EXPECT_EQ(0, message.packed_sint32_size()); + EXPECT_EQ(0, message.packed_sint64_size()); + EXPECT_EQ(0, message.packed_fixed32_size()); + EXPECT_EQ(0, message.packed_fixed64_size()); + EXPECT_EQ(0, message.packed_sfixed32_size()); + EXPECT_EQ(0, message.packed_sfixed64_size()); + EXPECT_EQ(0, message.packed_float_size()); + EXPECT_EQ(0, message.packed_double_size()); + EXPECT_EQ(0, message.packed_bool_size()); + EXPECT_EQ(0, message.packed_enum_size()); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectPackedFieldsModified( + const UNITTEST::TestPackedTypes& message) { + // Do the same for packed repeated fields. + ASSERT_EQ(2, message.packed_int32_size()); + ASSERT_EQ(2, message.packed_int64_size()); + ASSERT_EQ(2, message.packed_uint32_size()); + ASSERT_EQ(2, message.packed_uint64_size()); + ASSERT_EQ(2, message.packed_sint32_size()); + ASSERT_EQ(2, message.packed_sint64_size()); + ASSERT_EQ(2, message.packed_fixed32_size()); + ASSERT_EQ(2, message.packed_fixed64_size()); + ASSERT_EQ(2, message.packed_sfixed32_size()); + ASSERT_EQ(2, message.packed_sfixed64_size()); + ASSERT_EQ(2, message.packed_float_size()); + ASSERT_EQ(2, message.packed_double_size()); + ASSERT_EQ(2, message.packed_bool_size()); + ASSERT_EQ(2, message.packed_enum_size()); + + EXPECT_EQ(601, message.packed_int32(0)); + EXPECT_EQ(602, message.packed_int64(0)); + EXPECT_EQ(603, message.packed_uint32(0)); + EXPECT_EQ(604, message.packed_uint64(0)); + EXPECT_EQ(605, message.packed_sint32(0)); + EXPECT_EQ(606, message.packed_sint64(0)); + EXPECT_EQ(607, message.packed_fixed32(0)); + EXPECT_EQ(608, message.packed_fixed64(0)); + EXPECT_EQ(609, message.packed_sfixed32(0)); + EXPECT_EQ(610, message.packed_sfixed64(0)); + EXPECT_EQ(611, message.packed_float(0)); + EXPECT_EQ(612, message.packed_double(0)); + EXPECT_TRUE(message.packed_bool(0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.packed_enum(0)); + // Actually verify the second (modified) elements now. + EXPECT_EQ(801, message.packed_int32(1)); + EXPECT_EQ(802, message.packed_int64(1)); + EXPECT_EQ(803, message.packed_uint32(1)); + EXPECT_EQ(804, message.packed_uint64(1)); + EXPECT_EQ(805, message.packed_sint32(1)); + EXPECT_EQ(806, message.packed_sint64(1)); + EXPECT_EQ(807, message.packed_fixed32(1)); + EXPECT_EQ(808, message.packed_fixed64(1)); + EXPECT_EQ(809, message.packed_sfixed32(1)); + EXPECT_EQ(810, message.packed_sfixed64(1)); + EXPECT_EQ(811, message.packed_float(1)); + EXPECT_EQ(812, message.packed_double(1)); + EXPECT_TRUE(message.packed_bool(1)); + EXPECT_EQ(UNITTEST::FOREIGN_FOO, message.packed_enum(1)); +} + +// =================================================================== +// Extensions +// +// All this code is exactly equivalent to the above code except that it's +// manipulating extension fields instead of normal ones. + +inline void TestUtil::SetAllExtensions(UNITTEST::TestAllExtensions* message) { + message->SetExtension(UNITTEST::optional_int32_extension, 101); + message->SetExtension(UNITTEST::optional_int64_extension, 102); + message->SetExtension(UNITTEST::optional_uint32_extension, 103); + message->SetExtension(UNITTEST::optional_uint64_extension, 104); + message->SetExtension(UNITTEST::optional_sint32_extension, 105); + message->SetExtension(UNITTEST::optional_sint64_extension, 106); + message->SetExtension(UNITTEST::optional_fixed32_extension, 107); + message->SetExtension(UNITTEST::optional_fixed64_extension, 108); + message->SetExtension(UNITTEST::optional_sfixed32_extension, 109); + message->SetExtension(UNITTEST::optional_sfixed64_extension, 110); + message->SetExtension(UNITTEST::optional_float_extension, 111); + message->SetExtension(UNITTEST::optional_double_extension, 112); + message->SetExtension(UNITTEST::optional_bool_extension, true); + message->SetExtension(UNITTEST::optional_string_extension, "115"); + message->SetExtension(UNITTEST::optional_bytes_extension, "116"); + + message->MutableExtension(UNITTEST::optionalgroup_extension)->set_a(117); + message->MutableExtension(UNITTEST::optional_nested_message_extension) + ->set_bb(118); + message->MutableExtension(UNITTEST::optional_foreign_message_extension) + ->set_c(119); + message->MutableExtension(UNITTEST::optional_import_message_extension) + ->set_d(120); + + message->SetExtension(UNITTEST::optional_nested_enum_extension, + UNITTEST::TestAllTypes::BAZ); + message->SetExtension(UNITTEST::optional_foreign_enum_extension, + UNITTEST::FOREIGN_BAZ); + message->SetExtension(UNITTEST::optional_import_enum_extension, + UNITTEST_IMPORT::IMPORT_BAZ); + + message->SetExtension(UNITTEST::optional_string_piece_extension, "124"); + message->SetExtension(UNITTEST::optional_cord_extension, "125"); + + message->MutableExtension(UNITTEST::optional_public_import_message_extension) + ->set_e(126); + message->MutableExtension(UNITTEST::optional_lazy_message_extension) + ->set_bb(127); + + // ----------------------------------------------------------------- + + message->AddExtension(UNITTEST::repeated_int32_extension, 201); + message->AddExtension(UNITTEST::repeated_int64_extension, 202); + message->AddExtension(UNITTEST::repeated_uint32_extension, 203); + message->AddExtension(UNITTEST::repeated_uint64_extension, 204); + message->AddExtension(UNITTEST::repeated_sint32_extension, 205); + message->AddExtension(UNITTEST::repeated_sint64_extension, 206); + message->AddExtension(UNITTEST::repeated_fixed32_extension, 207); + message->AddExtension(UNITTEST::repeated_fixed64_extension, 208); + message->AddExtension(UNITTEST::repeated_sfixed32_extension, 209); + message->AddExtension(UNITTEST::repeated_sfixed64_extension, 210); + message->AddExtension(UNITTEST::repeated_float_extension, 211); + message->AddExtension(UNITTEST::repeated_double_extension, 212); + message->AddExtension(UNITTEST::repeated_bool_extension, true); + message->AddExtension(UNITTEST::repeated_string_extension, "215"); + message->AddExtension(UNITTEST::repeated_bytes_extension, "216"); + + message->AddExtension(UNITTEST::repeatedgroup_extension)->set_a(217); + message->AddExtension(UNITTEST::repeated_nested_message_extension) + ->set_bb(218); + message->AddExtension(UNITTEST::repeated_foreign_message_extension) + ->set_c(219); + message->AddExtension(UNITTEST::repeated_import_message_extension) + ->set_d(220); + message->AddExtension(UNITTEST::repeated_lazy_message_extension)->set_bb(227); + + message->AddExtension(UNITTEST::repeated_nested_enum_extension, + UNITTEST::TestAllTypes::BAR); + message->AddExtension(UNITTEST::repeated_foreign_enum_extension, + UNITTEST::FOREIGN_BAR); + message->AddExtension(UNITTEST::repeated_import_enum_extension, + UNITTEST_IMPORT::IMPORT_BAR); + + message->AddExtension(UNITTEST::repeated_string_piece_extension, "224"); + message->AddExtension(UNITTEST::repeated_cord_extension, "225"); + + // Add a second one of each field. + message->AddExtension(UNITTEST::repeated_int32_extension, 301); + message->AddExtension(UNITTEST::repeated_int64_extension, 302); + message->AddExtension(UNITTEST::repeated_uint32_extension, 303); + message->AddExtension(UNITTEST::repeated_uint64_extension, 304); + message->AddExtension(UNITTEST::repeated_sint32_extension, 305); + message->AddExtension(UNITTEST::repeated_sint64_extension, 306); + message->AddExtension(UNITTEST::repeated_fixed32_extension, 307); + message->AddExtension(UNITTEST::repeated_fixed64_extension, 308); + message->AddExtension(UNITTEST::repeated_sfixed32_extension, 309); + message->AddExtension(UNITTEST::repeated_sfixed64_extension, 310); + message->AddExtension(UNITTEST::repeated_float_extension, 311); + message->AddExtension(UNITTEST::repeated_double_extension, 312); + message->AddExtension(UNITTEST::repeated_bool_extension, false); + message->AddExtension(UNITTEST::repeated_string_extension, "315"); + message->AddExtension(UNITTEST::repeated_bytes_extension, "316"); + + message->AddExtension(UNITTEST::repeatedgroup_extension)->set_a(317); + message->AddExtension(UNITTEST::repeated_nested_message_extension) + ->set_bb(318); + message->AddExtension(UNITTEST::repeated_foreign_message_extension) + ->set_c(319); + message->AddExtension(UNITTEST::repeated_import_message_extension) + ->set_d(320); + message->AddExtension(UNITTEST::repeated_lazy_message_extension)->set_bb(327); + + message->AddExtension(UNITTEST::repeated_nested_enum_extension, + UNITTEST::TestAllTypes::BAZ); + message->AddExtension(UNITTEST::repeated_foreign_enum_extension, + UNITTEST::FOREIGN_BAZ); + message->AddExtension(UNITTEST::repeated_import_enum_extension, + UNITTEST_IMPORT::IMPORT_BAZ); + + message->AddExtension(UNITTEST::repeated_string_piece_extension, "324"); + message->AddExtension(UNITTEST::repeated_cord_extension, "325"); + + // ----------------------------------------------------------------- + + message->SetExtension(UNITTEST::default_int32_extension, 401); + message->SetExtension(UNITTEST::default_int64_extension, 402); + message->SetExtension(UNITTEST::default_uint32_extension, 403); + message->SetExtension(UNITTEST::default_uint64_extension, 404); + message->SetExtension(UNITTEST::default_sint32_extension, 405); + message->SetExtension(UNITTEST::default_sint64_extension, 406); + message->SetExtension(UNITTEST::default_fixed32_extension, 407); + message->SetExtension(UNITTEST::default_fixed64_extension, 408); + message->SetExtension(UNITTEST::default_sfixed32_extension, 409); + message->SetExtension(UNITTEST::default_sfixed64_extension, 410); + message->SetExtension(UNITTEST::default_float_extension, 411); + message->SetExtension(UNITTEST::default_double_extension, 412); + message->SetExtension(UNITTEST::default_bool_extension, false); + message->SetExtension(UNITTEST::default_string_extension, "415"); + message->SetExtension(UNITTEST::default_bytes_extension, "416"); + + message->SetExtension(UNITTEST::default_nested_enum_extension, + UNITTEST::TestAllTypes::FOO); + message->SetExtension(UNITTEST::default_foreign_enum_extension, + UNITTEST::FOREIGN_FOO); + message->SetExtension(UNITTEST::default_import_enum_extension, + UNITTEST_IMPORT::IMPORT_FOO); + + message->SetExtension(UNITTEST::default_string_piece_extension, "424"); + message->SetExtension(UNITTEST::default_cord_extension, "425"); + + SetOneofFields(message); +} + +inline void TestUtil::SetOneofFields(UNITTEST::TestAllExtensions* message) { + message->SetExtension(UNITTEST::oneof_uint32_extension, 601); + message->MutableExtension(UNITTEST::oneof_nested_message_extension) + ->set_bb(602); + message->SetExtension(UNITTEST::oneof_string_extension, "603"); + message->SetExtension(UNITTEST::oneof_bytes_extension, "604"); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::SetAllFieldsAndExtensions( + UNITTEST::TestFieldOrderings* message) { + GOOGLE_CHECK(message); + message->set_my_int(1); + message->set_my_string("foo"); + message->set_my_float(1.0); + message->SetExtension(UNITTEST::my_extension_int, 23); + message->SetExtension(UNITTEST::my_extension_string, "bar"); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ModifyRepeatedExtensions( + UNITTEST::TestAllExtensions* message) { + message->SetExtension(UNITTEST::repeated_int32_extension, 1, 501); + message->SetExtension(UNITTEST::repeated_int64_extension, 1, 502); + message->SetExtension(UNITTEST::repeated_uint32_extension, 1, 503); + message->SetExtension(UNITTEST::repeated_uint64_extension, 1, 504); + message->SetExtension(UNITTEST::repeated_sint32_extension, 1, 505); + message->SetExtension(UNITTEST::repeated_sint64_extension, 1, 506); + message->SetExtension(UNITTEST::repeated_fixed32_extension, 1, 507); + message->SetExtension(UNITTEST::repeated_fixed64_extension, 1, 508); + message->SetExtension(UNITTEST::repeated_sfixed32_extension, 1, 509); + message->SetExtension(UNITTEST::repeated_sfixed64_extension, 1, 510); + message->SetExtension(UNITTEST::repeated_float_extension, 1, 511); + message->SetExtension(UNITTEST::repeated_double_extension, 1, 512); + message->SetExtension(UNITTEST::repeated_bool_extension, 1, true); + message->SetExtension(UNITTEST::repeated_string_extension, 1, "515"); + message->SetExtension(UNITTEST::repeated_bytes_extension, 1, "516"); + + message->MutableExtension(UNITTEST::repeatedgroup_extension, 1)->set_a(517); + message->MutableExtension(UNITTEST::repeated_nested_message_extension, 1) + ->set_bb(518); + message->MutableExtension(UNITTEST::repeated_foreign_message_extension, 1) + ->set_c(519); + message->MutableExtension(UNITTEST::repeated_import_message_extension, 1) + ->set_d(520); + message->MutableExtension(UNITTEST::repeated_lazy_message_extension, 1) + ->set_bb(527); + + message->SetExtension(UNITTEST::repeated_nested_enum_extension, 1, + UNITTEST::TestAllTypes::FOO); + message->SetExtension(UNITTEST::repeated_foreign_enum_extension, 1, + UNITTEST::FOREIGN_FOO); + message->SetExtension(UNITTEST::repeated_import_enum_extension, 1, + UNITTEST_IMPORT::IMPORT_FOO); + + message->SetExtension(UNITTEST::repeated_string_piece_extension, 1, "524"); + message->SetExtension(UNITTEST::repeated_cord_extension, 1, "525"); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectAllExtensionsSet( + const UNITTEST::TestAllExtensions& message) { + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_int32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_int64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_uint32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_uint64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_sint32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_sint64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_fixed32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_fixed64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_sfixed32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_sfixed64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_float_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_double_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_bool_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_string_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_bytes_extension)); + + EXPECT_TRUE(message.HasExtension(UNITTEST::optionalgroup_extension)); + EXPECT_TRUE( + message.HasExtension(UNITTEST::optional_nested_message_extension)); + EXPECT_TRUE( + message.HasExtension(UNITTEST::optional_foreign_message_extension)); + EXPECT_TRUE( + message.HasExtension(UNITTEST::optional_import_message_extension)); + EXPECT_TRUE( + message.HasExtension(UNITTEST::optional_public_import_message_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_lazy_message_extension)); + + EXPECT_TRUE(message.GetExtension(UNITTEST::optionalgroup_extension).has_a()); + EXPECT_TRUE(message.GetExtension(UNITTEST::optional_nested_message_extension) + .has_bb()); + EXPECT_TRUE(message.GetExtension(UNITTEST::optional_foreign_message_extension) + .has_c()); + EXPECT_TRUE(message.GetExtension(UNITTEST::optional_import_message_extension) + .has_d()); + EXPECT_TRUE( + message.GetExtension(UNITTEST::optional_public_import_message_extension) + .has_e()); + EXPECT_TRUE( + message.GetExtension(UNITTEST::optional_lazy_message_extension).has_bb()); + + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_nested_enum_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_foreign_enum_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_import_enum_extension)); + + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_string_piece_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_cord_extension)); + + EXPECT_EQ(101, message.GetExtension(UNITTEST::optional_int32_extension)); + EXPECT_EQ(102, message.GetExtension(UNITTEST::optional_int64_extension)); + EXPECT_EQ(103, message.GetExtension(UNITTEST::optional_uint32_extension)); + EXPECT_EQ(104, message.GetExtension(UNITTEST::optional_uint64_extension)); + EXPECT_EQ(105, message.GetExtension(UNITTEST::optional_sint32_extension)); + EXPECT_EQ(106, message.GetExtension(UNITTEST::optional_sint64_extension)); + EXPECT_EQ(107, message.GetExtension(UNITTEST::optional_fixed32_extension)); + EXPECT_EQ(108, message.GetExtension(UNITTEST::optional_fixed64_extension)); + EXPECT_EQ(109, message.GetExtension(UNITTEST::optional_sfixed32_extension)); + EXPECT_EQ(110, message.GetExtension(UNITTEST::optional_sfixed64_extension)); + EXPECT_EQ(111, message.GetExtension(UNITTEST::optional_float_extension)); + EXPECT_EQ(112, message.GetExtension(UNITTEST::optional_double_extension)); + EXPECT_TRUE(message.GetExtension(UNITTEST::optional_bool_extension)); + EXPECT_EQ("115", message.GetExtension(UNITTEST::optional_string_extension)); + EXPECT_EQ("116", message.GetExtension(UNITTEST::optional_bytes_extension)); + + EXPECT_EQ(117, message.GetExtension(UNITTEST::optionalgroup_extension).a()); + EXPECT_EQ( + 118, + message.GetExtension(UNITTEST::optional_nested_message_extension).bb()); + EXPECT_EQ( + 119, + message.GetExtension(UNITTEST::optional_foreign_message_extension).c()); + EXPECT_EQ( + 120, + message.GetExtension(UNITTEST::optional_import_message_extension).d()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, + message.GetExtension(UNITTEST::optional_nested_enum_extension)); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, + message.GetExtension(UNITTEST::optional_foreign_enum_extension)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAZ, + message.GetExtension(UNITTEST::optional_import_enum_extension)); + + EXPECT_EQ("124", + message.GetExtension(UNITTEST::optional_string_piece_extension)); + EXPECT_EQ("125", message.GetExtension(UNITTEST::optional_cord_extension)); + EXPECT_EQ( + 126, + message.GetExtension(UNITTEST::optional_public_import_message_extension) + .e()); + EXPECT_EQ( + 127, + message.GetExtension(UNITTEST::optional_lazy_message_extension).bb()); + + // ----------------------------------------------------------------- + + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_int32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_int64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_uint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_uint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_fixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_fixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sfixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sfixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_float_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_double_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_bool_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_string_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_bytes_extension)); + + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeatedgroup_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_nested_message_extension)); + ASSERT_EQ( + 2, message.ExtensionSize(UNITTEST::repeated_foreign_message_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_import_message_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_lazy_message_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_nested_enum_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_foreign_enum_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_import_enum_extension)); + + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_string_piece_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_cord_extension)); + + EXPECT_EQ(201, message.GetExtension(UNITTEST::repeated_int32_extension, 0)); + EXPECT_EQ(202, message.GetExtension(UNITTEST::repeated_int64_extension, 0)); + EXPECT_EQ(203, message.GetExtension(UNITTEST::repeated_uint32_extension, 0)); + EXPECT_EQ(204, message.GetExtension(UNITTEST::repeated_uint64_extension, 0)); + EXPECT_EQ(205, message.GetExtension(UNITTEST::repeated_sint32_extension, 0)); + EXPECT_EQ(206, message.GetExtension(UNITTEST::repeated_sint64_extension, 0)); + EXPECT_EQ(207, message.GetExtension(UNITTEST::repeated_fixed32_extension, 0)); + EXPECT_EQ(208, message.GetExtension(UNITTEST::repeated_fixed64_extension, 0)); + EXPECT_EQ(209, + message.GetExtension(UNITTEST::repeated_sfixed32_extension, 0)); + EXPECT_EQ(210, + message.GetExtension(UNITTEST::repeated_sfixed64_extension, 0)); + EXPECT_EQ(211, message.GetExtension(UNITTEST::repeated_float_extension, 0)); + EXPECT_EQ(212, message.GetExtension(UNITTEST::repeated_double_extension, 0)); + EXPECT_TRUE(message.GetExtension(UNITTEST::repeated_bool_extension, 0)); + EXPECT_EQ("215", + message.GetExtension(UNITTEST::repeated_string_extension, 0)); + EXPECT_EQ("216", message.GetExtension(UNITTEST::repeated_bytes_extension, 0)); + + EXPECT_EQ(217, + message.GetExtension(UNITTEST::repeatedgroup_extension, 0).a()); + EXPECT_EQ(218, + message.GetExtension(UNITTEST::repeated_nested_message_extension, 0) + .bb()); + EXPECT_EQ( + 219, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 0) + .c()); + EXPECT_EQ( + 220, + message.GetExtension(UNITTEST::repeated_import_message_extension, 0).d()); + EXPECT_EQ( + 227, + message.GetExtension(UNITTEST::repeated_lazy_message_extension, 0).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, + message.GetExtension(UNITTEST::repeated_nested_enum_extension, 0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, + message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 0)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, + message.GetExtension(UNITTEST::repeated_import_enum_extension, 0)); + + EXPECT_EQ("224", + message.GetExtension(UNITTEST::repeated_string_piece_extension, 0)); + EXPECT_EQ("225", message.GetExtension(UNITTEST::repeated_cord_extension, 0)); + + EXPECT_EQ(301, message.GetExtension(UNITTEST::repeated_int32_extension, 1)); + EXPECT_EQ(302, message.GetExtension(UNITTEST::repeated_int64_extension, 1)); + EXPECT_EQ(303, message.GetExtension(UNITTEST::repeated_uint32_extension, 1)); + EXPECT_EQ(304, message.GetExtension(UNITTEST::repeated_uint64_extension, 1)); + EXPECT_EQ(305, message.GetExtension(UNITTEST::repeated_sint32_extension, 1)); + EXPECT_EQ(306, message.GetExtension(UNITTEST::repeated_sint64_extension, 1)); + EXPECT_EQ(307, message.GetExtension(UNITTEST::repeated_fixed32_extension, 1)); + EXPECT_EQ(308, message.GetExtension(UNITTEST::repeated_fixed64_extension, 1)); + EXPECT_EQ(309, + message.GetExtension(UNITTEST::repeated_sfixed32_extension, 1)); + EXPECT_EQ(310, + message.GetExtension(UNITTEST::repeated_sfixed64_extension, 1)); + EXPECT_EQ(311, message.GetExtension(UNITTEST::repeated_float_extension, 1)); + EXPECT_EQ(312, message.GetExtension(UNITTEST::repeated_double_extension, 1)); + EXPECT_FALSE(message.GetExtension(UNITTEST::repeated_bool_extension, 1)); + EXPECT_EQ("315", + message.GetExtension(UNITTEST::repeated_string_extension, 1)); + EXPECT_EQ("316", message.GetExtension(UNITTEST::repeated_bytes_extension, 1)); + + EXPECT_EQ(317, + message.GetExtension(UNITTEST::repeatedgroup_extension, 1).a()); + EXPECT_EQ(318, + message.GetExtension(UNITTEST::repeated_nested_message_extension, 1) + .bb()); + EXPECT_EQ( + 319, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 1) + .c()); + EXPECT_EQ( + 320, + message.GetExtension(UNITTEST::repeated_import_message_extension, 1).d()); + EXPECT_EQ( + 327, + message.GetExtension(UNITTEST::repeated_lazy_message_extension, 1).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, + message.GetExtension(UNITTEST::repeated_nested_enum_extension, 1)); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, + message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 1)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAZ, + message.GetExtension(UNITTEST::repeated_import_enum_extension, 1)); + + EXPECT_EQ("324", + message.GetExtension(UNITTEST::repeated_string_piece_extension, 1)); + EXPECT_EQ("325", message.GetExtension(UNITTEST::repeated_cord_extension, 1)); + + // ----------------------------------------------------------------- + + EXPECT_TRUE(message.HasExtension(UNITTEST::default_int32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_int64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_uint32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_uint64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_sint32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_sint64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_fixed32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_fixed64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_sfixed32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_sfixed64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_float_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_double_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_bool_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_string_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_bytes_extension)); + + EXPECT_TRUE(message.HasExtension(UNITTEST::default_nested_enum_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_foreign_enum_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_import_enum_extension)); + + EXPECT_TRUE(message.HasExtension(UNITTEST::default_string_piece_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_cord_extension)); + + EXPECT_EQ(401, message.GetExtension(UNITTEST::default_int32_extension)); + EXPECT_EQ(402, message.GetExtension(UNITTEST::default_int64_extension)); + EXPECT_EQ(403, message.GetExtension(UNITTEST::default_uint32_extension)); + EXPECT_EQ(404, message.GetExtension(UNITTEST::default_uint64_extension)); + EXPECT_EQ(405, message.GetExtension(UNITTEST::default_sint32_extension)); + EXPECT_EQ(406, message.GetExtension(UNITTEST::default_sint64_extension)); + EXPECT_EQ(407, message.GetExtension(UNITTEST::default_fixed32_extension)); + EXPECT_EQ(408, message.GetExtension(UNITTEST::default_fixed64_extension)); + EXPECT_EQ(409, message.GetExtension(UNITTEST::default_sfixed32_extension)); + EXPECT_EQ(410, message.GetExtension(UNITTEST::default_sfixed64_extension)); + EXPECT_EQ(411, message.GetExtension(UNITTEST::default_float_extension)); + EXPECT_EQ(412, message.GetExtension(UNITTEST::default_double_extension)); + EXPECT_FALSE(message.GetExtension(UNITTEST::default_bool_extension)); + EXPECT_EQ("415", message.GetExtension(UNITTEST::default_string_extension)); + EXPECT_EQ("416", message.GetExtension(UNITTEST::default_bytes_extension)); + + EXPECT_EQ(UNITTEST::TestAllTypes::FOO, + message.GetExtension(UNITTEST::default_nested_enum_extension)); + EXPECT_EQ(UNITTEST::FOREIGN_FOO, + message.GetExtension(UNITTEST::default_foreign_enum_extension)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_FOO, + message.GetExtension(UNITTEST::default_import_enum_extension)); + + EXPECT_EQ("424", + message.GetExtension(UNITTEST::default_string_piece_extension)); + EXPECT_EQ("425", message.GetExtension(UNITTEST::default_cord_extension)); + + EXPECT_TRUE(message.HasExtension(UNITTEST::oneof_uint32_extension)); + EXPECT_TRUE( + message.GetExtension(UNITTEST::oneof_nested_message_extension).has_bb()); + EXPECT_TRUE(message.HasExtension(UNITTEST::oneof_string_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::oneof_bytes_extension)); + + EXPECT_EQ(601, message.GetExtension(UNITTEST::oneof_uint32_extension)); + EXPECT_EQ( + 602, message.GetExtension(UNITTEST::oneof_nested_message_extension).bb()); + EXPECT_EQ("603", message.GetExtension(UNITTEST::oneof_string_extension)); + EXPECT_EQ("604", message.GetExtension(UNITTEST::oneof_bytes_extension)); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectExtensionsClear( + const UNITTEST::TestAllExtensions& message) { + string serialized; + ASSERT_TRUE(message.SerializeToString(&serialized)); + EXPECT_EQ("", serialized); + EXPECT_EQ(0, message.ByteSizeLong()); + + // has_blah() should initially be false for all optional fields. + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_int32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_int64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_uint32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_uint64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_sint32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_sint64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_fixed32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_fixed64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_sfixed32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_sfixed64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_float_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_double_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_bool_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_string_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_bytes_extension)); + + EXPECT_FALSE(message.HasExtension(UNITTEST::optionalgroup_extension)); + EXPECT_FALSE( + message.HasExtension(UNITTEST::optional_nested_message_extension)); + EXPECT_FALSE( + message.HasExtension(UNITTEST::optional_foreign_message_extension)); + EXPECT_FALSE( + message.HasExtension(UNITTEST::optional_import_message_extension)); + EXPECT_FALSE( + message.HasExtension(UNITTEST::optional_public_import_message_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_lazy_message_extension)); + + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_nested_enum_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_foreign_enum_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_import_enum_extension)); + + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_string_piece_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_cord_extension)); + + // Optional fields without defaults are set to zero or something like it. + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_int32_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_int64_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_uint32_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_uint64_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_sint32_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_sint64_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_fixed32_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_fixed64_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_sfixed32_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_sfixed64_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_float_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_double_extension)); + EXPECT_FALSE(message.GetExtension(UNITTEST::optional_bool_extension)); + EXPECT_EQ("", message.GetExtension(UNITTEST::optional_string_extension)); + EXPECT_EQ("", message.GetExtension(UNITTEST::optional_bytes_extension)); + + // Embedded messages should also be clear. + EXPECT_FALSE(message.GetExtension(UNITTEST::optionalgroup_extension).has_a()); + EXPECT_FALSE(message.GetExtension(UNITTEST::optional_nested_message_extension) + .has_bb()); + EXPECT_FALSE( + message.GetExtension(UNITTEST::optional_foreign_message_extension) + .has_c()); + EXPECT_FALSE(message.GetExtension(UNITTEST::optional_import_message_extension) + .has_d()); + EXPECT_FALSE( + message.GetExtension(UNITTEST::optional_public_import_message_extension) + .has_e()); + EXPECT_FALSE( + message.GetExtension(UNITTEST::optional_lazy_message_extension).has_bb()); + + EXPECT_EQ(0, message.GetExtension(UNITTEST::optionalgroup_extension).a()); + EXPECT_EQ( + 0, + message.GetExtension(UNITTEST::optional_nested_message_extension).bb()); + EXPECT_EQ( + 0, + message.GetExtension(UNITTEST::optional_foreign_message_extension).c()); + EXPECT_EQ( + 0, message.GetExtension(UNITTEST::optional_import_message_extension).d()); + EXPECT_EQ( + 0, + message.GetExtension(UNITTEST::optional_public_import_message_extension) + .e()); + EXPECT_EQ( + 0, message.GetExtension(UNITTEST::optional_lazy_message_extension).bb()); + + // Enums without defaults are set to the first value in the enum. + EXPECT_EQ(UNITTEST::TestAllTypes::FOO, + message.GetExtension(UNITTEST::optional_nested_enum_extension)); + EXPECT_EQ(UNITTEST::FOREIGN_FOO, + message.GetExtension(UNITTEST::optional_foreign_enum_extension)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_FOO, + message.GetExtension(UNITTEST::optional_import_enum_extension)); + + EXPECT_EQ("", + message.GetExtension(UNITTEST::optional_string_piece_extension)); + EXPECT_EQ("", message.GetExtension(UNITTEST::optional_cord_extension)); + + // Repeated fields are empty. + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_int32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_int64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_uint32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_uint64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_sint32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_sint64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_fixed32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_fixed64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_sfixed32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_sfixed64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_float_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_double_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_bool_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_string_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_bytes_extension)); + + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeatedgroup_extension)); + EXPECT_EQ(0, + message.ExtensionSize(UNITTEST::repeated_nested_message_extension)); + EXPECT_EQ( + 0, message.ExtensionSize(UNITTEST::repeated_foreign_message_extension)); + EXPECT_EQ(0, + message.ExtensionSize(UNITTEST::repeated_import_message_extension)); + EXPECT_EQ(0, + message.ExtensionSize(UNITTEST::repeated_lazy_message_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_nested_enum_extension)); + EXPECT_EQ(0, + message.ExtensionSize(UNITTEST::repeated_foreign_enum_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_import_enum_extension)); + + EXPECT_EQ(0, + message.ExtensionSize(UNITTEST::repeated_string_piece_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_cord_extension)); + + // has_blah() should also be false for all default fields. + EXPECT_FALSE(message.HasExtension(UNITTEST::default_int32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_int64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_uint32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_uint64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_sint32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_sint64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_fixed32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_fixed64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_sfixed32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_sfixed64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_float_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_double_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_bool_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_string_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_bytes_extension)); + + EXPECT_FALSE(message.HasExtension(UNITTEST::default_nested_enum_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_foreign_enum_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_import_enum_extension)); + + EXPECT_FALSE(message.HasExtension(UNITTEST::default_string_piece_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_cord_extension)); + + // Fields with defaults have their default values (duh). + EXPECT_EQ(41, message.GetExtension(UNITTEST::default_int32_extension)); + EXPECT_EQ(42, message.GetExtension(UNITTEST::default_int64_extension)); + EXPECT_EQ(43, message.GetExtension(UNITTEST::default_uint32_extension)); + EXPECT_EQ(44, message.GetExtension(UNITTEST::default_uint64_extension)); + EXPECT_EQ(-45, message.GetExtension(UNITTEST::default_sint32_extension)); + EXPECT_EQ(46, message.GetExtension(UNITTEST::default_sint64_extension)); + EXPECT_EQ(47, message.GetExtension(UNITTEST::default_fixed32_extension)); + EXPECT_EQ(48, message.GetExtension(UNITTEST::default_fixed64_extension)); + EXPECT_EQ(49, message.GetExtension(UNITTEST::default_sfixed32_extension)); + EXPECT_EQ(-50, message.GetExtension(UNITTEST::default_sfixed64_extension)); + EXPECT_EQ(51.5, message.GetExtension(UNITTEST::default_float_extension)); + EXPECT_EQ(52e3, message.GetExtension(UNITTEST::default_double_extension)); + EXPECT_TRUE(message.GetExtension(UNITTEST::default_bool_extension)); + EXPECT_EQ("hello", message.GetExtension(UNITTEST::default_string_extension)); + EXPECT_EQ("world", message.GetExtension(UNITTEST::default_bytes_extension)); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, + message.GetExtension(UNITTEST::default_nested_enum_extension)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, + message.GetExtension(UNITTEST::default_foreign_enum_extension)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, + message.GetExtension(UNITTEST::default_import_enum_extension)); + + EXPECT_EQ("abc", + message.GetExtension(UNITTEST::default_string_piece_extension)); + EXPECT_EQ("123", message.GetExtension(UNITTEST::default_cord_extension)); + + EXPECT_FALSE(message.HasExtension(UNITTEST::oneof_uint32_extension)); + EXPECT_FALSE( + message.GetExtension(UNITTEST::oneof_nested_message_extension).has_bb()); + EXPECT_FALSE(message.HasExtension(UNITTEST::oneof_string_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::oneof_bytes_extension)); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectRepeatedExtensionsModified( + const UNITTEST::TestAllExtensions& message) { + // ModifyRepeatedFields only sets the second repeated element of each + // field. In addition to verifying this, we also verify that the first + // element and size were *not* modified. + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_int32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_int64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_uint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_uint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_fixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_fixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sfixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sfixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_float_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_double_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_bool_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_string_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_bytes_extension)); + + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeatedgroup_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_nested_message_extension)); + ASSERT_EQ( + 2, message.ExtensionSize(UNITTEST::repeated_foreign_message_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_import_message_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_lazy_message_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_nested_enum_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_foreign_enum_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_import_enum_extension)); + + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_string_piece_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_cord_extension)); + + EXPECT_EQ(201, message.GetExtension(UNITTEST::repeated_int32_extension, 0)); + EXPECT_EQ(202, message.GetExtension(UNITTEST::repeated_int64_extension, 0)); + EXPECT_EQ(203, message.GetExtension(UNITTEST::repeated_uint32_extension, 0)); + EXPECT_EQ(204, message.GetExtension(UNITTEST::repeated_uint64_extension, 0)); + EXPECT_EQ(205, message.GetExtension(UNITTEST::repeated_sint32_extension, 0)); + EXPECT_EQ(206, message.GetExtension(UNITTEST::repeated_sint64_extension, 0)); + EXPECT_EQ(207, message.GetExtension(UNITTEST::repeated_fixed32_extension, 0)); + EXPECT_EQ(208, message.GetExtension(UNITTEST::repeated_fixed64_extension, 0)); + EXPECT_EQ(209, + message.GetExtension(UNITTEST::repeated_sfixed32_extension, 0)); + EXPECT_EQ(210, + message.GetExtension(UNITTEST::repeated_sfixed64_extension, 0)); + EXPECT_EQ(211, message.GetExtension(UNITTEST::repeated_float_extension, 0)); + EXPECT_EQ(212, message.GetExtension(UNITTEST::repeated_double_extension, 0)); + EXPECT_TRUE(message.GetExtension(UNITTEST::repeated_bool_extension, 0)); + EXPECT_EQ("215", + message.GetExtension(UNITTEST::repeated_string_extension, 0)); + EXPECT_EQ("216", message.GetExtension(UNITTEST::repeated_bytes_extension, 0)); + + EXPECT_EQ(217, + message.GetExtension(UNITTEST::repeatedgroup_extension, 0).a()); + EXPECT_EQ(218, + message.GetExtension(UNITTEST::repeated_nested_message_extension, 0) + .bb()); + EXPECT_EQ( + 219, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 0) + .c()); + EXPECT_EQ( + 220, + message.GetExtension(UNITTEST::repeated_import_message_extension, 0).d()); + EXPECT_EQ( + 227, + message.GetExtension(UNITTEST::repeated_lazy_message_extension, 0).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, + message.GetExtension(UNITTEST::repeated_nested_enum_extension, 0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, + message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 0)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, + message.GetExtension(UNITTEST::repeated_import_enum_extension, 0)); + + EXPECT_EQ("224", + message.GetExtension(UNITTEST::repeated_string_piece_extension, 0)); + EXPECT_EQ("225", message.GetExtension(UNITTEST::repeated_cord_extension, 0)); + + // Actually verify the second (modified) elements now. + EXPECT_EQ(501, message.GetExtension(UNITTEST::repeated_int32_extension, 1)); + EXPECT_EQ(502, message.GetExtension(UNITTEST::repeated_int64_extension, 1)); + EXPECT_EQ(503, message.GetExtension(UNITTEST::repeated_uint32_extension, 1)); + EXPECT_EQ(504, message.GetExtension(UNITTEST::repeated_uint64_extension, 1)); + EXPECT_EQ(505, message.GetExtension(UNITTEST::repeated_sint32_extension, 1)); + EXPECT_EQ(506, message.GetExtension(UNITTEST::repeated_sint64_extension, 1)); + EXPECT_EQ(507, message.GetExtension(UNITTEST::repeated_fixed32_extension, 1)); + EXPECT_EQ(508, message.GetExtension(UNITTEST::repeated_fixed64_extension, 1)); + EXPECT_EQ(509, + message.GetExtension(UNITTEST::repeated_sfixed32_extension, 1)); + EXPECT_EQ(510, + message.GetExtension(UNITTEST::repeated_sfixed64_extension, 1)); + EXPECT_EQ(511, message.GetExtension(UNITTEST::repeated_float_extension, 1)); + EXPECT_EQ(512, message.GetExtension(UNITTEST::repeated_double_extension, 1)); + EXPECT_TRUE(message.GetExtension(UNITTEST::repeated_bool_extension, 1)); + EXPECT_EQ("515", + message.GetExtension(UNITTEST::repeated_string_extension, 1)); + EXPECT_EQ("516", message.GetExtension(UNITTEST::repeated_bytes_extension, 1)); + + EXPECT_EQ(517, + message.GetExtension(UNITTEST::repeatedgroup_extension, 1).a()); + EXPECT_EQ(518, + message.GetExtension(UNITTEST::repeated_nested_message_extension, 1) + .bb()); + EXPECT_EQ( + 519, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 1) + .c()); + EXPECT_EQ( + 520, + message.GetExtension(UNITTEST::repeated_import_message_extension, 1).d()); + EXPECT_EQ( + 527, + message.GetExtension(UNITTEST::repeated_lazy_message_extension, 1).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::FOO, + message.GetExtension(UNITTEST::repeated_nested_enum_extension, 1)); + EXPECT_EQ(UNITTEST::FOREIGN_FOO, + message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 1)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_FOO, + message.GetExtension(UNITTEST::repeated_import_enum_extension, 1)); + + EXPECT_EQ("524", + message.GetExtension(UNITTEST::repeated_string_piece_extension, 1)); + EXPECT_EQ("525", message.GetExtension(UNITTEST::repeated_cord_extension, 1)); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::SetPackedExtensions( + UNITTEST::TestPackedExtensions* message) { + message->AddExtension(UNITTEST::packed_int32_extension, 601); + message->AddExtension(UNITTEST::packed_int64_extension, 602); + message->AddExtension(UNITTEST::packed_uint32_extension, 603); + message->AddExtension(UNITTEST::packed_uint64_extension, 604); + message->AddExtension(UNITTEST::packed_sint32_extension, 605); + message->AddExtension(UNITTEST::packed_sint64_extension, 606); + message->AddExtension(UNITTEST::packed_fixed32_extension, 607); + message->AddExtension(UNITTEST::packed_fixed64_extension, 608); + message->AddExtension(UNITTEST::packed_sfixed32_extension, 609); + message->AddExtension(UNITTEST::packed_sfixed64_extension, 610); + message->AddExtension(UNITTEST::packed_float_extension, 611); + message->AddExtension(UNITTEST::packed_double_extension, 612); + message->AddExtension(UNITTEST::packed_bool_extension, true); + message->AddExtension(UNITTEST::packed_enum_extension, UNITTEST::FOREIGN_BAR); + // add a second one of each field + message->AddExtension(UNITTEST::packed_int32_extension, 701); + message->AddExtension(UNITTEST::packed_int64_extension, 702); + message->AddExtension(UNITTEST::packed_uint32_extension, 703); + message->AddExtension(UNITTEST::packed_uint64_extension, 704); + message->AddExtension(UNITTEST::packed_sint32_extension, 705); + message->AddExtension(UNITTEST::packed_sint64_extension, 706); + message->AddExtension(UNITTEST::packed_fixed32_extension, 707); + message->AddExtension(UNITTEST::packed_fixed64_extension, 708); + message->AddExtension(UNITTEST::packed_sfixed32_extension, 709); + message->AddExtension(UNITTEST::packed_sfixed64_extension, 710); + message->AddExtension(UNITTEST::packed_float_extension, 711); + message->AddExtension(UNITTEST::packed_double_extension, 712); + message->AddExtension(UNITTEST::packed_bool_extension, false); + message->AddExtension(UNITTEST::packed_enum_extension, UNITTEST::FOREIGN_BAZ); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ModifyPackedExtensions( + UNITTEST::TestPackedExtensions* message) { + message->SetExtension(UNITTEST::packed_int32_extension, 1, 801); + message->SetExtension(UNITTEST::packed_int64_extension, 1, 802); + message->SetExtension(UNITTEST::packed_uint32_extension, 1, 803); + message->SetExtension(UNITTEST::packed_uint64_extension, 1, 804); + message->SetExtension(UNITTEST::packed_sint32_extension, 1, 805); + message->SetExtension(UNITTEST::packed_sint64_extension, 1, 806); + message->SetExtension(UNITTEST::packed_fixed32_extension, 1, 807); + message->SetExtension(UNITTEST::packed_fixed64_extension, 1, 808); + message->SetExtension(UNITTEST::packed_sfixed32_extension, 1, 809); + message->SetExtension(UNITTEST::packed_sfixed64_extension, 1, 810); + message->SetExtension(UNITTEST::packed_float_extension, 1, 811); + message->SetExtension(UNITTEST::packed_double_extension, 1, 812); + message->SetExtension(UNITTEST::packed_bool_extension, 1, true); + message->SetExtension(UNITTEST::packed_enum_extension, 1, + UNITTEST::FOREIGN_FOO); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectPackedExtensionsSet( + const UNITTEST::TestPackedExtensions& message) { + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_int32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_int64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_uint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_uint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_fixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_fixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sfixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sfixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_float_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_double_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_bool_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_enum_extension)); + + EXPECT_EQ(601, message.GetExtension(UNITTEST::packed_int32_extension, 0)); + EXPECT_EQ(602, message.GetExtension(UNITTEST::packed_int64_extension, 0)); + EXPECT_EQ(603, message.GetExtension(UNITTEST::packed_uint32_extension, 0)); + EXPECT_EQ(604, message.GetExtension(UNITTEST::packed_uint64_extension, 0)); + EXPECT_EQ(605, message.GetExtension(UNITTEST::packed_sint32_extension, 0)); + EXPECT_EQ(606, message.GetExtension(UNITTEST::packed_sint64_extension, 0)); + EXPECT_EQ(607, message.GetExtension(UNITTEST::packed_fixed32_extension, 0)); + EXPECT_EQ(608, message.GetExtension(UNITTEST::packed_fixed64_extension, 0)); + EXPECT_EQ(609, message.GetExtension(UNITTEST::packed_sfixed32_extension, 0)); + EXPECT_EQ(610, message.GetExtension(UNITTEST::packed_sfixed64_extension, 0)); + EXPECT_EQ(611, message.GetExtension(UNITTEST::packed_float_extension, 0)); + EXPECT_EQ(612, message.GetExtension(UNITTEST::packed_double_extension, 0)); + EXPECT_TRUE(message.GetExtension(UNITTEST::packed_bool_extension, 0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, + message.GetExtension(UNITTEST::packed_enum_extension, 0)); + EXPECT_EQ(701, message.GetExtension(UNITTEST::packed_int32_extension, 1)); + EXPECT_EQ(702, message.GetExtension(UNITTEST::packed_int64_extension, 1)); + EXPECT_EQ(703, message.GetExtension(UNITTEST::packed_uint32_extension, 1)); + EXPECT_EQ(704, message.GetExtension(UNITTEST::packed_uint64_extension, 1)); + EXPECT_EQ(705, message.GetExtension(UNITTEST::packed_sint32_extension, 1)); + EXPECT_EQ(706, message.GetExtension(UNITTEST::packed_sint64_extension, 1)); + EXPECT_EQ(707, message.GetExtension(UNITTEST::packed_fixed32_extension, 1)); + EXPECT_EQ(708, message.GetExtension(UNITTEST::packed_fixed64_extension, 1)); + EXPECT_EQ(709, message.GetExtension(UNITTEST::packed_sfixed32_extension, 1)); + EXPECT_EQ(710, message.GetExtension(UNITTEST::packed_sfixed64_extension, 1)); + EXPECT_EQ(711, message.GetExtension(UNITTEST::packed_float_extension, 1)); + EXPECT_EQ(712, message.GetExtension(UNITTEST::packed_double_extension, 1)); + EXPECT_FALSE(message.GetExtension(UNITTEST::packed_bool_extension, 1)); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, + message.GetExtension(UNITTEST::packed_enum_extension, 1)); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectPackedExtensionsClear( + const UNITTEST::TestPackedExtensions& message) { + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_int32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_int64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_uint32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_uint64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_sint32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_sint64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_fixed32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_fixed64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_sfixed32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_sfixed64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_float_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_double_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_bool_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_enum_extension)); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectPackedExtensionsModified( + const UNITTEST::TestPackedExtensions& message) { + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_int32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_int64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_uint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_uint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_fixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_fixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sfixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sfixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_float_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_double_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_bool_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_enum_extension)); + EXPECT_EQ(601, message.GetExtension(UNITTEST::packed_int32_extension, 0)); + EXPECT_EQ(602, message.GetExtension(UNITTEST::packed_int64_extension, 0)); + EXPECT_EQ(603, message.GetExtension(UNITTEST::packed_uint32_extension, 0)); + EXPECT_EQ(604, message.GetExtension(UNITTEST::packed_uint64_extension, 0)); + EXPECT_EQ(605, message.GetExtension(UNITTEST::packed_sint32_extension, 0)); + EXPECT_EQ(606, message.GetExtension(UNITTEST::packed_sint64_extension, 0)); + EXPECT_EQ(607, message.GetExtension(UNITTEST::packed_fixed32_extension, 0)); + EXPECT_EQ(608, message.GetExtension(UNITTEST::packed_fixed64_extension, 0)); + EXPECT_EQ(609, message.GetExtension(UNITTEST::packed_sfixed32_extension, 0)); + EXPECT_EQ(610, message.GetExtension(UNITTEST::packed_sfixed64_extension, 0)); + EXPECT_EQ(611, message.GetExtension(UNITTEST::packed_float_extension, 0)); + EXPECT_EQ(612, message.GetExtension(UNITTEST::packed_double_extension, 0)); + EXPECT_TRUE(message.GetExtension(UNITTEST::packed_bool_extension, 0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, + message.GetExtension(UNITTEST::packed_enum_extension, 0)); + + // Actually verify the second (modified) elements now. + EXPECT_EQ(801, message.GetExtension(UNITTEST::packed_int32_extension, 1)); + EXPECT_EQ(802, message.GetExtension(UNITTEST::packed_int64_extension, 1)); + EXPECT_EQ(803, message.GetExtension(UNITTEST::packed_uint32_extension, 1)); + EXPECT_EQ(804, message.GetExtension(UNITTEST::packed_uint64_extension, 1)); + EXPECT_EQ(805, message.GetExtension(UNITTEST::packed_sint32_extension, 1)); + EXPECT_EQ(806, message.GetExtension(UNITTEST::packed_sint64_extension, 1)); + EXPECT_EQ(807, message.GetExtension(UNITTEST::packed_fixed32_extension, 1)); + EXPECT_EQ(808, message.GetExtension(UNITTEST::packed_fixed64_extension, 1)); + EXPECT_EQ(809, message.GetExtension(UNITTEST::packed_sfixed32_extension, 1)); + EXPECT_EQ(810, message.GetExtension(UNITTEST::packed_sfixed64_extension, 1)); + EXPECT_EQ(811, message.GetExtension(UNITTEST::packed_float_extension, 1)); + EXPECT_EQ(812, message.GetExtension(UNITTEST::packed_double_extension, 1)); + EXPECT_TRUE(message.GetExtension(UNITTEST::packed_bool_extension, 1)); + EXPECT_EQ(UNITTEST::FOREIGN_FOO, + message.GetExtension(UNITTEST::packed_enum_extension, 1)); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectUnpackedExtensionsSet( + const UNITTEST::TestUnpackedExtensions& message) { + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_int32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_int64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_uint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_uint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_sint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_sint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_fixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_fixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_sfixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_sfixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_float_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_double_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_bool_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_enum_extension)); + + EXPECT_EQ(601, message.GetExtension(UNITTEST::unpacked_int32_extension, 0)); + EXPECT_EQ(602, message.GetExtension(UNITTEST::unpacked_int64_extension, 0)); + EXPECT_EQ(603, message.GetExtension(UNITTEST::unpacked_uint32_extension, 0)); + EXPECT_EQ(604, message.GetExtension(UNITTEST::unpacked_uint64_extension, 0)); + EXPECT_EQ(605, message.GetExtension(UNITTEST::unpacked_sint32_extension, 0)); + EXPECT_EQ(606, message.GetExtension(UNITTEST::unpacked_sint64_extension, 0)); + EXPECT_EQ(607, message.GetExtension(UNITTEST::unpacked_fixed32_extension, 0)); + EXPECT_EQ(608, message.GetExtension(UNITTEST::unpacked_fixed64_extension, 0)); + EXPECT_EQ(609, + message.GetExtension(UNITTEST::unpacked_sfixed32_extension, 0)); + EXPECT_EQ(610, + message.GetExtension(UNITTEST::unpacked_sfixed64_extension, 0)); + EXPECT_EQ(611, message.GetExtension(UNITTEST::unpacked_float_extension, 0)); + EXPECT_EQ(612, message.GetExtension(UNITTEST::unpacked_double_extension, 0)); + EXPECT_EQ(true, message.GetExtension(UNITTEST::unpacked_bool_extension, 0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, + message.GetExtension(UNITTEST::unpacked_enum_extension, 0)); + EXPECT_EQ(701, message.GetExtension(UNITTEST::unpacked_int32_extension, 1)); + EXPECT_EQ(702, message.GetExtension(UNITTEST::unpacked_int64_extension, 1)); + EXPECT_EQ(703, message.GetExtension(UNITTEST::unpacked_uint32_extension, 1)); + EXPECT_EQ(704, message.GetExtension(UNITTEST::unpacked_uint64_extension, 1)); + EXPECT_EQ(705, message.GetExtension(UNITTEST::unpacked_sint32_extension, 1)); + EXPECT_EQ(706, message.GetExtension(UNITTEST::unpacked_sint64_extension, 1)); + EXPECT_EQ(707, message.GetExtension(UNITTEST::unpacked_fixed32_extension, 1)); + EXPECT_EQ(708, message.GetExtension(UNITTEST::unpacked_fixed64_extension, 1)); + EXPECT_EQ(709, + message.GetExtension(UNITTEST::unpacked_sfixed32_extension, 1)); + EXPECT_EQ(710, + message.GetExtension(UNITTEST::unpacked_sfixed64_extension, 1)); + EXPECT_EQ(711, message.GetExtension(UNITTEST::unpacked_float_extension, 1)); + EXPECT_EQ(712, message.GetExtension(UNITTEST::unpacked_double_extension, 1)); + EXPECT_EQ(false, message.GetExtension(UNITTEST::unpacked_bool_extension, 1)); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, + message.GetExtension(UNITTEST::unpacked_enum_extension, 1)); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectLastRepeatedsRemoved( + const UNITTEST::TestAllTypes& message) { + ASSERT_EQ(1, message.repeated_int32_size()); + ASSERT_EQ(1, message.repeated_int64_size()); + ASSERT_EQ(1, message.repeated_uint32_size()); + ASSERT_EQ(1, message.repeated_uint64_size()); + ASSERT_EQ(1, message.repeated_sint32_size()); + ASSERT_EQ(1, message.repeated_sint64_size()); + ASSERT_EQ(1, message.repeated_fixed32_size()); + ASSERT_EQ(1, message.repeated_fixed64_size()); + ASSERT_EQ(1, message.repeated_sfixed32_size()); + ASSERT_EQ(1, message.repeated_sfixed64_size()); + ASSERT_EQ(1, message.repeated_float_size()); + ASSERT_EQ(1, message.repeated_double_size()); + ASSERT_EQ(1, message.repeated_bool_size()); + ASSERT_EQ(1, message.repeated_string_size()); + ASSERT_EQ(1, message.repeated_bytes_size()); + + ASSERT_EQ(1, message.repeatedgroup_size()); + ASSERT_EQ(1, message.repeated_nested_message_size()); + ASSERT_EQ(1, message.repeated_foreign_message_size()); + ASSERT_EQ(1, message.repeated_import_message_size()); + ASSERT_EQ(1, message.repeated_import_message_size()); + ASSERT_EQ(1, message.repeated_nested_enum_size()); + ASSERT_EQ(1, message.repeated_foreign_enum_size()); + ASSERT_EQ(1, message.repeated_import_enum_size()); + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + ASSERT_EQ(1, message.repeated_string_piece_size()); + ASSERT_EQ(1, message.repeated_cord_size()); +#endif + + // Test that the remaining element is the correct one. + EXPECT_EQ(201, message.repeated_int32(0)); + EXPECT_EQ(202, message.repeated_int64(0)); + EXPECT_EQ(203, message.repeated_uint32(0)); + EXPECT_EQ(204, message.repeated_uint64(0)); + EXPECT_EQ(205, message.repeated_sint32(0)); + EXPECT_EQ(206, message.repeated_sint64(0)); + EXPECT_EQ(207, message.repeated_fixed32(0)); + EXPECT_EQ(208, message.repeated_fixed64(0)); + EXPECT_EQ(209, message.repeated_sfixed32(0)); + EXPECT_EQ(210, message.repeated_sfixed64(0)); + EXPECT_EQ(211, message.repeated_float(0)); + EXPECT_EQ(212, message.repeated_double(0)); + EXPECT_TRUE(message.repeated_bool(0)); + EXPECT_EQ("215", message.repeated_string(0)); + EXPECT_EQ("216", message.repeated_bytes(0)); + + EXPECT_EQ(217, message.repeatedgroup(0).a()); + EXPECT_EQ(218, message.repeated_nested_message(0).bb()); + EXPECT_EQ(219, message.repeated_foreign_message(0).c()); + EXPECT_EQ(220, message.repeated_import_message(0).d()); + EXPECT_EQ(220, message.repeated_import_message(0).d()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message.repeated_nested_enum(0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.repeated_foreign_enum(0)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, message.repeated_import_enum(0)); +} + +inline void TestUtil::ExpectLastRepeatedExtensionsRemoved( + const UNITTEST::TestAllExtensions& message) { + // Test that one element was removed. + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_int32_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_int64_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_uint32_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_uint64_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_sint32_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_sint64_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_fixed32_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_fixed64_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_sfixed32_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_sfixed64_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_float_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_double_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_bool_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_string_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_bytes_extension)); + + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeatedgroup_extension)); + ASSERT_EQ(1, + message.ExtensionSize(UNITTEST::repeated_nested_message_extension)); + ASSERT_EQ( + 1, message.ExtensionSize(UNITTEST::repeated_foreign_message_extension)); + ASSERT_EQ(1, + message.ExtensionSize(UNITTEST::repeated_import_message_extension)); + ASSERT_EQ(1, + message.ExtensionSize(UNITTEST::repeated_lazy_message_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_nested_enum_extension)); + ASSERT_EQ(1, + message.ExtensionSize(UNITTEST::repeated_foreign_enum_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_import_enum_extension)); + + ASSERT_EQ(1, + message.ExtensionSize(UNITTEST::repeated_string_piece_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_cord_extension)); + + // Test that the remaining element is the correct one. + EXPECT_EQ(201, message.GetExtension(UNITTEST::repeated_int32_extension, 0)); + EXPECT_EQ(202, message.GetExtension(UNITTEST::repeated_int64_extension, 0)); + EXPECT_EQ(203, message.GetExtension(UNITTEST::repeated_uint32_extension, 0)); + EXPECT_EQ(204, message.GetExtension(UNITTEST::repeated_uint64_extension, 0)); + EXPECT_EQ(205, message.GetExtension(UNITTEST::repeated_sint32_extension, 0)); + EXPECT_EQ(206, message.GetExtension(UNITTEST::repeated_sint64_extension, 0)); + EXPECT_EQ(207, message.GetExtension(UNITTEST::repeated_fixed32_extension, 0)); + EXPECT_EQ(208, message.GetExtension(UNITTEST::repeated_fixed64_extension, 0)); + EXPECT_EQ(209, + message.GetExtension(UNITTEST::repeated_sfixed32_extension, 0)); + EXPECT_EQ(210, + message.GetExtension(UNITTEST::repeated_sfixed64_extension, 0)); + EXPECT_EQ(211, message.GetExtension(UNITTEST::repeated_float_extension, 0)); + EXPECT_EQ(212, message.GetExtension(UNITTEST::repeated_double_extension, 0)); + EXPECT_TRUE(message.GetExtension(UNITTEST::repeated_bool_extension, 0)); + EXPECT_EQ("215", + message.GetExtension(UNITTEST::repeated_string_extension, 0)); + EXPECT_EQ("216", message.GetExtension(UNITTEST::repeated_bytes_extension, 0)); + + EXPECT_EQ(217, + message.GetExtension(UNITTEST::repeatedgroup_extension, 0).a()); + EXPECT_EQ(218, + message.GetExtension(UNITTEST::repeated_nested_message_extension, 0) + .bb()); + EXPECT_EQ( + 219, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 0) + .c()); + EXPECT_EQ( + 220, + message.GetExtension(UNITTEST::repeated_import_message_extension, 0).d()); + EXPECT_EQ( + 227, + message.GetExtension(UNITTEST::repeated_lazy_message_extension, 0).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, + message.GetExtension(UNITTEST::repeated_nested_enum_extension, 0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, + message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 0)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, + message.GetExtension(UNITTEST::repeated_import_enum_extension, 0)); + + EXPECT_EQ("224", + message.GetExtension(UNITTEST::repeated_string_piece_extension, 0)); + EXPECT_EQ("225", message.GetExtension(UNITTEST::repeated_cord_extension, 0)); +} + +inline void TestUtil::ExpectLastRepeatedsReleased( + const UNITTEST::TestAllTypes& message) { + ASSERT_EQ(1, message.repeatedgroup_size()); + ASSERT_EQ(1, message.repeated_nested_message_size()); + ASSERT_EQ(1, message.repeated_foreign_message_size()); + ASSERT_EQ(1, message.repeated_import_message_size()); + ASSERT_EQ(1, message.repeated_import_message_size()); + + EXPECT_EQ(217, message.repeatedgroup(0).a()); + EXPECT_EQ(218, message.repeated_nested_message(0).bb()); + EXPECT_EQ(219, message.repeated_foreign_message(0).c()); + EXPECT_EQ(220, message.repeated_import_message(0).d()); + EXPECT_EQ(220, message.repeated_import_message(0).d()); +} + +inline void TestUtil::ExpectLastRepeatedExtensionsReleased( + const UNITTEST::TestAllExtensions& message) { + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeatedgroup_extension)); + ASSERT_EQ(1, + message.ExtensionSize(UNITTEST::repeated_nested_message_extension)); + ASSERT_EQ( + 1, message.ExtensionSize(UNITTEST::repeated_foreign_message_extension)); + ASSERT_EQ(1, + message.ExtensionSize(UNITTEST::repeated_import_message_extension)); + ASSERT_EQ(1, + message.ExtensionSize(UNITTEST::repeated_lazy_message_extension)); + + EXPECT_EQ(217, + message.GetExtension(UNITTEST::repeatedgroup_extension, 0).a()); + EXPECT_EQ(218, + message.GetExtension(UNITTEST::repeated_nested_message_extension, 0) + .bb()); + EXPECT_EQ( + 219, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 0) + .c()); + EXPECT_EQ( + 220, + message.GetExtension(UNITTEST::repeated_import_message_extension, 0).d()); + EXPECT_EQ( + 227, + message.GetExtension(UNITTEST::repeated_lazy_message_extension, 0).bb()); +} + +inline void TestUtil::ExpectRepeatedsSwapped( + const UNITTEST::TestAllTypes& message) { + ASSERT_EQ(2, message.repeated_int32_size()); + ASSERT_EQ(2, message.repeated_int64_size()); + ASSERT_EQ(2, message.repeated_uint32_size()); + ASSERT_EQ(2, message.repeated_uint64_size()); + ASSERT_EQ(2, message.repeated_sint32_size()); + ASSERT_EQ(2, message.repeated_sint64_size()); + ASSERT_EQ(2, message.repeated_fixed32_size()); + ASSERT_EQ(2, message.repeated_fixed64_size()); + ASSERT_EQ(2, message.repeated_sfixed32_size()); + ASSERT_EQ(2, message.repeated_sfixed64_size()); + ASSERT_EQ(2, message.repeated_float_size()); + ASSERT_EQ(2, message.repeated_double_size()); + ASSERT_EQ(2, message.repeated_bool_size()); + ASSERT_EQ(2, message.repeated_string_size()); + ASSERT_EQ(2, message.repeated_bytes_size()); + + ASSERT_EQ(2, message.repeatedgroup_size()); + ASSERT_EQ(2, message.repeated_nested_message_size()); + ASSERT_EQ(2, message.repeated_foreign_message_size()); + ASSERT_EQ(2, message.repeated_import_message_size()); + ASSERT_EQ(2, message.repeated_import_message_size()); + ASSERT_EQ(2, message.repeated_nested_enum_size()); + ASSERT_EQ(2, message.repeated_foreign_enum_size()); + ASSERT_EQ(2, message.repeated_import_enum_size()); + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + ASSERT_EQ(2, message.repeated_string_piece_size()); + ASSERT_EQ(2, message.repeated_cord_size()); +#endif + + // Test that the first element and second element are flipped. + EXPECT_EQ(201, message.repeated_int32(1)); + EXPECT_EQ(202, message.repeated_int64(1)); + EXPECT_EQ(203, message.repeated_uint32(1)); + EXPECT_EQ(204, message.repeated_uint64(1)); + EXPECT_EQ(205, message.repeated_sint32(1)); + EXPECT_EQ(206, message.repeated_sint64(1)); + EXPECT_EQ(207, message.repeated_fixed32(1)); + EXPECT_EQ(208, message.repeated_fixed64(1)); + EXPECT_EQ(209, message.repeated_sfixed32(1)); + EXPECT_EQ(210, message.repeated_sfixed64(1)); + EXPECT_EQ(211, message.repeated_float(1)); + EXPECT_EQ(212, message.repeated_double(1)); + EXPECT_TRUE(message.repeated_bool(1)); + EXPECT_EQ("215", message.repeated_string(1)); + EXPECT_EQ("216", message.repeated_bytes(1)); + + EXPECT_EQ(217, message.repeatedgroup(1).a()); + EXPECT_EQ(218, message.repeated_nested_message(1).bb()); + EXPECT_EQ(219, message.repeated_foreign_message(1).c()); + EXPECT_EQ(220, message.repeated_import_message(1).d()); + EXPECT_EQ(220, message.repeated_import_message(1).d()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message.repeated_nested_enum(1)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.repeated_foreign_enum(1)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, message.repeated_import_enum(1)); + + EXPECT_EQ(301, message.repeated_int32(0)); + EXPECT_EQ(302, message.repeated_int64(0)); + EXPECT_EQ(303, message.repeated_uint32(0)); + EXPECT_EQ(304, message.repeated_uint64(0)); + EXPECT_EQ(305, message.repeated_sint32(0)); + EXPECT_EQ(306, message.repeated_sint64(0)); + EXPECT_EQ(307, message.repeated_fixed32(0)); + EXPECT_EQ(308, message.repeated_fixed64(0)); + EXPECT_EQ(309, message.repeated_sfixed32(0)); + EXPECT_EQ(310, message.repeated_sfixed64(0)); + EXPECT_EQ(311, message.repeated_float(0)); + EXPECT_EQ(312, message.repeated_double(0)); + EXPECT_FALSE(message.repeated_bool(0)); + EXPECT_EQ("315", message.repeated_string(0)); + EXPECT_EQ("316", message.repeated_bytes(0)); + + EXPECT_EQ(317, message.repeatedgroup(0).a()); + EXPECT_EQ(318, message.repeated_nested_message(0).bb()); + EXPECT_EQ(319, message.repeated_foreign_message(0).c()); + EXPECT_EQ(320, message.repeated_import_message(0).d()); + EXPECT_EQ(320, message.repeated_import_message(0).d()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, message.repeated_nested_enum(0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, message.repeated_foreign_enum(0)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAZ, message.repeated_import_enum(0)); +} + +inline void TestUtil::ExpectRepeatedExtensionsSwapped( + const UNITTEST::TestAllExtensions& message) { + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_int32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_int64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_uint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_uint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_fixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_fixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sfixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sfixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_float_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_double_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_bool_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_string_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_bytes_extension)); + + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeatedgroup_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_nested_message_extension)); + ASSERT_EQ( + 2, message.ExtensionSize(UNITTEST::repeated_foreign_message_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_import_message_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_lazy_message_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_nested_enum_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_foreign_enum_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_import_enum_extension)); + + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_string_piece_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_cord_extension)); + + EXPECT_EQ(201, message.GetExtension(UNITTEST::repeated_int32_extension, 1)); + EXPECT_EQ(202, message.GetExtension(UNITTEST::repeated_int64_extension, 1)); + EXPECT_EQ(203, message.GetExtension(UNITTEST::repeated_uint32_extension, 1)); + EXPECT_EQ(204, message.GetExtension(UNITTEST::repeated_uint64_extension, 1)); + EXPECT_EQ(205, message.GetExtension(UNITTEST::repeated_sint32_extension, 1)); + EXPECT_EQ(206, message.GetExtension(UNITTEST::repeated_sint64_extension, 1)); + EXPECT_EQ(207, message.GetExtension(UNITTEST::repeated_fixed32_extension, 1)); + EXPECT_EQ(208, message.GetExtension(UNITTEST::repeated_fixed64_extension, 1)); + EXPECT_EQ(209, + message.GetExtension(UNITTEST::repeated_sfixed32_extension, 1)); + EXPECT_EQ(210, + message.GetExtension(UNITTEST::repeated_sfixed64_extension, 1)); + EXPECT_EQ(211, message.GetExtension(UNITTEST::repeated_float_extension, 1)); + EXPECT_EQ(212, message.GetExtension(UNITTEST::repeated_double_extension, 1)); + EXPECT_TRUE(message.GetExtension(UNITTEST::repeated_bool_extension, 1)); + EXPECT_EQ("215", + message.GetExtension(UNITTEST::repeated_string_extension, 1)); + EXPECT_EQ("216", message.GetExtension(UNITTEST::repeated_bytes_extension, 1)); + + EXPECT_EQ(217, + message.GetExtension(UNITTEST::repeatedgroup_extension, 1).a()); + EXPECT_EQ(218, + message.GetExtension(UNITTEST::repeated_nested_message_extension, 1) + .bb()); + EXPECT_EQ( + 219, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 1) + .c()); + EXPECT_EQ( + 220, + message.GetExtension(UNITTEST::repeated_import_message_extension, 1).d()); + EXPECT_EQ( + 227, + message.GetExtension(UNITTEST::repeated_lazy_message_extension, 1).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, + message.GetExtension(UNITTEST::repeated_nested_enum_extension, 1)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, + message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 1)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, + message.GetExtension(UNITTEST::repeated_import_enum_extension, 1)); + + EXPECT_EQ("224", + message.GetExtension(UNITTEST::repeated_string_piece_extension, 1)); + EXPECT_EQ("225", message.GetExtension(UNITTEST::repeated_cord_extension, 1)); + + EXPECT_EQ(301, message.GetExtension(UNITTEST::repeated_int32_extension, 0)); + EXPECT_EQ(302, message.GetExtension(UNITTEST::repeated_int64_extension, 0)); + EXPECT_EQ(303, message.GetExtension(UNITTEST::repeated_uint32_extension, 0)); + EXPECT_EQ(304, message.GetExtension(UNITTEST::repeated_uint64_extension, 0)); + EXPECT_EQ(305, message.GetExtension(UNITTEST::repeated_sint32_extension, 0)); + EXPECT_EQ(306, message.GetExtension(UNITTEST::repeated_sint64_extension, 0)); + EXPECT_EQ(307, message.GetExtension(UNITTEST::repeated_fixed32_extension, 0)); + EXPECT_EQ(308, message.GetExtension(UNITTEST::repeated_fixed64_extension, 0)); + EXPECT_EQ(309, + message.GetExtension(UNITTEST::repeated_sfixed32_extension, 0)); + EXPECT_EQ(310, + message.GetExtension(UNITTEST::repeated_sfixed64_extension, 0)); + EXPECT_EQ(311, message.GetExtension(UNITTEST::repeated_float_extension, 0)); + EXPECT_EQ(312, message.GetExtension(UNITTEST::repeated_double_extension, 0)); + EXPECT_FALSE(message.GetExtension(UNITTEST::repeated_bool_extension, 0)); + EXPECT_EQ("315", + message.GetExtension(UNITTEST::repeated_string_extension, 0)); + EXPECT_EQ("316", message.GetExtension(UNITTEST::repeated_bytes_extension, 0)); + + EXPECT_EQ(317, + message.GetExtension(UNITTEST::repeatedgroup_extension, 0).a()); + EXPECT_EQ(318, + message.GetExtension(UNITTEST::repeated_nested_message_extension, 0) + .bb()); + EXPECT_EQ( + 319, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 0) + .c()); + EXPECT_EQ( + 320, + message.GetExtension(UNITTEST::repeated_import_message_extension, 0).d()); + EXPECT_EQ( + 327, + message.GetExtension(UNITTEST::repeated_lazy_message_extension, 0).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, + message.GetExtension(UNITTEST::repeated_nested_enum_extension, 0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, + message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 0)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAZ, + message.GetExtension(UNITTEST::repeated_import_enum_extension, 0)); + + EXPECT_EQ("324", + message.GetExtension(UNITTEST::repeated_string_piece_extension, 0)); + EXPECT_EQ("325", message.GetExtension(UNITTEST::repeated_cord_extension, 0)); +} + +inline void TestUtil::SetOneof1(UNITTEST::TestOneof2* message) { + message->mutable_foo_lazy_message()->set_qux_int(100); + message->set_bar_string("101"); + message->set_baz_int(102); + message->set_baz_string("103"); +} + +inline void TestUtil::SetOneof2(UNITTEST::TestOneof2* message) { + message->set_foo_int(200); + message->set_bar_enum(UNITTEST::TestOneof2::BAZ); + message->set_baz_int(202); + message->set_baz_string("203"); +} + +inline void TestUtil::ExpectOneofSet1(const UNITTEST::TestOneof2& message) { + ExpectAtMostOneFieldSetInOneof(message); + + EXPECT_TRUE(message.has_foo_lazy_message()); + EXPECT_TRUE(message.foo_lazy_message().has_qux_int()); + + EXPECT_TRUE(message.has_bar_string()); + EXPECT_TRUE(message.has_baz_int()); + EXPECT_TRUE(message.has_baz_string()); + + ASSERT_EQ(0, message.foo_lazy_message().corge_int_size()); + + EXPECT_EQ(100, message.foo_lazy_message().qux_int()); + EXPECT_EQ("101", message.bar_string()); + EXPECT_EQ(102, message.baz_int()); + EXPECT_EQ("103", message.baz_string()); +} + +inline void TestUtil::ExpectOneofSet2(const UNITTEST::TestOneof2& message) { + ExpectAtMostOneFieldSetInOneof(message); + + EXPECT_TRUE(message.has_foo_int()); + EXPECT_TRUE(message.has_bar_enum()); + EXPECT_TRUE(message.has_baz_int()); + EXPECT_TRUE(message.has_baz_string()); + + EXPECT_EQ(200, message.foo_int()); + EXPECT_EQ(UNITTEST::TestOneof2::BAZ, message.bar_enum()); + EXPECT_EQ(202, message.baz_int()); + EXPECT_EQ("203", message.baz_string()); +} + +inline void TestUtil::ExpectOneofClear(const UNITTEST::TestOneof2& message) { + EXPECT_FALSE(message.has_foo_int()); + EXPECT_FALSE(message.has_foo_string()); + EXPECT_FALSE(message.has_foo_bytes()); + EXPECT_FALSE(message.has_foo_enum()); + EXPECT_FALSE(message.has_foo_message()); + EXPECT_FALSE(message.has_foogroup()); + EXPECT_FALSE(message.has_foo_lazy_message()); + + EXPECT_FALSE(message.has_bar_int()); + EXPECT_FALSE(message.has_bar_string()); + EXPECT_FALSE(message.has_bar_bytes()); + EXPECT_FALSE(message.has_bar_enum()); + + EXPECT_FALSE(message.has_baz_int()); + EXPECT_FALSE(message.has_baz_string()); + + EXPECT_EQ(UNITTEST::TestOneof2::FOO_NOT_SET, message.foo_case()); + EXPECT_EQ(UNITTEST::TestOneof2::BAR_NOT_SET, message.bar_case()); +} + +inline void TestUtil::ExpectAtMostOneFieldSetInOneof( + const UNITTEST::TestOneof2& message) { + int count = 0; + if (message.has_foo_int()) count++; + if (message.has_foo_string()) count++; + if (message.has_foo_bytes()) count++; + if (message.has_foo_enum()) count++; + if (message.has_foo_message()) count++; + if (message.has_foogroup()) count++; + if (message.has_foo_lazy_message()) count++; + EXPECT_LE(count, 1); + count = 0; + if (message.has_bar_int()) count++; + if (message.has_bar_string()) count++; + if (message.has_bar_bytes()) count++; + if (message.has_bar_enum()) count++; + EXPECT_TRUE(count == 0 || count == 1); +} + +// =================================================================== + +} // namespace protobuf +} // namespace google diff --git a/src/google/protobuf/testing/googletest.cc b/src/google/protobuf/testing/googletest.cc index b81d3994..8c89e5af 100644 --- a/src/google/protobuf/testing/googletest.cc +++ b/src/google/protobuf/testing/googletest.cc @@ -263,7 +263,7 @@ ScopedMemoryLog::~ScopedMemoryLog() { active_log_ = NULL; } -const vector<string>& ScopedMemoryLog::GetMessages(LogLevel level) { +const std::vector<string>& ScopedMemoryLog::GetMessages(LogLevel level) { GOOGLE_CHECK(level == ERROR || level == WARNING); return messages_[level]; diff --git a/src/google/protobuf/testing/googletest.h b/src/google/protobuf/testing/googletest.h index 2db3bfee..81637486 100644 --- a/src/google/protobuf/testing/googletest.h +++ b/src/google/protobuf/testing/googletest.h @@ -83,10 +83,10 @@ class ScopedMemoryLog { virtual ~ScopedMemoryLog(); // Fetches all messages with the given severity level. - const vector<string>& GetMessages(LogLevel error); + const std::vector<string>& GetMessages(LogLevel error); private: - std::map<LogLevel, vector<string> > messages_; + std::map<LogLevel, std::vector<string> > messages_; LogHandler* old_handler_; static void HandleLog(LogLevel level, const char* filename, int line, diff --git a/src/google/protobuf/text_format.cc b/src/google/protobuf/text_format.cc index eed2a768..0965fd7a 100644 --- a/src/google/protobuf/text_format.cc +++ b/src/google/protobuf/text_format.cc @@ -57,6 +57,7 @@ #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/stubs/strutil.h> + #include <google/protobuf/stubs/map_util.h> #include <google/protobuf/stubs/stl_util.h> @@ -189,6 +190,24 @@ TextFormat::ParseInfoTree* TextFormat::ParseInfoTree::GetTreeForNested( return (*trees)[index]; } +namespace { +// These functions implement the behavior of the "default" TextFormat::Finder, +// they are defined as standalone to be called when finder_ is NULL. +const FieldDescriptor* DefaultFinderFindExtension(Message* message, + const string& name) { + return message->GetReflection()->FindKnownExtensionByName(name); +} + +const Descriptor* DefaultFinderFindAnyType(const Message& message, + const string& prefix, + const string& name) { + if (prefix != internal::kTypeGoogleApisComPrefix && + prefix != internal::kTypeGoogleProdComPrefix) { + return NULL; + } + return message.GetDescriptor()->file()->pool()->FindMessageTypeByName(name); +} +} // namespace // =========================================================================== // Internal class for parsing an ASCII representation of a Protocol Message. @@ -217,7 +236,7 @@ class TextFormat::Parser::ParserImpl { ParserImpl(const Descriptor* root_message_type, io::ZeroCopyInputStream* input_stream, io::ErrorCollector* error_collector, - TextFormat::Finder* finder, + const TextFormat::Finder* finder, ParseInfoTree* parse_info_tree, SingularOverwritePolicy singular_overwrite_policy, bool allow_case_insensitive_field, @@ -380,9 +399,15 @@ class TextFormat::Parser::ParserImpl { DO(Consume("]")); TryConsume(":"); // ':' is optional between message labels and values. string serialized_value; - DO(ConsumeAnyValue(full_type_name, - message->GetDescriptor()->file()->pool(), - &serialized_value)); + const Descriptor* value_descriptor = + finder_ ? finder_->FindAnyType(*message, prefix, full_type_name) + : DefaultFinderFindAnyType(*message, prefix, full_type_name); + if (value_descriptor == NULL) { + ReportError("Could not find type \"" + prefix + full_type_name + + "\" stored in google.protobuf.Any."); + return false; + } + DO(ConsumeAnyValue(value_descriptor, &serialized_value)); if (singular_overwrite_policy_ == FORBID_SINGULAR_OVERWRITES) { // Fail if any_type_url_field has already been specified. if ((!any_type_url_field->is_repeated() && @@ -404,9 +429,8 @@ class TextFormat::Parser::ParserImpl { DO(ConsumeFullTypeName(&field_name)); DO(Consume("]")); - field = (finder_ != NULL - ? finder_->FindExtension(message, field_name) - : reflection->FindKnownExtensionByName(field_name)); + field = finder_ ? finder_->FindExtension(message, field_name) + : DefaultFinderFindExtension(message, field_name); if (field == NULL) { if (!allow_unknown_field_) { @@ -572,12 +596,12 @@ label_skip_parsing: // Skips the next field including the field's name and value. bool SkipField() { - string field_name; if (TryConsume("[")) { - // Extension name. - DO(ConsumeFullTypeName(&field_name)); + // Extension name or type URL. + DO(ConsumeTypeUrlOrFullTypeName()); DO(Consume("]")); } else { + string field_name; DO(ConsumeIdentifier(&field_name)); } @@ -881,6 +905,15 @@ label_skip_parsing: return true; } + bool ConsumeTypeUrlOrFullTypeName() { + string discarded; + DO(ConsumeIdentifier(&discarded)); + while (TryConsume(".") || TryConsume("/")) { + DO(ConsumeIdentifier(&discarded)); + } + return true; + } + // Consumes a string and saves its value in the text parameter. // Returns false if the token is not of type STRING. bool ConsumeString(string* text) { @@ -1029,44 +1062,29 @@ label_skip_parsing: bool ConsumeAnyTypeUrl(string* full_type_name, string* prefix) { // TODO(saito) Extend Consume() to consume multiple tokens at once, so that // this code can be written as just DO(Consume(kGoogleApisTypePrefix)). - string url1, url2, url3; - DO(ConsumeIdentifier(&url1)); // type - DO(Consume(".")); - DO(ConsumeIdentifier(&url2)); // googleapis - DO(Consume(".")); - DO(ConsumeIdentifier(&url3)); // com + DO(ConsumeIdentifier(prefix)); + while (TryConsume(".")) { + string url; + DO(ConsumeIdentifier(&url)); + *prefix += "." + url; + } DO(Consume("/")); + *prefix += "/"; DO(ConsumeFullTypeName(full_type_name)); - *prefix = url1 + "." + url2 + "." + url3 + "/"; - if (*prefix != internal::kTypeGoogleApisComPrefix && - *prefix != internal::kTypeGoogleProdComPrefix) { - ReportError("TextFormat::Parser for Any supports only " - "type.googleapis.com and type.googleprod.com, " - "but found \"" + *prefix + "\""); - return false; - } return true; } // A helper function for reconstructing Any::value. Consumes a text of - // full_type_name, then serializes it into serialized_value. "pool" is used to - // look up and create a temporary object with full_type_name. - bool ConsumeAnyValue(const string& full_type_name, const DescriptorPool* pool, + // full_type_name, then serializes it into serialized_value. + bool ConsumeAnyValue(const Descriptor* value_descriptor, string* serialized_value) { - const Descriptor* value_descriptor = - pool->FindMessageTypeByName(full_type_name); - if (value_descriptor == NULL) { - ReportError("Could not find type \"" + full_type_name + - "\" stored in google.protobuf.Any."); - return false; - } DynamicMessageFactory factory; const Message* value_prototype = factory.GetPrototype(value_descriptor); if (value_prototype == NULL) { return false; } - google::protobuf::scoped_ptr<Message> value(value_prototype->New()); + std::unique_ptr<Message> value(value_prototype->New()); string sub_delimiter; DO(ConsumeMessageDelimiter(&sub_delimiter)); DO(ConsumeMessage(value.get(), sub_delimiter)); @@ -1076,7 +1094,7 @@ label_skip_parsing: } else { if (!value->IsInitialized()) { ReportError( - "Value of type \"" + full_type_name + + "Value of type \"" + value_descriptor->full_name() + "\" stored in google.protobuf.Any has missing required fields"); return false; } @@ -1136,7 +1154,7 @@ label_skip_parsing: }; io::ErrorCollector* error_collector_; - TextFormat::Finder* finder_; + const TextFormat::Finder* finder_; ParseInfoTree* parse_info_tree_; ParserErrorCollector tokenizer_error_collector_; io::Tokenizer tokenizer_; @@ -1180,13 +1198,11 @@ class TextFormat::Printer::TextGenerator // Indent text by two spaces. After calling Indent(), two spaces will be // inserted at the beginning of each line of text. Indent() may be called // multiple times to produce deeper indents. - void Indent() { - ++indent_level_; - } + void Indent() override { ++indent_level_; } // Reduces the current indent level by two spaces, or crashes if the indent // level is zero. - void Outdent() { + void Outdent() override { if (indent_level_ == 0 || indent_level_ < initial_indent_level_) { GOOGLE_LOG(DFATAL) << " Outdent() without matching Indent()."; @@ -1197,7 +1213,7 @@ class TextFormat::Printer::TextGenerator } // Print text to the output stream. - void Print(const char* text, size_t size) { + void Print(const char* text, size_t size) override { if (indent_level_ > 0) { size_t pos = 0; // The number of bytes we've written so far. for (size_t i = 0; i < size; i++) { @@ -1294,10 +1310,23 @@ class TextFormat::Printer::TextGenerator }; // =========================================================================== - +// Implementation of the default Finder for extensions. TextFormat::Finder::~Finder() { } +const FieldDescriptor* TextFormat::Finder::FindExtension( + Message* message, const string& name) const { + return DefaultFinderFindExtension(message, name); +} + +const Descriptor* TextFormat::Finder::FindAnyType(const Message& message, + const string& prefix, + const string& name) const { + return DefaultFinderFindAnyType(message, prefix, name); +} + +// =========================================================================== + TextFormat::Parser::Parser() : error_collector_(NULL), finder_(NULL), @@ -1363,8 +1392,9 @@ bool TextFormat::Parser::MergeUsingImpl(io::ZeroCopyInputStream* /* input */, if (!allow_partial_ && !output->IsInitialized()) { std::vector<string> missing_fields; output->FindInitializationErrors(&missing_fields); - parser_impl->ReportError(-1, 0, "Message missing required fields: " + - Join(missing_fields, ", ")); + parser_impl->ReportError(-1, 0, + "Message missing required fields: " + + Join(missing_fields, ", ")); return false; } return true; @@ -1553,6 +1583,12 @@ void TextFormat::FastFieldValuePrinter::PrintBytes( PrintString(val, generator); } void TextFormat::FastFieldValuePrinter::PrintFieldName( + const Message& message, int field_index, int field_count, + const Reflection* reflection, const FieldDescriptor* field, + BaseTextGenerator* generator) const { + PrintFieldName(message, reflection, field, generator); +} +void TextFormat::FastFieldValuePrinter::PrintFieldName( const Message& message, const Reflection* reflection, const FieldDescriptor* field, BaseTextGenerator* generator) const { if (field->is_extension()) { @@ -1639,6 +1675,13 @@ class FieldValuePrinterWrapper : public TextFormat::FastFieldValuePrinter { TextFormat::BaseTextGenerator* generator) const { generator->PrintString(delegate_->PrintEnum(val, name)); } + void PrintFieldName(const Message& message, int field_index, int field_count, + const Reflection* reflection, + const FieldDescriptor* field, + TextFormat::BaseTextGenerator* generator) const { + generator->PrintString(delegate_->PrintFieldName( + message, reflection, field)); + } void PrintFieldName(const Message& message, const Reflection* reflection, const FieldDescriptor* field, TextFormat::BaseTextGenerator* generator) const { @@ -1659,7 +1702,7 @@ class FieldValuePrinterWrapper : public TextFormat::FastFieldValuePrinter { } private: - google::protobuf::scoped_ptr<const TextFormat::FieldValuePrinter> delegate_; + std::unique_ptr<const TextFormat::FieldValuePrinter> delegate_; }; // Our own specialization: for UTF8 escaped strings. @@ -1688,12 +1731,14 @@ TextFormat::Printer::Printer() hide_unknown_fields_(false), print_message_fields_in_index_order_(false), expand_any_(false), - truncate_string_field_longer_than_(0LL) { + truncate_string_field_longer_than_(0LL), + finder_(NULL) { SetUseUtf8StringEscaping(false); } TextFormat::Printer::~Printer() { STLDeleteValues(&custom_printers_); + STLDeleteValues(&custom_message_printers_); } void TextFormat::Printer::SetUseUtf8StringEscaping(bool as_utf8) { @@ -1718,7 +1763,7 @@ bool TextFormat::Printer::RegisterFieldValuePrinter( return false; } FieldValuePrinterWrapper* const wrapper = - new FieldValuePrinterWrapper(NULL); + new FieldValuePrinterWrapper(nullptr); if (custom_printers_.insert(std::make_pair(field, wrapper)).second) { wrapper->SetDelegate(printer); return true; @@ -1734,6 +1779,13 @@ bool TextFormat::Printer::RegisterFieldValuePrinter( custom_printers_.insert(std::make_pair(field, printer)).second; } +bool TextFormat::Printer::RegisterMessagePrinter( + const Descriptor* descriptor, const MessagePrinter* printer) { + return descriptor != nullptr && printer != nullptr && + custom_message_printers_.insert(std::make_pair(descriptor, printer)) + .second; +} + bool TextFormat::Printer::PrintToString(const Message& message, string* output) const { GOOGLE_DCHECK(output) << "output specified is NULL"; @@ -1777,10 +1829,19 @@ bool TextFormat::Printer::PrintUnknownFields( namespace { // Comparison functor for sorting FieldDescriptors by field index. +// Normal fields have higher precedence than extensions. struct FieldIndexSorter { bool operator()(const FieldDescriptor* left, const FieldDescriptor* right) const { - return left->index() < right->index(); + if (left->is_extension() && right->is_extension()) { + return left->number() < right->number(); + } else if (left->is_extension()) { + return false; + } else if (right->is_extension()) { + return true; + } else { + return left->index() < right->index(); + } } }; @@ -1799,21 +1860,22 @@ bool TextFormat::Printer::PrintAny(const Message& message, // Extract the full type name from the type_url field. const string& type_url = reflection->GetString(message, type_url_field); + string url_prefix; string full_type_name; - if (!internal::ParseAnyTypeUrl(type_url, &full_type_name)) { + if (!internal::ParseAnyTypeUrl(type_url, &url_prefix, &full_type_name)) { return false; } // Print the "value" in text. const google::protobuf::Descriptor* value_descriptor = - message.GetDescriptor()->file()->pool()->FindMessageTypeByName( - full_type_name); + finder_ ? finder_->FindAnyType(message, url_prefix, full_type_name) + : DefaultFinderFindAnyType(message, url_prefix, full_type_name); if (value_descriptor == NULL) { GOOGLE_LOG(WARNING) << "Proto type " << type_url << " not found"; return false; } DynamicMessageFactory factory; - google::protobuf::scoped_ptr<google::protobuf::Message> value_message( + std::unique_ptr<google::protobuf::Message> value_message( factory.GetPrototype(value_descriptor)->New()); string serialized_value = reflection->GetString(message, value_field); if (!value_message->ParseFromString(serialized_value)) { @@ -1836,6 +1898,11 @@ bool TextFormat::Printer::PrintAny(const Message& message, void TextFormat::Printer::Print(const Message& message, TextGenerator* generator) const { const Descriptor* descriptor = message.GetDescriptor(); + auto itr = custom_message_printers_.find(descriptor); + if (itr != custom_message_printers_.end()) { + itr->second->Print(message, single_line_mode_, generator); + return; + } const Reflection* reflection = message.GetReflection(); if (descriptor->full_name() == internal::kAnyFullTypeName && expand_any_ && PrintAny(message, generator)) { @@ -1859,7 +1926,6 @@ void TextFormat::Printer::PrintFieldValueToString( const FieldDescriptor* field, int index, string* output) const { - GOOGLE_DCHECK(output) << "output specified is NULL"; output->clear(); @@ -1898,7 +1964,7 @@ void TextFormat::Printer::PrintField(const Message& message, for (int j = 0; j < count; ++j) { const int field_index = field->is_repeated() ? j : -1; - PrintFieldName(message, reflection, field, generator); + PrintFieldName(message, field_index, count, reflection, field, generator); if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { const FastFieldValuePrinter* printer = FindWithDefault( @@ -1932,9 +1998,9 @@ void TextFormat::Printer::PrintShortRepeatedField( const Message& message, const Reflection* reflection, const FieldDescriptor* field, TextGenerator* generator) const { // Print primitive repeated field in short form. - PrintFieldName(message, reflection, field, generator); - int size = reflection->FieldSize(message, field); + PrintFieldName(message, /*field_index=*/-1, /*field_count=*/size, reflection, + field, generator); generator->PrintLiteral(": ["); for (int i = 0; i < size; i++) { if (i > 0) generator->PrintLiteral(", "); @@ -1948,6 +2014,7 @@ void TextFormat::Printer::PrintShortRepeatedField( } void TextFormat::Printer::PrintFieldName(const Message& message, + int field_index, int field_count, const Reflection* reflection, const FieldDescriptor* field, TextGenerator* generator) const { @@ -1960,7 +2027,8 @@ void TextFormat::Printer::PrintFieldName(const Message& message, const FastFieldValuePrinter* printer = FindWithDefault( custom_printers_, field, default_field_value_printer_.get()); - printer->PrintFieldName(message, reflection, field, generator); + printer->PrintFieldName(message, field_index, field_count, reflection, field, + generator); } void TextFormat::Printer::PrintFieldValue(const Message& message, diff --git a/src/google/protobuf/text_format.h b/src/google/protobuf/text_format.h index a2670d6b..d6f3e16b 100644 --- a/src/google/protobuf/text_format.h +++ b/src/google/protobuf/text_format.h @@ -40,9 +40,6 @@ #include <map> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <string> #include <vector> @@ -97,6 +94,10 @@ class LIBPROTOBUF_EXPORT TextFormat { class LIBPROTOBUF_EXPORT BaseTextGenerator { public: virtual ~BaseTextGenerator(); + + virtual void Indent() {} + virtual void Outdent() {} + // Print text to the output stream. virtual void Print(const char* text, size_t size) = 0; @@ -129,6 +130,10 @@ class LIBPROTOBUF_EXPORT TextFormat { BaseTextGenerator* generator) const; virtual void PrintEnum(int32 val, const string& name, BaseTextGenerator* generator) const; + virtual void PrintFieldName(const Message& message, int field_index, + int field_count, const Reflection* reflection, + const FieldDescriptor* field, + BaseTextGenerator* generator) const; virtual void PrintFieldName(const Message& message, const Reflection* reflection, const FieldDescriptor* field, @@ -176,6 +181,40 @@ class LIBPROTOBUF_EXPORT TextFormat { GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldValuePrinter); }; + class LIBPROTOBUF_EXPORT MessagePrinter { + public: + MessagePrinter() {} + virtual ~MessagePrinter() {} + virtual void Print(const Message& message, bool single_line_mode, + BaseTextGenerator* generator) const = 0; + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessagePrinter); + }; + + // Interface that Printers or Parsers can use to find extensions, or types + // referenced in Any messages. + class LIBPROTOBUF_EXPORT Finder { + public: + virtual ~Finder(); + + // Try to find an extension of *message by fully-qualified field + // name. Returns NULL if no extension is known for this name or number. + // The base implementation uses the extensions already known by the message. + virtual const FieldDescriptor* FindExtension( + Message* message, + const string& name) const; + + // Find the message type for an Any proto. + // Returns NULL if no message is known for this name. + // The base implementation only accepts prefixes of type.googleprod.com/ or + // type.googleapis.com/, and searches the DescriptorPool of the parent + // message. + virtual const Descriptor* FindAnyType(const Message& message, + const string& prefix, + const string& name) const; + }; + // Class for those users which require more fine-grained control over how // a protobuffer message is printed out. class LIBPROTOBUF_EXPORT Printer { @@ -251,9 +290,11 @@ class LIBPROTOBUF_EXPORT TextFormat { hide_unknown_fields_ = hide; } - // If print_message_fields_in_index_order is true, print fields of a proto - // message using the order defined in source code instead of the field - // number. By default, use the field number order. + // If print_message_fields_in_index_order is true, fields of a proto message + // will be printed using the order defined in source code instead of the + // field number, extensions will be printed at the end of the message + // and their relative order is determined by the extension number. + // By default, use the field number order. void SetPrintMessageFieldsInIndexOrder( bool print_message_fields_in_index_order) { print_message_fields_in_index_order_ = @@ -271,6 +312,11 @@ class LIBPROTOBUF_EXPORT TextFormat { expand_any_ = expand; } + // Set how parser finds message for Any payloads. + void SetFinder(Finder* finder) { + finder_ = finder; + } + // If non-zero, we truncate all string fields that are longer than this // threshold. This is useful when the proto message has very long strings, // e.g., dump of encoded image file. @@ -293,6 +339,13 @@ class LIBPROTOBUF_EXPORT TextFormat { bool RegisterFieldValuePrinter(const FieldDescriptor* field, const FastFieldValuePrinter* printer); + // Register a custom message-specific MessagePrinter for messages with a + // particular Descriptor. + // Returns "true" if the registration succeeded, or "false" if there is + // already a printer for that Descriptor. + bool RegisterMessagePrinter(const Descriptor* descriptor, + const MessagePrinter* printer); + private: // Forward declaration of an internal class used to print the text // output to the OutputStream (see text_format.cc for implementation). @@ -315,7 +368,8 @@ class LIBPROTOBUF_EXPORT TextFormat { // Print the name of a field -- i.e. everything that comes before the // ':' for a single name/value pair. - void PrintFieldName(const Message& message, const Reflection* reflection, + void PrintFieldName(const Message& message, int field_index, + int field_count, const Reflection* reflection, const FieldDescriptor* field, TextGenerator* generator) const; @@ -349,10 +403,16 @@ class LIBPROTOBUF_EXPORT TextFormat { int64 truncate_string_field_longer_than_; - google::protobuf::scoped_ptr<const FastFieldValuePrinter> default_field_value_printer_; + std::unique_ptr<const FastFieldValuePrinter> default_field_value_printer_; typedef std::map<const FieldDescriptor*, const FastFieldValuePrinter*> CustomPrinterMap; CustomPrinterMap custom_printers_; + + typedef std::map<const Descriptor*, const MessagePrinter*> + CustomMessagePrinterMap; + CustomMessagePrinterMap custom_message_printers_; + + const Finder* finder_; }; // Parses a text-format protocol message from the given input stream to @@ -387,20 +447,6 @@ class LIBPROTOBUF_EXPORT TextFormat { const FieldDescriptor* field, Message* message); - // Interface that TextFormat::Parser can use to find extensions. - // This class may be extended in the future to find more information - // like fields, etc. - class LIBPROTOBUF_EXPORT Finder { - public: - virtual ~Finder(); - - // Try to find an extension of *message by fully-qualified field - // name. Returns NULL if no extension is known for this name or number. - virtual const FieldDescriptor* FindExtension( - Message* message, - const string& name) const = 0; - }; - // A location in the parsed text. struct ParseLocation { int line; @@ -524,7 +570,7 @@ class LIBPROTOBUF_EXPORT TextFormat { ParserImpl* parser_impl); io::ErrorCollector* error_collector_; - Finder* finder_; + const Finder* finder_; ParseInfoTree* parse_info_tree_; bool allow_partial_; bool allow_case_insensitive_field_; diff --git a/src/google/protobuf/text_format_unittest.cc b/src/google/protobuf/text_format_unittest.cc index f823bcb2..544c37e2 100644 --- a/src/google/protobuf/text_format_unittest.cc +++ b/src/google/protobuf/text_format_unittest.cc @@ -38,9 +38,6 @@ #include <stdlib.h> #include <limits> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> @@ -474,14 +471,14 @@ TEST_F(TextFormatTest, ErrorCasesRegisteringFieldValuePrinterShouldFail) { // NULL printer. EXPECT_FALSE(printer.RegisterFieldValuePrinter( message.GetDescriptor()->FindFieldByName("optional_int32"), - static_cast<const TextFormat::FieldValuePrinter*>(NULL))); + static_cast<const TextFormat::FieldValuePrinter*>(nullptr))); EXPECT_FALSE(printer.RegisterFieldValuePrinter( message.GetDescriptor()->FindFieldByName("optional_int32"), - static_cast<const TextFormat::FastFieldValuePrinter*>(NULL))); + static_cast<const TextFormat::FastFieldValuePrinter*>(nullptr))); // Because registration fails, the ownership of this printer is never taken. TextFormat::FieldValuePrinter my_field_printer; // NULL field - EXPECT_FALSE(printer.RegisterFieldValuePrinter(NULL, &my_field_printer)); + EXPECT_FALSE(printer.RegisterFieldValuePrinter(nullptr, &my_field_printer)); } class CustomMessageFieldValuePrinter : public TextFormat::FieldValuePrinter { @@ -564,6 +561,143 @@ TEST_F(TextFormatTest, CustomPrinterForMultilineComments) { text); } +// Achieve effects similar to SetUseShortRepeatedPrimitives for messages, using +// RegisterFieldValuePrinter. Use this to test the version of PrintFieldName +// that accepts repeated field index and count. +class CompactRepeatedFieldPrinter : public TextFormat::FastFieldValuePrinter { + public: + void PrintFieldName(const Message& message, int field_index, int field_count, + const Reflection* reflection, + const FieldDescriptor* field, + TextFormat::BaseTextGenerator* generator) const override { + if (field_index == 0 || field_index == -1) { + generator->PrintString(field->name()); + } + } + void PrintMessageStart( + const Message& message, int field_index, int field_count, + bool single_line_mode, + TextFormat::BaseTextGenerator* generator) const override { + if (field_index == 0 || field_index == -1) { + if (single_line_mode) { + generator->PrintLiteral(" { "); + } else { + generator->PrintLiteral(" {\n"); + } + } + } + void PrintMessageEnd( + const Message& message, int field_index, int field_count, + bool single_line_mode, + TextFormat::BaseTextGenerator* generator) const override { + if (field_index == field_count - 1 || field_index == -1) { + if (single_line_mode) { + generator->PrintLiteral("} "); + } else { + generator->PrintLiteral("}\n"); + } + } + } +}; + +TEST_F(TextFormatTest, CompactRepeatedFieldPrinter) { + TextFormat::Printer printer; + ASSERT_TRUE(printer.RegisterFieldValuePrinter( + unittest::TestAllTypes::default_instance() + .descriptor() + ->FindFieldByNumber( + unittest::TestAllTypes::kRepeatedNestedMessageFieldNumber), + new CompactRepeatedFieldPrinter)); + + protobuf_unittest::TestAllTypes message; + message.add_repeated_nested_message()->set_bb(1); + message.add_repeated_nested_message()->set_bb(2); + message.add_repeated_nested_message()->set_bb(3); + + string text; + ASSERT_TRUE(printer.PrintToString(message, &text)); + EXPECT_EQ( + "repeated_nested_message {\n" + " bb: 1\n" + " bb: 2\n" + " bb: 3\n" + "}\n", + text); +} + +// Print strings into multiple line, with indention. Use this to test +// BaseTextGenerator::Indent and BaseTextGenerator::Outdent. +class MultilineStringPrinter : public TextFormat::FastFieldValuePrinter { + public: + void PrintString(const string& val, + TextFormat::BaseTextGenerator* generator) const override { + generator->Indent(); + int last_pos = 0; + int newline_pos = val.find('\n'); + while (newline_pos != string::npos) { + generator->PrintLiteral("\n"); + TextFormat::FastFieldValuePrinter::PrintString( + val.substr(last_pos, newline_pos + 1 - last_pos), generator); + last_pos = newline_pos + 1; + newline_pos = val.find('\n', last_pos); + } + if (last_pos < val.size()) { + generator->PrintLiteral("\n"); + TextFormat::FastFieldValuePrinter::PrintString(val.substr(last_pos), + generator); + } + generator->Outdent(); + } +}; + +TEST_F(TextFormatTest, MultilineStringPrinter) { + TextFormat::Printer printer; + ASSERT_TRUE(printer.RegisterFieldValuePrinter( + unittest::TestAllTypes::default_instance() + .descriptor() + ->FindFieldByNumber( + unittest::TestAllTypes::kOptionalStringFieldNumber), + new MultilineStringPrinter)); + + protobuf_unittest::TestAllTypes message; + message.set_optional_string("first line\nsecond line\nthird line"); + + string text; + ASSERT_TRUE(printer.PrintToString(message, &text)); + EXPECT_EQ( + "optional_string: \n" + " \"first line\\n\"\n" + " \"second line\\n\"\n" + " \"third line\"\n", + text); +} + +class CustomNestedMessagePrinter : public TextFormat::MessagePrinter { + public: + CustomNestedMessagePrinter() {} + ~CustomNestedMessagePrinter() override {} + void Print(const Message& message, bool single_line_mode, + TextFormat::BaseTextGenerator* generator) const override { + generator->PrintLiteral("custom"); + } +}; + +TEST_F(TextFormatTest, CustomMessagePrinter) { + TextFormat::Printer printer; + printer.RegisterMessagePrinter( + unittest::TestAllTypes::NestedMessage::default_instance().descriptor(), + new CustomNestedMessagePrinter); + + unittest::TestAllTypes message; + string text; + EXPECT_TRUE(printer.PrintToString(message, &text)); + EXPECT_EQ("", text); + + message.mutable_optional_nested_message()->set_bb(1); + EXPECT_TRUE(printer.PrintToString(message, &text)); + EXPECT_EQ("optional_nested_message {\n custom}\n", text); +} + TEST_F(TextFormatTest, ParseBasic) { io::ArrayInputStream input_stream(proto_debug_string_.data(), proto_debug_string_.size()); @@ -1031,29 +1165,93 @@ TEST_F(TextFormatTest, ParseExotic) { TEST_F(TextFormatTest, PrintFieldsInIndexOrder) { protobuf_unittest::TestFieldOrderings message; // Fields are listed in index order instead of field number. - message.set_my_string("Test String"); // Field number 11 + message.set_my_string("str"); // Field number 11 message.set_my_int(12345); // Field number 1 message.set_my_float(0.999); // Field number 101 + // Extensions are listed based on the order of extension number. + // Extension number 12. + message + .MutableExtension( + protobuf_unittest::TestExtensionOrderings2::test_ext_orderings2) + ->set_my_string("ext_str2"); + // Extension number 13. + message + .MutableExtension( + protobuf_unittest::TestExtensionOrderings1::test_ext_orderings1) + ->set_my_string("ext_str1"); + // Extension number 14. + message + .MutableExtension(protobuf_unittest::TestExtensionOrderings2:: + TestExtensionOrderings3::test_ext_orderings3) + ->set_my_string("ext_str3"); + // Extension number 50. + *message.MutableExtension(protobuf_unittest::my_extension_string) = "ext_str0"; + TextFormat::Printer printer; string text; // By default, print in field number order. + // my_int: 12345 + // my_string: "str" + // [protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] { + // my_string: "ext_str2" + // } + // [protobuf_unittest.TestExtensionOrderings1.test_ext_orderings1] { + // my_string: "ext_str1" + // } + // [protobuf_unittest.TestExtensionOrderings2.TestExtensionOrderings3.test_ext_orderings3] + // { + // my_string: "ext_str3" + // } + // [protobuf_unittest.my_extension_string]: "ext_str0" + // my_float: 0.999 printer.PrintToString(message, &text); - EXPECT_EQ("my_int: 12345\nmy_string: \"Test String\"\nmy_float: 0.999\n", - text); + EXPECT_EQ( + "my_int: 12345\nmy_string: " + "\"str\"\n[protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] " + "{\n my_string: " + "\"ext_str2\"\n}\n[protobuf_unittest.TestExtensionOrderings1.test_ext_" + "orderings1] {\n my_string: " + "\"ext_str1\"\n}\n[protobuf_unittest.TestExtensionOrderings2." + "TestExtensionOrderings3.test_ext_orderings3] {\n my_string: " + "\"ext_str3\"\n}\n[protobuf_unittest.my_extension_string]: " + "\"ext_str0\"\nmy_float: 0.999\n", + text); // Print in index order. + // my_string: "str" + // my_int: 12345 + // my_float: 0.999 + // [protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] { + // my_string: "ext_str2" + // } + // [protobuf_unittest.TestExtensionOrderings1.test_ext_orderings1] { + // my_string: "ext_str1" + // } + // [protobuf_unittest.TestExtensionOrderings2.TestExtensionOrderings3.test_ext_orderings3] + // { + // my_string: "ext_str3" + // } + // [protobuf_unittest.my_extension_string]: "ext_str0" printer.SetPrintMessageFieldsInIndexOrder(true); printer.PrintToString(message, &text); - EXPECT_EQ("my_string: \"Test String\"\nmy_int: 12345\nmy_float: 0.999\n", - text); + EXPECT_EQ( + "my_string: \"str\"\nmy_int: 12345\nmy_float: " + "0.999\n[protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] " + "{\n my_string: " + "\"ext_str2\"\n}\n[protobuf_unittest.TestExtensionOrderings1.test_ext_" + "orderings1] {\n my_string: " + "\"ext_str1\"\n}\n[protobuf_unittest.TestExtensionOrderings2." + "TestExtensionOrderings3.test_ext_orderings3] {\n my_string: " + "\"ext_str3\"\n}\n[protobuf_unittest.my_extension_string]: \"ext_str0\"\n", + text); } class TextFormatParserTest : public testing::Test { protected: void ExpectFailure(const string& input, const string& message, int line, int col) { - google::protobuf::scoped_ptr<unittest::TestAllTypes> proto(new unittest::TestAllTypes); + std::unique_ptr<unittest::TestAllTypes> proto(new unittest::TestAllTypes); ExpectFailure(input, message, line, col, proto.get()); } @@ -1114,7 +1312,7 @@ class TextFormatParserTest : public testing::Test { }; TEST_F(TextFormatParserTest, ParseInfoTreeBuilding) { - google::protobuf::scoped_ptr<unittest::TestAllTypes> message(new unittest::TestAllTypes); + std::unique_ptr<unittest::TestAllTypes> message(new unittest::TestAllTypes); const Descriptor* d = message->GetDescriptor(); string stringData = @@ -1179,7 +1377,7 @@ TEST_F(TextFormatParserTest, ParseInfoTreeBuilding) { } TEST_F(TextFormatParserTest, ParseFieldValueFromString) { - google::protobuf::scoped_ptr<unittest::TestAllTypes> message(new unittest::TestAllTypes); + std::unique_ptr<unittest::TestAllTypes> message(new unittest::TestAllTypes); const Descriptor* d = message->GetDescriptor(); #define EXPECT_FIELD(name, value, valuestring) \ diff --git a/src/google/protobuf/timestamp.pb.cc b/src/google/protobuf/timestamp.pb.cc index f57d4d66..3184bd97 100644 --- a/src/google/protobuf/timestamp.pb.cc +++ b/src/google/protobuf/timestamp.pb.cc @@ -7,7 +7,6 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> -#include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> @@ -19,6 +18,7 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + namespace google { namespace protobuf { class TimestampDefaultTypeInternal { @@ -29,14 +29,9 @@ class TimestampDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto { -void InitDefaultsTimestampImpl() { +static void InitDefaultsTimestamp() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_Timestamp_default_instance_; new (ptr) ::google::protobuf::Timestamp(); @@ -45,9 +40,11 @@ void InitDefaultsTimestampImpl() { ::google::protobuf::Timestamp::InitAsDefaultInstance(); } -void InitDefaultsTimestamp() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsTimestampImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Timestamp = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsTimestamp}, {}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_Timestamp.base); } ::google::protobuf::Metadata file_level_metadata[1]; @@ -69,17 +66,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Timestamp_default_instance_), }; -void protobuf_AssignDescriptors() { +static void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/timestamp.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/timestamp.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } -void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); +static void protobuf_AssignDescriptorsOnce() { + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -88,7 +84,7 @@ void protobuf_RegisterTypes(const ::std::string&) { ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1); } -void AddDescriptorsImpl() { +static void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n\037google/protobuf/timestamp.proto\022\017googl" @@ -105,8 +101,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -129,24 +125,22 @@ const int Timestamp::kNanosFieldNumber; Timestamp::Timestamp() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::InitDefaultsTimestamp(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2ftimestamp_2eproto::scc_info_Timestamp.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Timestamp) } Timestamp::Timestamp(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::InitDefaultsTimestamp(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftimestamp_2eproto::scc_info_Timestamp.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Timestamp) } Timestamp::Timestamp(const Timestamp& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&seconds_, &from.seconds_, static_cast<size_t>(reinterpret_cast<char*>(&nanos_) - @@ -158,7 +152,6 @@ void Timestamp::SharedCtor() { ::memset(&seconds_, 0, static_cast<size_t>( reinterpret_cast<char*>(&nanos_) - reinterpret_cast<char*>(&seconds_)) + sizeof(nanos_)); - _cached_size_ = 0; } Timestamp::~Timestamp() { @@ -177,9 +170,7 @@ void Timestamp::ArenaDtor(void* object) { void Timestamp::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Timestamp::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Timestamp::descriptor() { ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::protobuf_AssignDescriptorsOnce(); @@ -187,7 +178,7 @@ const ::google::protobuf::Descriptor* Timestamp::descriptor() { } const Timestamp& Timestamp::default_instance() { - ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::InitDefaultsTimestamp(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftimestamp_2eproto::scc_info_Timestamp.base); return *internal_default_instance(); } @@ -210,7 +201,7 @@ bool Timestamp::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Timestamp) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -334,9 +325,7 @@ size_t Timestamp::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -412,7 +401,6 @@ void Timestamp::InternalSwap(Timestamp* other) { swap(seconds_, other->seconds_); swap(nanos_, other->nanos_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Timestamp::GetMetadata() const { @@ -426,7 +414,7 @@ void Timestamp::InternalSwap(Timestamp* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Timestamp* Arena::CreateMessage< ::google::protobuf::Timestamp >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Timestamp* Arena::CreateMaybeMessage< ::google::protobuf::Timestamp >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Timestamp >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/timestamp.pb.h b/src/google/protobuf/timestamp.pb.h index a0f9605c..f73e75b3 100644 --- a/src/google/protobuf/timestamp.pb.h +++ b/src/google/protobuf/timestamp.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/timestamp.proto -#ifndef PROTOBUF_google_2fprotobuf_2ftimestamp_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2ftimestamp_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto #include <string> @@ -24,12 +24,14 @@ #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> +#include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftimestamp_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto { // Internal implementation detail -- do not use these members. @@ -42,11 +44,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsTimestampImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsTimestamp(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsTimestamp(); -} } // namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto namespace google { namespace protobuf { @@ -57,7 +54,7 @@ LIBPROTOBUF_EXPORT extern TimestampDefaultTypeInternal _Timestamp_default_instan } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Timestamp* Arena::CreateMessage< ::google::protobuf::Timestamp>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Timestamp* Arena::CreateMaybeMessage<::google::protobuf::Timestamp>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -91,10 +88,10 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -105,7 +102,7 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro return reinterpret_cast<const Timestamp*>( &_Timestamp_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void UnsafeArenaSwap(Timestamp* other); @@ -116,32 +113,33 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro // implements Message ---------------------------------------------- - inline Timestamp* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Timestamp>(NULL); + inline Timestamp* New() const final { + return CreateMaybeMessage<Timestamp>(NULL); } - Timestamp* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Timestamp>(arena); + Timestamp* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<Timestamp>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Timestamp& from); void MergeFrom(const Timestamp& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Timestamp* other); protected: explicit Timestamp(::google::protobuf::Arena* arena); @@ -157,7 +155,7 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -184,9 +182,8 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro typedef void DestructorSkippable_; ::google::protobuf::int64 seconds_; ::google::protobuf::int32 nanos_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::InitDefaultsTimestampImpl(); }; // =================================================================== @@ -238,4 +235,4 @@ inline void Timestamp::set_nanos(::google::protobuf::int32 value) { // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2ftimestamp_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto diff --git a/src/google/protobuf/type.pb.cc b/src/google/protobuf/type.pb.cc index a2edabb6..17d5ce2a 100644 --- a/src/google/protobuf/type.pb.cc +++ b/src/google/protobuf/type.pb.cc @@ -7,7 +7,6 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> -#include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> @@ -19,6 +18,18 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + +namespace protobuf_google_2fprotobuf_2fany_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fany_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Any; +} // namespace protobuf_google_2fprotobuf_2fany_2eproto +namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SourceContext; +} // namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto +namespace protobuf_google_2fprotobuf_2ftype_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValue; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Field; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Option; +} // namespace protobuf_google_2fprotobuf_2ftype_2eproto namespace google { namespace protobuf { class TypeDefaultTypeInternal { @@ -49,17 +60,9 @@ class OptionDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2ftype_2eproto { -void InitDefaultsTypeImpl() { +static void InitDefaultsType() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsField(); - protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption(); - protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext(); { void* ptr = &::google::protobuf::_Type_default_instance_; new (ptr) ::google::protobuf::Type(); @@ -68,20 +71,15 @@ void InitDefaultsTypeImpl() { ::google::protobuf::Type::InitAsDefaultInstance(); } -void InitDefaultsType() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsTypeImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<3> scc_info_Type = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsType}, { + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Field.base, + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base, + &protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base,}}; -void InitDefaultsFieldImpl() { +static void InitDefaultsField() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption(); { void* ptr = &::google::protobuf::_Field_default_instance_; new (ptr) ::google::protobuf::Field(); @@ -90,22 +88,13 @@ void InitDefaultsFieldImpl() { ::google::protobuf::Field::InitAsDefaultInstance(); } -void InitDefaultsField() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFieldImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_Field = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsField}, { + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base,}}; -void InitDefaultsEnumImpl() { +static void InitDefaultsEnum() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValue(); - protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption(); - protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext(); { void* ptr = &::google::protobuf::_Enum_default_instance_; new (ptr) ::google::protobuf::Enum(); @@ -114,20 +103,15 @@ void InitDefaultsEnumImpl() { ::google::protobuf::Enum::InitAsDefaultInstance(); } -void InitDefaultsEnum() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<3> scc_info_Enum = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsEnum}, { + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_EnumValue.base, + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base, + &protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base,}}; -void InitDefaultsEnumValueImpl() { +static void InitDefaultsEnumValue() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption(); { void* ptr = &::google::protobuf::_EnumValue_default_instance_; new (ptr) ::google::protobuf::EnumValue(); @@ -136,20 +120,13 @@ void InitDefaultsEnumValueImpl() { ::google::protobuf::EnumValue::InitAsDefaultInstance(); } -void InitDefaultsEnumValue() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumValueImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValue = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumValue}, { + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base,}}; -void InitDefaultsOptionImpl() { +static void InitDefaultsOption() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAny(); { void* ptr = &::google::protobuf::_Option_default_instance_; new (ptr) ::google::protobuf::Option(); @@ -158,9 +135,16 @@ void InitDefaultsOptionImpl() { ::google::protobuf::Option::InitAsDefaultInstance(); } -void InitDefaultsOption() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsOptionImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_Option = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsOption}, { + &protobuf_google_2fprotobuf_2fany_2eproto::scc_info_Any.base,}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_Type.base); + ::google::protobuf::internal::InitSCC(&scc_info_Field.base); + ::google::protobuf::internal::InitSCC(&scc_info_Enum.base); + ::google::protobuf::internal::InitSCC(&scc_info_EnumValue.base); + ::google::protobuf::internal::InitSCC(&scc_info_Option.base); } ::google::protobuf::Metadata file_level_metadata[5]; @@ -235,17 +219,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Option_default_instance_), }; -void protobuf_AssignDescriptors() { +static void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/type.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/type.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, file_level_enum_descriptors, NULL); } -void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); +static void protobuf_AssignDescriptorsOnce() { + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -254,7 +237,7 @@ void protobuf_RegisterTypes(const ::std::string&) { ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 5); } -void AddDescriptorsImpl() { +static void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n\032google/protobuf/type.proto\022\017google.pro" @@ -307,8 +290,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -450,9 +433,8 @@ const int Type::kSyntaxFieldNumber; Type::Type() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsType(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Type.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Type) } @@ -462,7 +444,7 @@ Type::Type(::google::protobuf::Arena* arena) fields_(arena), oneofs_(arena), options_(arena) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsType(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Type.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Type) @@ -472,8 +454,7 @@ Type::Type(const Type& from) _internal_metadata_(NULL), fields_(from.fields_), oneofs_(from.oneofs_), - options_(from.options_), - _cached_size_(0) { + options_(from.options_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { @@ -494,7 +475,6 @@ void Type::SharedCtor() { ::memset(&source_context_, 0, static_cast<size_t>( reinterpret_cast<char*>(&syntax_) - reinterpret_cast<char*>(&source_context_)) + sizeof(syntax_)); - _cached_size_ = 0; } Type::~Type() { @@ -515,9 +495,7 @@ void Type::ArenaDtor(void* object) { void Type::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Type::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Type::descriptor() { ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce(); @@ -525,7 +503,7 @@ const ::google::protobuf::Descriptor* Type::descriptor() { } const Type& Type::default_instance() { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsType(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Type.base); return *internal_default_instance(); } @@ -554,7 +532,7 @@ bool Type::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Type) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -709,7 +687,7 @@ void Type::SerializeWithCachedSizes( // .google.protobuf.SourceContext source_context = 5; if (this->has_source_context()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 5, *source_context_, output); + 5, this->_internal_source_context(), output); } // .google.protobuf.Syntax syntax = 6; @@ -773,7 +751,7 @@ void Type::SerializeWithCachedSizes( if (this->has_source_context()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 5, *source_context_, deterministic, target); + 5, this->_internal_source_context(), deterministic, target); } // .google.protobuf.Syntax syntax = 6; @@ -850,9 +828,7 @@ size_t Type::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -934,11 +910,11 @@ void Type::InternalSwap(Type* other) { CastToBase(&fields_)->InternalSwap(CastToBase(&other->fields_)); oneofs_.InternalSwap(CastToBase(&other->oneofs_)); CastToBase(&options_)->InternalSwap(CastToBase(&other->options_)); - name_.Swap(&other->name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(source_context_, other->source_context_); swap(syntax_, other->syntax_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Type::GetMetadata() const { @@ -966,9 +942,8 @@ const int Field::kDefaultValueFieldNumber; Field::Field() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsField(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Field.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Field) } @@ -976,7 +951,7 @@ Field::Field(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), options_(arena) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsField(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Field.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Field) @@ -984,8 +959,7 @@ Field::Field(::google::protobuf::Arena* arena) Field::Field(const Field& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - options_(from.options_), - _cached_size_(0) { + options_(from.options_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { @@ -1021,7 +995,6 @@ void Field::SharedCtor() { ::memset(&kind_, 0, static_cast<size_t>( reinterpret_cast<char*>(&packed_) - reinterpret_cast<char*>(&kind_)) + sizeof(packed_)); - _cached_size_ = 0; } Field::~Field() { @@ -1044,9 +1017,7 @@ void Field::ArenaDtor(void* object) { void Field::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Field::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Field::descriptor() { ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1054,7 +1025,7 @@ const ::google::protobuf::Descriptor* Field::descriptor() { } const Field& Field::default_instance() { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsField(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Field.base); return *internal_default_instance(); } @@ -1082,7 +1053,7 @@ bool Field::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Field) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1517,9 +1488,7 @@ size_t Field::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1615,17 +1584,20 @@ void Field::UnsafeArenaSwap(Field* other) { void Field::InternalSwap(Field* other) { using std::swap; CastToBase(&options_)->InternalSwap(CastToBase(&other->options_)); - name_.Swap(&other->name_); - type_url_.Swap(&other->type_url_); - json_name_.Swap(&other->json_name_); - default_value_.Swap(&other->default_value_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + type_url_.Swap(&other->type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + json_name_.Swap(&other->json_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + default_value_.Swap(&other->default_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(kind_, other->kind_); swap(cardinality_, other->cardinality_); swap(number_, other->number_); swap(oneof_index_, other->oneof_index_); swap(packed_, other->packed_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Field::GetMetadata() const { @@ -1669,9 +1641,8 @@ const int Enum::kSyntaxFieldNumber; Enum::Enum() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnum(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Enum.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Enum) } @@ -1680,7 +1651,7 @@ Enum::Enum(::google::protobuf::Arena* arena) _internal_metadata_(arena), enumvalue_(arena), options_(arena) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnum(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Enum.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Enum) @@ -1689,8 +1660,7 @@ Enum::Enum(const Enum& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), enumvalue_(from.enumvalue_), - options_(from.options_), - _cached_size_(0) { + options_(from.options_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { @@ -1711,7 +1681,6 @@ void Enum::SharedCtor() { ::memset(&source_context_, 0, static_cast<size_t>( reinterpret_cast<char*>(&syntax_) - reinterpret_cast<char*>(&source_context_)) + sizeof(syntax_)); - _cached_size_ = 0; } Enum::~Enum() { @@ -1732,9 +1701,7 @@ void Enum::ArenaDtor(void* object) { void Enum::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Enum::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Enum::descriptor() { ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1742,7 +1709,7 @@ const ::google::protobuf::Descriptor* Enum::descriptor() { } const Enum& Enum::default_instance() { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnum(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Enum.base); return *internal_default_instance(); } @@ -1770,7 +1737,7 @@ bool Enum::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Enum) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1898,7 +1865,7 @@ void Enum::SerializeWithCachedSizes( // .google.protobuf.SourceContext source_context = 4; if (this->has_source_context()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 4, *source_context_, output); + 4, this->_internal_source_context(), output); } // .google.protobuf.Syntax syntax = 5; @@ -1952,7 +1919,7 @@ void Enum::SerializeWithCachedSizes( if (this->has_source_context()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 4, *source_context_, deterministic, target); + 4, this->_internal_source_context(), deterministic, target); } // .google.protobuf.Syntax syntax = 5; @@ -2021,9 +1988,7 @@ size_t Enum::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -2103,11 +2068,11 @@ void Enum::InternalSwap(Enum* other) { using std::swap; CastToBase(&enumvalue_)->InternalSwap(CastToBase(&other->enumvalue_)); CastToBase(&options_)->InternalSwap(CastToBase(&other->options_)); - name_.Swap(&other->name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(source_context_, other->source_context_); swap(syntax_, other->syntax_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Enum::GetMetadata() const { @@ -2128,9 +2093,8 @@ const int EnumValue::kOptionsFieldNumber; EnumValue::EnumValue() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValue(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_EnumValue.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.EnumValue) } @@ -2138,7 +2102,7 @@ EnumValue::EnumValue(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), options_(arena) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_EnumValue.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValue) @@ -2146,8 +2110,7 @@ EnumValue::EnumValue(::google::protobuf::Arena* arena) EnumValue::EnumValue(const EnumValue& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - options_(from.options_), - _cached_size_(0) { + options_(from.options_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { @@ -2161,7 +2124,6 @@ EnumValue::EnumValue(const EnumValue& from) void EnumValue::SharedCtor() { name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); number_ = 0; - _cached_size_ = 0; } EnumValue::~EnumValue() { @@ -2181,9 +2143,7 @@ void EnumValue::ArenaDtor(void* object) { void EnumValue::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void EnumValue::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* EnumValue::descriptor() { ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce(); @@ -2191,7 +2151,7 @@ const ::google::protobuf::Descriptor* EnumValue::descriptor() { } const EnumValue& EnumValue::default_instance() { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_EnumValue.base); return *internal_default_instance(); } @@ -2214,7 +2174,7 @@ bool EnumValue::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumValue) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -2391,9 +2351,7 @@ size_t EnumValue::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -2468,10 +2426,10 @@ void EnumValue::UnsafeArenaSwap(EnumValue* other) { void EnumValue::InternalSwap(EnumValue* other) { using std::swap; CastToBase(&options_)->InternalSwap(CastToBase(&other->options_)); - name_.Swap(&other->name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(number_, other->number_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata EnumValue::GetMetadata() const { @@ -2512,24 +2470,22 @@ const int Option::kValueFieldNumber; Option::Option() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Option) } Option::Option(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Option) } Option::Option(const Option& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { @@ -2547,7 +2503,6 @@ Option::Option(const Option& from) void Option::SharedCtor() { name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); value_ = NULL; - _cached_size_ = 0; } Option::~Option() { @@ -2568,9 +2523,7 @@ void Option::ArenaDtor(void* object) { void Option::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Option::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Option::descriptor() { ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce(); @@ -2578,7 +2531,7 @@ const ::google::protobuf::Descriptor* Option::descriptor() { } const Option& Option::default_instance() { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base); return *internal_default_instance(); } @@ -2603,7 +2556,7 @@ bool Option::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Option) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -2674,7 +2627,7 @@ void Option::SerializeWithCachedSizes( // .google.protobuf.Any value = 2; if (this->has_value()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 2, *value_, output); + 2, this->_internal_value(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { @@ -2706,7 +2659,7 @@ void Option::SerializeWithCachedSizes( if (this->has_value()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 2, *value_, deterministic, target); + 2, this->_internal_value(), deterministic, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { @@ -2741,9 +2694,7 @@ size_t Option::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -2816,10 +2767,10 @@ void Option::UnsafeArenaSwap(Option* other) { } void Option::InternalSwap(Option* other) { using std::swap; - name_.Swap(&other->name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(value_, other->value_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Option::GetMetadata() const { @@ -2833,19 +2784,19 @@ void Option::InternalSwap(Option* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Type* Arena::CreateMessage< ::google::protobuf::Type >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Type* Arena::CreateMaybeMessage< ::google::protobuf::Type >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Type >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Field* Arena::CreateMessage< ::google::protobuf::Field >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Field* Arena::CreateMaybeMessage< ::google::protobuf::Field >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Field >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Enum* Arena::CreateMessage< ::google::protobuf::Enum >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Enum* Arena::CreateMaybeMessage< ::google::protobuf::Enum >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Enum >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValue* Arena::CreateMessage< ::google::protobuf::EnumValue >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValue* Arena::CreateMaybeMessage< ::google::protobuf::EnumValue >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::EnumValue >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Option* Arena::CreateMessage< ::google::protobuf::Option >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Option* Arena::CreateMaybeMessage< ::google::protobuf::Option >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Option >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/type.pb.h b/src/google/protobuf/type.pb.h index 49bed8ee..69af6c2e 100644 --- a/src/google/protobuf/type.pb.h +++ b/src/google/protobuf/type.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/type.proto -#ifndef PROTOBUF_google_2fprotobuf_2ftype_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2ftype_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2ftype_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2ftype_2eproto #include <string> @@ -24,6 +24,7 @@ #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> +#include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export @@ -33,6 +34,7 @@ #include <google/protobuf/any.pb.h> #include <google/protobuf/source_context.pb.h> // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2ftype_2eproto { // Internal implementation detail -- do not use these members. @@ -45,23 +47,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsTypeImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsType(); -void LIBPROTOBUF_EXPORT InitDefaultsFieldImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsField(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsEnum(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumValueImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumValue(); -void LIBPROTOBUF_EXPORT InitDefaultsOptionImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsOption(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsType(); - InitDefaultsField(); - InitDefaultsEnum(); - InitDefaultsEnumValue(); - InitDefaultsOption(); -} } // namespace protobuf_google_2fprotobuf_2ftype_2eproto namespace google { namespace protobuf { @@ -84,11 +69,11 @@ LIBPROTOBUF_EXPORT extern TypeDefaultTypeInternal _Type_default_instance_; } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Enum* Arena::CreateMessage< ::google::protobuf::Enum>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValue* Arena::CreateMessage< ::google::protobuf::EnumValue>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Field* Arena::CreateMessage< ::google::protobuf::Field>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Option* Arena::CreateMessage< ::google::protobuf::Option>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Type* Arena::CreateMessage< ::google::protobuf::Type>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Enum* Arena::CreateMaybeMessage<::google::protobuf::Enum>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValue* Arena::CreateMaybeMessage<::google::protobuf::EnumValue>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Field* Arena::CreateMaybeMessage<::google::protobuf::Field>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Option* Arena::CreateMaybeMessage<::google::protobuf::Option>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Type* Arena::CreateMaybeMessage<::google::protobuf::Type>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -204,10 +189,10 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -218,7 +203,7 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i return reinterpret_cast<const Type*>( &_Type_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void UnsafeArenaSwap(Type* other); @@ -229,32 +214,33 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i // implements Message ---------------------------------------------- - inline Type* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Type>(NULL); + inline Type* New() const final { + return CreateMaybeMessage<Type>(NULL); } - Type* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Type>(arena); + Type* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<Type>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Type& from); void MergeFrom(const Type& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Type* other); protected: explicit Type(::google::protobuf::Arena* arena); @@ -270,7 +256,7 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -349,6 +335,9 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i bool has_source_context() const; void clear_source_context(); static const int kSourceContextFieldNumber = 5; + private: + const ::google::protobuf::SourceContext& _internal_source_context() const; + public: const ::google::protobuf::SourceContext& source_context() const; ::google::protobuf::SourceContext* release_source_context(); ::google::protobuf::SourceContext* mutable_source_context(); @@ -376,9 +365,8 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::SourceContext* source_context_; int syntax_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsTypeImpl(); }; // ------------------------------------------------------------------- @@ -408,10 +396,10 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_ return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -422,7 +410,7 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_ return reinterpret_cast<const Field*>( &_Field_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 1; void UnsafeArenaSwap(Field* other); @@ -433,32 +421,33 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_ // implements Message ---------------------------------------------- - inline Field* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Field>(NULL); + inline Field* New() const final { + return CreateMaybeMessage<Field>(NULL); } - Field* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Field>(arena); + Field* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<Field>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Field& from); void MergeFrom(const Field& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Field* other); protected: explicit Field(::google::protobuf::Arena* arena); @@ -474,7 +463,7 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_ } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -721,9 +710,8 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_ ::google::protobuf::int32 number_; ::google::protobuf::int32 oneof_index_; bool packed_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsFieldImpl(); }; // ------------------------------------------------------------------- @@ -753,10 +741,10 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -767,7 +755,7 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i return reinterpret_cast<const Enum*>( &_Enum_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 2; void UnsafeArenaSwap(Enum* other); @@ -778,32 +766,33 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i // implements Message ---------------------------------------------- - inline Enum* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Enum>(NULL); + inline Enum* New() const final { + return CreateMaybeMessage<Enum>(NULL); } - Enum* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Enum>(arena); + Enum* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<Enum>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Enum& from); void MergeFrom(const Enum& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Enum* other); protected: explicit Enum(::google::protobuf::Arena* arena); @@ -819,7 +808,7 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -876,6 +865,9 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i bool has_source_context() const; void clear_source_context(); static const int kSourceContextFieldNumber = 4; + private: + const ::google::protobuf::SourceContext& _internal_source_context() const; + public: const ::google::protobuf::SourceContext& source_context() const; ::google::protobuf::SourceContext* release_source_context(); ::google::protobuf::SourceContext* mutable_source_context(); @@ -902,9 +894,8 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::SourceContext* source_context_; int syntax_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumImpl(); }; // ------------------------------------------------------------------- @@ -934,10 +925,10 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -948,7 +939,7 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro return reinterpret_cast<const EnumValue*>( &_EnumValue_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 3; void UnsafeArenaSwap(EnumValue* other); @@ -959,32 +950,33 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro // implements Message ---------------------------------------------- - inline EnumValue* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<EnumValue>(NULL); + inline EnumValue* New() const final { + return CreateMaybeMessage<EnumValue>(NULL); } - EnumValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<EnumValue>(arena); + EnumValue* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<EnumValue>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const EnumValue& from); void MergeFrom(const EnumValue& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(EnumValue* other); protected: explicit EnumValue(::google::protobuf::Arena* arena); @@ -1000,7 +992,7 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -1057,9 +1049,8 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::int32 number_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValueImpl(); }; // ------------------------------------------------------------------- @@ -1089,10 +1080,10 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -1103,7 +1094,7 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc return reinterpret_cast<const Option*>( &_Option_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 4; void UnsafeArenaSwap(Option* other); @@ -1114,32 +1105,33 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc // implements Message ---------------------------------------------- - inline Option* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Option>(NULL); + inline Option* New() const final { + return CreateMaybeMessage<Option>(NULL); } - Option* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Option>(arena); + Option* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<Option>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Option& from); void MergeFrom(const Option& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Option* other); protected: explicit Option(::google::protobuf::Arena* arena); @@ -1155,7 +1147,7 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -1188,6 +1180,9 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc bool has_value() const; void clear_value(); static const int kValueFieldNumber = 2; + private: + const ::google::protobuf::Any& _internal_value() const; + public: const ::google::protobuf::Any& value() const; ::google::protobuf::Any* release_value(); ::google::protobuf::Any* mutable_value(); @@ -1205,9 +1200,8 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc typedef void DestructorSkippable_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::Any* value_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOptionImpl(); }; // =================================================================== @@ -1428,6 +1422,9 @@ Type::options() const { inline bool Type::has_source_context() const { return this != internal_default_instance() && source_context_ != NULL; } +inline const ::google::protobuf::SourceContext& Type::_internal_source_context() const { + return *source_context_; +} inline const ::google::protobuf::SourceContext& Type::source_context() const { const ::google::protobuf::SourceContext* p = source_context_; // @@protoc_insertion_point(field_get:google.protobuf.Type.source_context) @@ -1439,7 +1436,7 @@ inline ::google::protobuf::SourceContext* Type::release_source_context() { ::google::protobuf::SourceContext* temp = source_context_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } source_context_ = NULL; return temp; @@ -1454,8 +1451,8 @@ inline ::google::protobuf::SourceContext* Type::unsafe_arena_release_source_cont inline ::google::protobuf::SourceContext* Type::mutable_source_context() { if (source_context_ == NULL) { - source_context_ = ::google::protobuf::Arena::Create< ::google::protobuf::SourceContext >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::SourceContext>(GetArenaNoVirtual()); + source_context_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.Type.source_context) return source_context_; @@ -2040,6 +2037,9 @@ Enum::options() const { inline bool Enum::has_source_context() const { return this != internal_default_instance() && source_context_ != NULL; } +inline const ::google::protobuf::SourceContext& Enum::_internal_source_context() const { + return *source_context_; +} inline const ::google::protobuf::SourceContext& Enum::source_context() const { const ::google::protobuf::SourceContext* p = source_context_; // @@protoc_insertion_point(field_get:google.protobuf.Enum.source_context) @@ -2051,7 +2051,7 @@ inline ::google::protobuf::SourceContext* Enum::release_source_context() { ::google::protobuf::SourceContext* temp = source_context_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } source_context_ = NULL; return temp; @@ -2066,8 +2066,8 @@ inline ::google::protobuf::SourceContext* Enum::unsafe_arena_release_source_cont inline ::google::protobuf::SourceContext* Enum::mutable_source_context() { if (source_context_ == NULL) { - source_context_ = ::google::protobuf::Arena::Create< ::google::protobuf::SourceContext >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::SourceContext>(GetArenaNoVirtual()); + source_context_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.Enum.source_context) return source_context_; @@ -2311,6 +2311,9 @@ inline void Option::unsafe_arena_set_allocated_name( inline bool Option::has_value() const { return this != internal_default_instance() && value_ != NULL; } +inline const ::google::protobuf::Any& Option::_internal_value() const { + return *value_; +} inline const ::google::protobuf::Any& Option::value() const { const ::google::protobuf::Any* p = value_; // @@protoc_insertion_point(field_get:google.protobuf.Option.value) @@ -2322,7 +2325,7 @@ inline ::google::protobuf::Any* Option::release_value() { ::google::protobuf::Any* temp = value_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } value_ = NULL; return temp; @@ -2337,8 +2340,8 @@ inline ::google::protobuf::Any* Option::unsafe_arena_release_value() { inline ::google::protobuf::Any* Option::mutable_value() { if (value_ == NULL) { - value_ = ::google::protobuf::Arena::Create< ::google::protobuf::Any >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::Any>(GetArenaNoVirtual()); + value_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.Option.value) return value_; @@ -2382,17 +2385,17 @@ inline void Option::set_allocated_value(::google::protobuf::Any* value) { namespace google { namespace protobuf { -template <> struct is_proto_enum< ::google::protobuf::Field_Kind> : ::google::protobuf::internal::true_type {}; +template <> struct is_proto_enum< ::google::protobuf::Field_Kind> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::Field_Kind>() { return ::google::protobuf::Field_Kind_descriptor(); } -template <> struct is_proto_enum< ::google::protobuf::Field_Cardinality> : ::google::protobuf::internal::true_type {}; +template <> struct is_proto_enum< ::google::protobuf::Field_Cardinality> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::Field_Cardinality>() { return ::google::protobuf::Field_Cardinality_descriptor(); } -template <> struct is_proto_enum< ::google::protobuf::Syntax> : ::google::protobuf::internal::true_type {}; +template <> struct is_proto_enum< ::google::protobuf::Syntax> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::Syntax>() { return ::google::protobuf::Syntax_descriptor(); @@ -2403,4 +2406,4 @@ inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::Syntax>() { // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2ftype_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2ftype_2eproto diff --git a/src/google/protobuf/unittest.proto b/src/google/protobuf/unittest.proto index 2a288daa..4af2b051 100644 --- a/src/google/protobuf/unittest.proto +++ b/src/google/protobuf/unittest.proto @@ -33,6 +33,8 @@ // Sanjay Ghemawat, Jeff Dean, and others. // // A proto file we will use for unit testing. +// +// LINT: ALLOW_GROUPS, LEGACY_NAMES syntax = "proto2"; @@ -333,6 +335,17 @@ extend TestAllExtensions { optional bytes oneof_bytes_extension = 114; } +message TestGroup { + optional group OptionalGroup = 16 { + optional int32 a = 17; + } + optional ForeignEnum optional_foreign_enum = 22; +} + +message TestGroupExtension { + extensions 1 to max; +} + message TestNestedExtension { extend TestAllExtensions { // Check for bug where string extensions declared in tested scope did not @@ -342,6 +355,13 @@ message TestNestedExtension { // underscores. optional string nested_string_extension = 1003; } + + extend TestGroupExtension { + optional group OptionalGroup_extension = 16 { + optional int32 a = 17; + } + optional ForeignEnum optional_foreign_enum_extension = 22; + } } // We have separate messages for testing required fields because it's @@ -554,12 +574,30 @@ message TestFieldOrderings { optional NestedMessage optional_nested_message = 200; } - extend TestFieldOrderings { optional string my_extension_string = 50; optional int32 my_extension_int = 5; } +message TestExtensionOrderings1 { + extend TestFieldOrderings { + optional TestExtensionOrderings1 test_ext_orderings1 = 13; + } + optional string my_string = 1; +} + +message TestExtensionOrderings2 { + extend TestFieldOrderings { + optional TestExtensionOrderings2 test_ext_orderings2 = 12; + } + message TestExtensionOrderings3 { + extend TestFieldOrderings { + optional TestExtensionOrderings3 test_ext_orderings3 = 14; + } + optional string my_string = 1; + } + optional string my_string = 1; +} message TestExtremeDefaultValues { optional bytes escaped_bytes = 1 [default = "\0\001\a\b\f\n\r\t\v\\\'\"\xfe"]; @@ -946,3 +984,21 @@ message TestHugeFieldNumbers { extend TestHugeFieldNumbers { optional TestAllTypes test_all_types = 536860000; } + +message TestExtensionInsideTable { + optional int32 field1 = 1; + optional int32 field2 = 2; + optional int32 field3 = 3; + optional int32 field4 = 4; + extensions 5 to 5; + optional int32 field6 = 6; + optional int32 field7 = 7; + optional int32 field8 = 8; + optional int32 field9 = 9; + optional int32 field10 = 10; +} + +extend TestExtensionInsideTable { + optional int32 test_extension_inside_table_extension = 5; +} + diff --git a/src/google/protobuf/unittest_lite.proto b/src/google/protobuf/unittest_lite.proto index 9a15bdaa..f3ff2b5d 100644 --- a/src/google/protobuf/unittest_lite.proto +++ b/src/google/protobuf/unittest_lite.proto @@ -454,3 +454,22 @@ message TestOneofParsingLite { V2EnumLite oneof_enum = 9; } } + +// The following four messages are set up to test for wire compatibility between +// packed and non-packed repeated fields. We use the field number 2048, because +// that is large enough to require a 3-byte varint for the tag. +message PackedInt32 { + repeated int32 repeated_int32 = 2048 [packed = true]; +} + +message NonPackedInt32 { + repeated int32 repeated_int32 = 2048; +} + +message PackedFixed32 { + repeated fixed32 repeated_fixed32 = 2048 [packed = true]; +} + +message NonPackedFixed32 { + repeated fixed32 repeated_fixed32 = 2048; +} diff --git a/src/google/protobuf/unknown_field_set_unittest.cc b/src/google/protobuf/unknown_field_set_unittest.cc index e55bb012..a64769e7 100644 --- a/src/google/protobuf/unknown_field_set_unittest.cc +++ b/src/google/protobuf/unknown_field_set_unittest.cc @@ -49,6 +49,7 @@ #include <google/protobuf/stubs/mutex.h> #include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> + #include <google/protobuf/stubs/stl_util.h> namespace google { diff --git a/src/google/protobuf/util/delimited_message_util.cc b/src/google/protobuf/util/delimited_message_util.cc index 16378782..3ba930e7 100644 --- a/src/google/protobuf/util/delimited_message_util.cc +++ b/src/google/protobuf/util/delimited_message_util.cc @@ -12,7 +12,7 @@ bool SerializeDelimitedToFileDescriptor(const MessageLite& message, int file_des return SerializeDelimitedToZeroCopyStream(message, &output); } -bool SerializeDelimitedToOstream(const MessageLite& message, ostream* output) { +bool SerializeDelimitedToOstream(const MessageLite& message, std::ostream* output) { { io::OstreamOutputStream zero_copy_output(output); if (!SerializeDelimitedToZeroCopyStream(message, &zero_copy_output)) return false; diff --git a/src/google/protobuf/util/delimited_message_util.h b/src/google/protobuf/util/delimited_message_util.h index 302d4781..e8a7204a 100644 --- a/src/google/protobuf/util/delimited_message_util.h +++ b/src/google/protobuf/util/delimited_message_util.h @@ -32,7 +32,7 @@ namespace util { // underlying source, so instead you must keep using the same stream object. bool LIBPROTOBUF_EXPORT SerializeDelimitedToFileDescriptor(const MessageLite& message, int file_descriptor); -bool LIBPROTOBUF_EXPORT SerializeDelimitedToOstream(const MessageLite& message, ostream* output); +bool LIBPROTOBUF_EXPORT SerializeDelimitedToOstream(const MessageLite& message, std::ostream* output); // Read a single size-delimited message from the given stream. Delimited // format allows a single file or stream to contain multiple messages, diff --git a/src/google/protobuf/util/field_mask_util.cc b/src/google/protobuf/util/field_mask_util.cc index 8a413498..a2e2a388 100644 --- a/src/google/protobuf/util/field_mask_util.cc +++ b/src/google/protobuf/util/field_mask_util.cc @@ -31,6 +31,7 @@ #include <google/protobuf/util/field_mask_util.h> #include <google/protobuf/stubs/strutil.h> + #include <google/protobuf/stubs/map_util.h> namespace google { @@ -131,27 +132,27 @@ bool FieldMaskUtil::FromJsonString(StringPiece str, FieldMask* out) { bool FieldMaskUtil::GetFieldDescriptors( const Descriptor* descriptor, StringPiece path, std::vector<const FieldDescriptor*>* field_descriptors) { - if (field_descriptors != NULL) { + if (field_descriptors != nullptr) { field_descriptors->clear(); } std::vector<string> parts = Split(path, "."); for (int i = 0; i < parts.size(); ++i) { const string& field_name = parts[i]; - if (descriptor == NULL) { + if (descriptor == nullptr) { return false; } const FieldDescriptor* field = descriptor->FindFieldByName(field_name); - if (field == NULL) { + if (field == nullptr) { return false; } - if (field_descriptors != NULL) { + if (field_descriptors != nullptr) { field_descriptors->push_back(field); } if (!field->is_repeated() && field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { descriptor = field->message_type(); } else { - descriptor = NULL; + descriptor = nullptr; } } return true; @@ -342,6 +343,12 @@ void FieldMaskTree::AddPath(const string& path) { void FieldMaskTree::RemovePath(const string& path, const Descriptor* descriptor) { + if (root_.children.empty()) { + // Nothing to be removed from an empty tree. We shortcut it here so an empty + // tree won't be interpreted as a field mask containing all fields by the + // code below. + return; + } std::vector<string> parts = Split(path, "."); if (parts.empty()) { return; @@ -349,16 +356,16 @@ void FieldMaskTree::RemovePath(const string& path, std::vector<Node*> nodes(parts.size()); Node* node = &root_; const Descriptor* current_descriptor = descriptor; - Node* new_branch_node = NULL; + Node* new_branch_node = nullptr; for (int i = 0; i < parts.size(); ++i) { nodes[i] = node; const FieldDescriptor* field_descriptor = current_descriptor->FindFieldByName(parts[i]); - if (field_descriptor == NULL || + if (field_descriptor == nullptr || (field_descriptor->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE && i != parts.size() - 1)) { // Invalid path. - if (new_branch_node != NULL) { + if (new_branch_node != nullptr) { // If add any new nodes, cleanup. new_branch_node->ClearChildren(); } @@ -366,7 +373,7 @@ void FieldMaskTree::RemovePath(const string& path, } if (node->children.empty()) { - if (new_branch_node == NULL) { + if (new_branch_node == nullptr) { new_branch_node = node; } for (int i = 0; i < current_descriptor->field_count(); ++i) { @@ -542,7 +549,7 @@ void FieldMaskTree::AddRequiredFieldPath( if (field->is_required()) { const string& node_name = field->name(); Node*& child = node->children[node_name]; - if (child == NULL) { + if (child == nullptr) { // Add required field path to the tree child = new Node(); } else if (child->children.empty()){ diff --git a/src/google/protobuf/util/field_mask_util.h b/src/google/protobuf/util/field_mask_util.h index 91787bd5..f0299de9 100644 --- a/src/google/protobuf/util/field_mask_util.h +++ b/src/google/protobuf/util/field_mask_util.h @@ -70,14 +70,14 @@ class LIBPROTOBUF_EXPORT FieldMaskUtil { // Checks whether the given path is valid for type T. template <typename T> static bool IsValidPath(StringPiece path) { - return GetFieldDescriptors(T::descriptor(), path, NULL); + return GetFieldDescriptors(T::descriptor(), path, nullptr); } // Checks whether the given FieldMask is valid for type T. template <typename T> static bool IsValidFieldMask(const FieldMask& mask) { for (int i = 0; i < mask.paths_size(); ++i) { - if (!GetFieldDescriptors(T::descriptor(), mask.paths(i), NULL)) + if (!GetFieldDescriptors(T::descriptor(), mask.paths(i), nullptr)) return false; } return true; diff --git a/src/google/protobuf/util/field_mask_util_test.cc b/src/google/protobuf/util/field_mask_util_test.cc index 0664d9e5..3ba30aa3 100644 --- a/src/google/protobuf/util/field_mask_util_test.cc +++ b/src/google/protobuf/util/field_mask_util_test.cc @@ -168,7 +168,7 @@ TEST(FieldMaskUtilTest, GetFieldDescriptors) { EXPECT_EQ(1, field_descriptors.size()); EXPECT_EQ("optional_int32", field_descriptors[0]->name()); EXPECT_FALSE(FieldMaskUtil::GetFieldDescriptors( - TestAllTypes::descriptor(), "optional_nonexist", NULL)); + TestAllTypes::descriptor(), "optional_nonexist", nullptr)); EXPECT_TRUE(FieldMaskUtil::GetFieldDescriptors(TestAllTypes::descriptor(), "optional_nested_message.bb", &field_descriptors)); @@ -176,10 +176,10 @@ TEST(FieldMaskUtilTest, GetFieldDescriptors) { EXPECT_EQ("optional_nested_message", field_descriptors[0]->name()); EXPECT_EQ("bb", field_descriptors[1]->name()); EXPECT_FALSE(FieldMaskUtil::GetFieldDescriptors( - TestAllTypes::descriptor(), "optional_nested_message.nonexist", NULL)); + TestAllTypes::descriptor(), "optional_nested_message.nonexist", nullptr)); // FieldMask cannot be used to specify sub-fields of a repeated message. EXPECT_FALSE(FieldMaskUtil::GetFieldDescriptors( - TestAllTypes::descriptor(), "repeated_nested_message.bb", NULL)); + TestAllTypes::descriptor(), "repeated_nested_message.bb", nullptr)); } TEST(FieldMaskUtilTest, TestIsVaildPath) { @@ -386,6 +386,13 @@ TEST(FieldMaskUtilTest, TestSubtract) { FieldMaskUtil::FromString("optional_nested_message", &mask2); FieldMaskUtil::Subtract<TestAllTypes>(mask1, mask2, &out); EXPECT_EQ("", FieldMaskUtil::ToString(out)); + + // Regression test for b/72727550 + FieldMaskUtil::FromString("optional_foreign_message.c", &mask1); + FieldMaskUtil::FromString("optional_foreign_message,optional_nested_message", + &mask2); + FieldMaskUtil::Subtract<TestAllTypes>(mask1, mask2, &out); + EXPECT_EQ("", FieldMaskUtil::ToString(out)); } TEST(FieldMaskUtilTest, TestIspathInFieldMask) { diff --git a/src/google/protobuf/util/internal/datapiece.cc b/src/google/protobuf/util/internal/datapiece.cc index 213c2c40..59bc28ae 100644 --- a/src/google/protobuf/util/internal/datapiece.cc +++ b/src/google/protobuf/util/internal/datapiece.cc @@ -64,9 +64,9 @@ StatusOr<To> ValidateNumberConversion(To after, From before) { MathUtil::Sign<From>(before) == MathUtil::Sign<To>(after)) { return after; } else { - return InvalidArgument(::google::protobuf::internal::is_integral<From>::value + return InvalidArgument(std::is_integral<From>::value ? ValueAsString(before) - : ::google::protobuf::internal::is_same<From, double>::value + : std::is_same<From, double>::value ? DoubleAsString(before) : FloatAsString(before)); } @@ -77,7 +77,7 @@ StatusOr<To> ValidateNumberConversion(To after, From before) { // except conversion between double and float. template <typename To, typename From> StatusOr<To> NumberConvertAndCheck(From before) { - if (::google::protobuf::internal::is_same<From, To>::value) return before; + if (std::is_same<From, To>::value) return before; To after = static_cast<To>(before); return ValidateNumberConversion(after, before); @@ -87,7 +87,7 @@ StatusOr<To> NumberConvertAndCheck(From before) { // point types (double, float) only. template <typename To, typename From> StatusOr<To> FloatingPointToIntConvertAndCheck(From before) { - if (::google::protobuf::internal::is_same<From, To>::value) return before; + if (std::is_same<From, To>::value) return before; To after = static_cast<To>(before); return ValidateNumberConversion(after, before); @@ -272,7 +272,8 @@ StatusOr<string> DataPiece::ToBytes() const { } StatusOr<int> DataPiece::ToEnum(const google::protobuf::Enum* enum_type, - bool use_lower_camel_for_enums) const { + bool use_lower_camel_for_enums, + bool ignore_unknown_enum_values) const { if (type_ == TYPE_NULL) return google::protobuf::NULL_VALUE; if (type_ == TYPE_STRING) { @@ -280,7 +281,7 @@ StatusOr<int> DataPiece::ToEnum(const google::protobuf::Enum* enum_type, string enum_name = str_.ToString(); const google::protobuf::EnumValue* value = FindEnumValueByNameOrNull(enum_type, enum_name); - if (value != NULL) return value->number(); + if (value != nullptr) return value->number(); // Check if int version of enum is sent as string. StatusOr<int32> int_value = ToInt32(); @@ -296,15 +297,19 @@ StatusOr<int> DataPiece::ToEnum(const google::protobuf::Enum* enum_type, *it = *it == '-' ? '_' : ascii_toupper(*it); } value = FindEnumValueByNameOrNull(enum_type, enum_name); - if (value != NULL) return value->number(); + if (value != nullptr) return value->number(); // If use_lower_camel_for_enums is true try with enum name without // underscore. This will also accept camel case names as the enum_name has // been normalized before. if (use_lower_camel_for_enums) { value = FindEnumValueByNameWithoutUnderscoreOrNull(enum_type, enum_name); - if (value != NULL) return value->number(); + if (value != nullptr) return value->number(); } + + // If ignore_unknown_enum_values is true an unknown enum value is treated + // as the default + if (ignore_unknown_enum_values) return enum_type->enumvalue(0).number(); } else { // We don't need to check whether the value is actually declared in the // enum because we preserve unknown enum values as well. @@ -357,7 +362,8 @@ bool DataPiece::DecodeBase64(StringPiece src, string* dest) const { WebSafeBase64Escape(*dest, &encoded); // Remove trailing padding '=' characters before comparison. StringPiece src_no_padding = StringPiece(src).substr( - 0, src.ends_with("=") ? src.find_last_not_of('=') + 1 : src.length()); + 0, StringEndsWith(src, "=") ? src.find_last_not_of('=') + 1 + : src.length()); return encoded == src_no_padding; } return true; @@ -370,7 +376,8 @@ bool DataPiece::DecodeBase64(StringPiece src, string* dest) const { reinterpret_cast<const unsigned char*>(dest->data()), dest->length(), &encoded, false); StringPiece src_no_padding = StringPiece(src).substr( - 0, src.ends_with("=") ? src.find_last_not_of('=') + 1 : src.length()); + 0, StringEndsWith(src, "=") ? src.find_last_not_of('=') + 1 + : src.length()); return encoded == src_no_padding; } return true; diff --git a/src/google/protobuf/util/internal/datapiece.h b/src/google/protobuf/util/internal/datapiece.h index 83516d09..95b133da 100644 --- a/src/google/protobuf/util/internal/datapiece.h +++ b/src/google/protobuf/util/internal/datapiece.h @@ -164,7 +164,8 @@ class LIBPROTOBUF_EXPORT DataPiece { // If the value is not a string, attempts to convert to a 32-bit integer. // If none of these succeeds, returns a conversion error status. util::StatusOr<int> ToEnum(const google::protobuf::Enum* enum_type, - bool use_lower_camel_for_enums) const; + bool use_lower_camel_for_enums, + bool ignore_unknown_enum_values) const; private: // Disallow implicit constructor. diff --git a/src/google/protobuf/util/internal/default_value_objectwriter.cc b/src/google/protobuf/util/internal/default_value_objectwriter.cc index 95b3a17d..b41feb7a 100644 --- a/src/google/protobuf/util/internal/default_value_objectwriter.cc +++ b/src/google/protobuf/util/internal/default_value_objectwriter.cc @@ -62,11 +62,12 @@ DefaultValueObjectWriter::DefaultValueObjectWriter( : typeinfo_(TypeInfo::NewTypeInfo(type_resolver)), own_typeinfo_(true), type_(type), - current_(NULL), - root_(NULL), + current_(nullptr), + root_(nullptr), suppress_empty_list_(false), preserve_proto_field_names_(false), - field_scrub_callback_(NULL), + use_ints_for_enums_(false), + field_scrub_callback_(nullptr), ow_(ow) {} DefaultValueObjectWriter::~DefaultValueObjectWriter() { @@ -80,7 +81,7 @@ DefaultValueObjectWriter::~DefaultValueObjectWriter() { DefaultValueObjectWriter* DefaultValueObjectWriter::RenderBool(StringPiece name, bool value) { - if (current_ == NULL) { + if (current_ == nullptr) { ow_->RenderBool(name, value); } else { RenderDataPiece(name, DataPiece(value)); @@ -90,7 +91,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderBool(StringPiece name, DefaultValueObjectWriter* DefaultValueObjectWriter::RenderInt32( StringPiece name, int32 value) { - if (current_ == NULL) { + if (current_ == nullptr) { ow_->RenderInt32(name, value); } else { RenderDataPiece(name, DataPiece(value)); @@ -100,7 +101,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderInt32( DefaultValueObjectWriter* DefaultValueObjectWriter::RenderUint32( StringPiece name, uint32 value) { - if (current_ == NULL) { + if (current_ == nullptr) { ow_->RenderUint32(name, value); } else { RenderDataPiece(name, DataPiece(value)); @@ -110,7 +111,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderUint32( DefaultValueObjectWriter* DefaultValueObjectWriter::RenderInt64( StringPiece name, int64 value) { - if (current_ == NULL) { + if (current_ == nullptr) { ow_->RenderInt64(name, value); } else { RenderDataPiece(name, DataPiece(value)); @@ -120,7 +121,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderInt64( DefaultValueObjectWriter* DefaultValueObjectWriter::RenderUint64( StringPiece name, uint64 value) { - if (current_ == NULL) { + if (current_ == nullptr) { ow_->RenderUint64(name, value); } else { RenderDataPiece(name, DataPiece(value)); @@ -130,7 +131,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderUint64( DefaultValueObjectWriter* DefaultValueObjectWriter::RenderDouble( StringPiece name, double value) { - if (current_ == NULL) { + if (current_ == nullptr) { ow_->RenderDouble(name, value); } else { RenderDataPiece(name, DataPiece(value)); @@ -140,7 +141,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderDouble( DefaultValueObjectWriter* DefaultValueObjectWriter::RenderFloat( StringPiece name, float value) { - if (current_ == NULL) { + if (current_ == nullptr) { ow_->RenderBool(name, value); } else { RenderDataPiece(name, DataPiece(value)); @@ -150,7 +151,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderFloat( DefaultValueObjectWriter* DefaultValueObjectWriter::RenderString( StringPiece name, StringPiece value) { - if (current_ == NULL) { + if (current_ == nullptr) { ow_->RenderString(name, value); } else { // Since StringPiece is essentially a pointer, takes a copy of "value" to @@ -163,7 +164,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderString( DefaultValueObjectWriter* DefaultValueObjectWriter::RenderBytes( StringPiece name, StringPiece value) { - if (current_ == NULL) { + if (current_ == nullptr) { ow_->RenderBytes(name, value); } else { // Since StringPiece is essentially a pointer, takes a copy of "value" to @@ -176,7 +177,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderBytes( DefaultValueObjectWriter* DefaultValueObjectWriter::RenderNull( StringPiece name) { - if (current_ == NULL) { + if (current_ == nullptr) { ow_->RenderNull(name); } else { RenderDataPiece(name, DataPiece::NullData()); @@ -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,12 +238,13 @@ 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( StringPiece name) { if (name.empty() || kind_ != OBJECT) { - return NULL; + return nullptr; } for (int i = 0; i < children_.size(); ++i) { Node* child = children_[i]; @@ -249,7 +252,7 @@ DefaultValueObjectWriter::Node* DefaultValueObjectWriter::Node::FindChild( return child; } } - return NULL; + return nullptr; } void DefaultValueObjectWriter::Node::WriteTo(ObjectWriter* ow) { @@ -317,7 +320,7 @@ const google::protobuf::Type* DefaultValueObjectWriter::Node::GetMapValueType( } break; } - return NULL; + return nullptr; } void DefaultValueObjectWriter::Node::PopulateChildren( @@ -328,7 +331,7 @@ void DefaultValueObjectWriter::Node::PopulateChildren( // TODO(tsun): remove "kStructValueType" from the list. It's being checked // now because of a bug in the tool-chain that causes the "oneof_index" // of kStructValueType to not be set correctly. - if (type_ == NULL || type_->name() == kAnyType || + if (type_ == nullptr || type_->name() == kAnyType || type_->name() == kStructType || type_->name() == kTimestampType || type_->name() == kDurationType || type_->name() == kStructValueType) { return; @@ -351,7 +354,7 @@ void DefaultValueObjectWriter::Node::PopulateChildren( path.insert(path.begin(), path_.begin(), path_.end()); } path.push_back(field.name()); - if (field_scrub_callback_ != NULL && + if (field_scrub_callback_ != nullptr && field_scrub_callback_->Run(path, &field)) { continue; } @@ -362,11 +365,11 @@ void DefaultValueObjectWriter::Node::PopulateChildren( // of children. if (found != orig_children_map.end()) { new_children.push_back(children_[found->second]); - children_[found->second] = NULL; + children_[found->second] = nullptr; continue; } - const google::protobuf::Type* field_type = NULL; + const google::protobuf::Type* field_type = nullptr; bool is_map = false; NodeKind kind = PRIMITIVE; @@ -405,22 +408,22 @@ void DefaultValueObjectWriter::Node::PopulateChildren( // If the child field is of primitive type, sets its data to the default // value of its type. - google::protobuf::scoped_ptr<Node> child(new Node( + 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()); } // Adds all leftover nodes in children_ to the beginning of new_child. for (int i = 0; i < children_.size(); ++i) { - if (children_[i] == NULL) { + if (children_[i] == nullptr) { continue; } new_children.insert(new_children.begin(), children_[i]); - children_[i] = NULL; + children_[i] = nullptr; } children_.swap(new_children); } @@ -428,14 +431,14 @@ void DefaultValueObjectWriter::Node::PopulateChildren( void DefaultValueObjectWriter::MaybePopulateChildrenOfAny(Node* node) { // If this is an "Any" node with "@type" already given and no other children // have been added, populates its children. - if (node != NULL && node->is_any() && node->type() != NULL && + if (node != nullptr && node->is_any() && node->type() != nullptr && node->type()->name() != kAnyType && node->number_of_children() == 1) { node->PopulateChildren(typeinfo_); } } 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(); } } @@ -504,11 +507,11 @@ DataPiece DefaultValueObjectWriter::CreateDefaultDataPieceForField( DefaultValueObjectWriter* DefaultValueObjectWriter::StartObject( StringPiece name) { - if (current_ == NULL) { + if (current_ == nullptr) { 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(); @@ -516,17 +519,17 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::StartObject( } MaybePopulateChildrenOfAny(current_); Node* child = current_->FindChild(name); - if (current_->kind() == LIST || current_->kind() == MAP || child == NULL) { + if (current_->kind() == LIST || current_->kind() == MAP || child == nullptr) { // If current_ is a list or a map node, we should create a new child and use // the type of current_ as the type of the new child. - google::protobuf::scoped_ptr<Node> node( + std::unique_ptr<Node> node( CreateNewNode(string(name), ((current_->kind() == LIST || current_->kind() == MAP) ? current_->type() - : NULL), + : nullptr), OBJECT, DataPiece::NullData(), false, - child == NULL ? current_->path() : child->path(), - suppress_empty_list_, preserve_proto_field_names_, + child == nullptr ? current_->path() : child->path(), + suppress_empty_list_, preserve_proto_field_names_, use_ints_for_enums_, field_scrub_callback_.get())); child = node.get(); current_->AddChild(node.release()); @@ -555,22 +558,22 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::EndObject() { DefaultValueObjectWriter* DefaultValueObjectWriter::StartList( StringPiece name) { - if (current_ == NULL) { + if (current_ == nullptr) { 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; } MaybePopulateChildrenOfAny(current_); Node* child = current_->FindChild(name); - if (child == NULL || child->kind() != LIST) { - google::protobuf::scoped_ptr<Node> node( - CreateNewNode(string(name), NULL, LIST, DataPiece::NullData(), false, - child == NULL ? current_->path() : child->path(), - suppress_empty_list_, preserve_proto_field_names_, + if (child == nullptr || child->kind() != LIST) { + 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_, use_ints_for_enums_, field_scrub_callback_.get())); child = node.get(); current_->AddChild(node.release()); @@ -584,8 +587,8 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::StartList( void DefaultValueObjectWriter::WriteRoot() { root_->WriteTo(ow_); - root_.reset(NULL); - current_ = NULL; + root_.reset(nullptr); + current_ = nullptr; } DefaultValueObjectWriter* DefaultValueObjectWriter::EndList() { @@ -601,7 +604,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::EndList() { void DefaultValueObjectWriter::RenderDataPiece(StringPiece name, const DataPiece& data) { MaybePopulateChildrenOfAny(current_); - if (current_->type() != NULL && current_->type()->name() == kAnyType && + if (current_->type() != nullptr && current_->type()->name() == kAnyType && name == "@type") { util::StatusOr<string> data_string = data.ToString(); if (data_string.ok()) { @@ -621,18 +624,18 @@ void DefaultValueObjectWriter::RenderDataPiece(StringPiece name, // other children of primitive type now. Otherwise, we should wait until // the first value field is rendered before we populate the children, // because the "value" field of a Any message could be omitted. - if (current_->number_of_children() > 1 && current_->type() != NULL) { + if (current_->number_of_children() > 1 && current_->type() != nullptr) { current_->PopulateChildren(typeinfo_); } } } Node* child = current_->FindChild(name); - if (child == NULL || child->kind() != PRIMITIVE) { + if (child == nullptr || child->kind() != PRIMITIVE) { // No children are found, creates a new child. - google::protobuf::scoped_ptr<Node> node( - CreateNewNode(string(name), NULL, PRIMITIVE, data, false, - child == NULL ? current_->path() : child->path(), - suppress_empty_list_, preserve_proto_field_names_, + 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_, 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 09c6d23f..6e71f9c8 100644 --- a/src/google/protobuf/util/internal/default_value_objectwriter.h +++ b/src/google/protobuf/util/internal/default_value_objectwriter.h @@ -32,9 +32,6 @@ #define GOOGLE_PROTOBUF_UTIL_CONVERTER_DEFAULT_VALUE_OBJECTWRITER_H__ #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <stack> #include <vector> @@ -77,7 +74,7 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter { FieldScrubCallBack; // A unique pointer to a DefaultValueObjectWriter::FieldScrubCallBack. - typedef google::protobuf::scoped_ptr<FieldScrubCallBack> FieldScrubCallBackPtr; + typedef std::unique_ptr<FieldScrubCallBack> FieldScrubCallBackPtr; DefaultValueObjectWriter(TypeResolver* type_resolver, const google::protobuf::Type& type, @@ -131,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, @@ -150,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) { @@ -233,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_; @@ -256,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. @@ -272,7 +279,7 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter { void MaybePopulateChildrenOfAny(Node* node); // Writes the root_ node to ow_ and resets the root_ and current_ pointer to - // NULL. + // nullptr. void WriteRoot(); // Adds or replaces the data_ of a primitive child node. @@ -282,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. @@ -297,7 +305,7 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter { // The current Node. Owned by its parents. Node* current_; // The root Node. - google::protobuf::scoped_ptr<Node> root_; + std::unique_ptr<Node> root_; // The stack to hold the path of Nodes from current_ to root_; std::stack<Node*> stack_; @@ -307,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/internal/default_value_objectwriter_test.cc b/src/google/protobuf/util/internal/default_value_objectwriter_test.cc index e1dd697a..0c4af61b 100644 --- a/src/google/protobuf/util/internal/default_value_objectwriter_test.cc +++ b/src/google/protobuf/util/internal/default_value_objectwriter_test.cc @@ -60,7 +60,7 @@ class BaseDefaultValueObjectWriterTest TypeInfoTestHelper helper_; MockObjectWriter mock_; ExpectingObjectWriter expects_; - google::protobuf::scoped_ptr<DefaultValueObjectWriter> testing_; + std::unique_ptr<DefaultValueObjectWriter> testing_; }; // Tests to cover some basic DefaultValueObjectWriter use cases. More tests are @@ -156,7 +156,7 @@ class DefaultValueObjectWriterSuppressListTest : BaseDefaultValueObjectWriterTest(DefaultValueTest::descriptor()) { testing_->set_suppress_empty_list(true); } - ~DefaultValueObjectWriterSuppressListTest() {} + ~DefaultValueObjectWriterSuppressListTest() override {} }; INSTANTIATE_TEST_CASE_P(DifferentTypeInfoSourceTest, diff --git a/src/google/protobuf/util/internal/error_listener.h b/src/google/protobuf/util/internal/error_listener.h index 1dc814a3..a19bd3f7 100644 --- a/src/google/protobuf/util/internal/error_listener.h +++ b/src/google/protobuf/util/internal/error_listener.h @@ -33,9 +33,6 @@ #include <algorithm> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <string> #include <vector> diff --git a/src/google/protobuf/util/internal/field_mask_utility.cc b/src/google/protobuf/util/internal/field_mask_utility.cc index 38835f67..778a4510 100644 --- a/src/google/protobuf/util/internal/field_mask_utility.cc +++ b/src/google/protobuf/util/internal/field_mask_utility.cc @@ -30,6 +30,7 @@ #include <google/protobuf/util/internal/field_mask_utility.h> +#include <google/protobuf/util/internal/utility.h> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/status_macros.h> @@ -53,7 +54,7 @@ string AppendPathSegmentToPrefix(StringPiece prefix, StringPiece segment) { return prefix.ToString(); } // If the segment is a map key, appends it to the prefix without the ".". - if (segment.starts_with("[\"")) { + if (StringStartsWith(segment, "[\"")) { return StrCat(prefix, segment); } return StrCat(prefix, ".", segment); diff --git a/src/google/protobuf/util/internal/json_objectwriter.h b/src/google/protobuf/util/internal/json_objectwriter.h index 81da0500..81644dab 100644 --- a/src/google/protobuf/util/internal/json_objectwriter.h +++ b/src/google/protobuf/util/internal/json_objectwriter.h @@ -32,9 +32,6 @@ #define GOOGLE_PROTOBUF_UTIL_CONVERTER_JSON_OBJECTWRITER_H__ #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <string> #include <google/protobuf/io/coded_stream.h> @@ -89,7 +86,7 @@ class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter { public: JsonObjectWriter(StringPiece indent_string, google::protobuf::io::CodedOutputStream* out) - : element_(new Element(/*parent=*/NULL, /*is_json_object=*/false)), + : element_(new Element(/*parent=*/nullptr, /*is_json_object=*/false)), stream_(out), sink_(out), indent_string_(indent_string.ToString()), @@ -211,7 +208,7 @@ class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter { // Writes an individual character to the output. void WriteChar(const char c) { stream_->WriteRaw(&c, sizeof(c)); } - google::protobuf::scoped_ptr<Element> element_; + std::unique_ptr<Element> element_; google::protobuf::io::CodedOutputStream* stream_; ByteSinkWrapper sink_; const string indent_string_; diff --git a/src/google/protobuf/util/internal/json_objectwriter_test.cc b/src/google/protobuf/util/internal/json_objectwriter_test.cc index 8cc588a6..0dc710c7 100644 --- a/src/google/protobuf/util/internal/json_objectwriter_test.cc +++ b/src/google/protobuf/util/internal/json_objectwriter_test.cc @@ -47,7 +47,7 @@ class JsonObjectWriterTest : public ::testing::Test { JsonObjectWriterTest() : str_stream_(new StringOutputStream(&output_)), out_stream_(new CodedOutputStream(str_stream_)), - ow_(NULL) {} + ow_(nullptr) {} virtual ~JsonObjectWriterTest() { delete ow_; diff --git a/src/google/protobuf/util/internal/json_stream_parser.cc b/src/google/protobuf/util/internal/json_stream_parser.cc index 2ada3583..1c63b31d 100644 --- a/src/google/protobuf/util/internal/json_stream_parser.cc +++ b/src/google/protobuf/util/internal/json_stream_parser.cc @@ -36,9 +36,6 @@ #include <cstdlib> #include <cstring> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> @@ -157,7 +154,7 @@ util::Status JsonStreamParser::FinishParse() { } // Storage for UTF8-coerced string. - google::protobuf::scoped_array<char> utf8; + std::unique_ptr<char[]> utf8; if (coerce_to_utf8_) { utf8.reset(new char[leftover_.size()]); char* coerced = internal::UTF8CoerceToStructurallyValid(leftover_, utf8.get(), ' '); diff --git a/src/google/protobuf/util/internal/proto_writer.cc b/src/google/protobuf/util/internal/proto_writer.cc index 8bebf2ab..b7a52db6 100644 --- a/src/google/protobuf/util/internal/proto_writer.cc +++ b/src/google/protobuf/util/internal/proto_writer.cc @@ -66,7 +66,7 @@ ProtoWriter::ProtoWriter(TypeResolver* type_resolver, done_(false), ignore_unknown_fields_(false), use_lower_camel_for_enums_(false), - element_(NULL), + element_(nullptr), size_insert_(), output_(output), buffer_(), @@ -85,7 +85,7 @@ ProtoWriter::ProtoWriter(const TypeInfo* typeinfo, done_(false), ignore_unknown_fields_(false), use_lower_camel_for_enums_(false), - element_(NULL), + element_(nullptr), size_insert_(), output_(output), buffer_(), @@ -99,14 +99,14 @@ ProtoWriter::~ProtoWriter() { if (own_typeinfo_) { delete typeinfo_; } - if (element_ == NULL) return; + if (element_ == nullptr) return; // Cleanup explicitly in order to avoid destructor stack overflow when input // is deeply nested. // Cast to BaseElement to avoid doing additional checks (like missing fields) // during pop(). - google::protobuf::scoped_ptr<BaseElement> element( + std::unique_ptr<BaseElement> element( static_cast<BaseElement*>(element_.get())->pop<BaseElement>()); - while (element != NULL) { + while (element != nullptr) { element.reset(element->pop<BaseElement>()); } } @@ -267,8 +267,9 @@ inline Status WriteString(int field_number, const DataPiece& data, inline Status WriteEnum(int field_number, const DataPiece& data, const google::protobuf::Enum* enum_type, CodedOutputStream* stream, - bool use_lower_camel_for_enums) { - StatusOr<int> e = data.ToEnum(enum_type, use_lower_camel_for_enums); + bool use_lower_camel_for_enums, + bool ignore_unknown_values) { + StatusOr<int> e = data.ToEnum(enum_type, use_lower_camel_for_enums, ignore_unknown_values); if (e.ok()) { WireFormatLite::WriteEnum(field_number, e.ValueOrDie(), stream); } @@ -294,9 +295,9 @@ std::set<const google::protobuf::Field*> GetRequiredFields( ProtoWriter::ProtoElement::ProtoElement(const TypeInfo* typeinfo, const google::protobuf::Type& type, ProtoWriter* enclosing) - : BaseElement(NULL), + : BaseElement(nullptr), ow_(enclosing), - parent_field_(NULL), + parent_field_(nullptr), typeinfo_(typeinfo), proto3_(type.syntax() == google::protobuf::SYNTAX_PROTO3), type_(type), @@ -374,7 +375,7 @@ ProtoWriter::ProtoElement* ProtoWriter::ProtoElement::pop() { // all enclosing messages. int size = ow_->size_insert_[size_index_].size; int length = CodedOutputStream::VarintSize32(size); - for (ProtoElement* e = parent(); e != NULL; e = e->parent()) { + for (ProtoElement* e = parent(); e != nullptr; e = e->parent()) { // Only nested messages have size field, lists do not have size field. if (e->size_index_ >= 0) { ow_->size_insert_[e->size_index_].size += length; @@ -394,7 +395,7 @@ void ProtoWriter::ProtoElement::RegisterField( } string ProtoWriter::ProtoElement::ToString() const { - if (parent() == NULL) return ""; + if (parent() == nullptr) return ""; string loc = parent()->ToString(); if (!ow_->IsRepeated(*parent_field_) || parent()->parent_field_ != parent_field_) { @@ -439,7 +440,7 @@ void ProtoWriter::MissingField(StringPiece missing_name) { ProtoWriter* ProtoWriter::StartObject(StringPiece name) { // Starting the root message. Create the root ProtoElement and return. - if (element_ == NULL) { + if (element_ == nullptr) { if (!name.empty()) { InvalidName(name, "Root element should not be named."); } @@ -447,9 +448,9 @@ ProtoWriter* ProtoWriter::StartObject(StringPiece name) { return this; } - const google::protobuf::Field* field = NULL; + const google::protobuf::Field* field = nullptr; field = BeginNamed(name, false); - if (field == NULL) return this; + if (field == nullptr) return this; // Check to see if this field is a oneof and that no oneof in that group has // already been set. @@ -459,7 +460,7 @@ ProtoWriter* ProtoWriter::StartObject(StringPiece name) { } const google::protobuf::Type* type = LookupType(field); - if (type == NULL) { + if (type == nullptr) { ++invalid_depth_; InvalidName(name, StrCat("Missing descriptor for field: ", field->type_url())); @@ -475,14 +476,14 @@ ProtoWriter* ProtoWriter::EndObject() { return this; } - if (element_ != NULL) { + if (element_ != nullptr) { element_.reset(element_->pop()); } // If ending the root element, // then serialize the full message with calculated sizes. - if (element_ == NULL) { + if (element_ == nullptr) { WriteRootMessage(); } return this; @@ -490,7 +491,7 @@ ProtoWriter* ProtoWriter::EndObject() { ProtoWriter* ProtoWriter::StartList(StringPiece name) { const google::protobuf::Field* field = BeginNamed(name, true); - if (field == NULL) return this; + if (field == nullptr) return this; if (!ValidOneof(*field, name)) { ++invalid_depth_; @@ -498,7 +499,7 @@ ProtoWriter* ProtoWriter::StartList(StringPiece name) { } const google::protobuf::Type* type = LookupType(field); - if (type == NULL) { + if (type == nullptr) { ++invalid_depth_; InvalidName(name, StrCat("Missing descriptor for field: ", field->type_url())); @@ -511,7 +512,7 @@ ProtoWriter* ProtoWriter::StartList(StringPiece name) { ProtoWriter* ProtoWriter::EndList() { if (invalid_depth_ > 0) { --invalid_depth_; - } else if (element_ != NULL) { + } else if (element_ != nullptr) { element_.reset(element_->pop()); } return this; @@ -523,12 +524,12 @@ ProtoWriter* ProtoWriter::RenderDataPiece(StringPiece name, if (invalid_depth_ > 0) return this; const google::protobuf::Field* field = Lookup(name); - if (field == NULL) return this; + if (field == nullptr) return this; if (!ValidOneof(*field, name)) return this; const google::protobuf::Type* type = LookupType(field); - if (type == NULL) { + if (type == nullptr) { InvalidName(name, StrCat("Missing descriptor for field: ", field->type_url())); return this; @@ -539,7 +540,7 @@ ProtoWriter* ProtoWriter::RenderDataPiece(StringPiece name, bool ProtoWriter::ValidOneof(const google::protobuf::Field& field, StringPiece unnormalized_name) { - if (element_ == NULL) return true; + if (element_ == nullptr) return true; if (field.oneof_index() > 0) { if (element_->IsOneofIndexTaken(field.oneof_index())) { @@ -665,7 +666,8 @@ ProtoWriter* ProtoWriter::RenderPrimitiveField( case google::protobuf::Field_Kind_TYPE_ENUM: { status = WriteEnum(field.number(), data, typeinfo_->GetEnumByTypeUrl(field.type_url()), - stream_.get(), use_lower_camel_for_enums_); + stream_.get(), use_lower_camel_for_enums_, + ignore_unknown_fields_); break; } default: // TYPE_GROUP or TYPE_MESSAGE @@ -692,18 +694,18 @@ const google::protobuf::Field* ProtoWriter::BeginNamed(StringPiece name, bool is_list) { if (invalid_depth_ > 0) { ++invalid_depth_; - return NULL; + return nullptr; } const google::protobuf::Field* field = Lookup(name); - if (field == NULL) { + if (field == nullptr) { ++invalid_depth_; // InvalidName() already called in Lookup(). - return NULL; + return nullptr; } if (is_list && !IsRepeated(*field)) { ++invalid_depth_; InvalidName(name, "Proto field is not repeating, cannot start list."); - return NULL; + return nullptr; } return field; } @@ -711,23 +713,23 @@ const google::protobuf::Field* ProtoWriter::BeginNamed(StringPiece name, const google::protobuf::Field* ProtoWriter::Lookup( StringPiece unnormalized_name) { ProtoElement* e = element(); - if (e == NULL) { + if (e == nullptr) { InvalidName(unnormalized_name, "Root element must be a message."); - return NULL; + return nullptr; } if (unnormalized_name.empty()) { // Objects in repeated field inherit the same field descriptor. - if (e->parent_field() == NULL) { + if (e->parent_field() == nullptr) { InvalidName(unnormalized_name, "Proto fields must have a name."); } else if (!IsRepeated(*e->parent_field())) { InvalidName(unnormalized_name, "Proto fields must have a name."); - return NULL; + return nullptr; } return e->parent_field(); } const google::protobuf::Field* field = typeinfo_->FindField(&e->type(), unnormalized_name); - if (field == NULL && !ignore_unknown_fields_) { + if (field == nullptr && !ignore_unknown_fields_) { InvalidName(unnormalized_name, "Cannot find field."); } return field; @@ -746,7 +748,7 @@ void ProtoWriter::WriteRootMessage() { int curr_pos = 0; // Calls the destructor of CodedOutputStream to remove any uninitialized // memory from the Cord before we read it. - stream_.reset(NULL); + stream_.reset(nullptr); const void* data; int length; google::protobuf::io::ArrayInputStream input_stream(buffer_.data(), buffer_.size()); diff --git a/src/google/protobuf/util/internal/proto_writer.h b/src/google/protobuf/util/internal/proto_writer.h index 0db8485c..f2b4f42f 100644 --- a/src/google/protobuf/util/internal/proto_writer.h +++ b/src/google/protobuf/util/internal/proto_writer.h @@ -81,40 +81,40 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter { virtual ~ProtoWriter(); // ObjectWriter methods. - ProtoWriter* StartObject(StringPiece name); - ProtoWriter* EndObject(); - ProtoWriter* StartList(StringPiece name); - ProtoWriter* EndList(); - ProtoWriter* RenderBool(StringPiece name, bool value) { + ProtoWriter* StartObject(StringPiece name) override; + ProtoWriter* EndObject() override; + ProtoWriter* StartList(StringPiece name) override; + ProtoWriter* EndList() override; + ProtoWriter* RenderBool(StringPiece name, bool value) override { return RenderDataPiece(name, DataPiece(value)); } - ProtoWriter* RenderInt32(StringPiece name, int32 value) { + ProtoWriter* RenderInt32(StringPiece name, int32 value) override { return RenderDataPiece(name, DataPiece(value)); } - ProtoWriter* RenderUint32(StringPiece name, uint32 value) { + ProtoWriter* RenderUint32(StringPiece name, uint32 value) override { return RenderDataPiece(name, DataPiece(value)); } - ProtoWriter* RenderInt64(StringPiece name, int64 value) { + ProtoWriter* RenderInt64(StringPiece name, int64 value) override { return RenderDataPiece(name, DataPiece(value)); } - ProtoWriter* RenderUint64(StringPiece name, uint64 value) { + ProtoWriter* RenderUint64(StringPiece name, uint64 value) override { return RenderDataPiece(name, DataPiece(value)); } - ProtoWriter* RenderDouble(StringPiece name, double value) { + ProtoWriter* RenderDouble(StringPiece name, double value) override { return RenderDataPiece(name, DataPiece(value)); } - ProtoWriter* RenderFloat(StringPiece name, float value) { + ProtoWriter* RenderFloat(StringPiece name, float value) override { return RenderDataPiece(name, DataPiece(value)); } - ProtoWriter* RenderString(StringPiece name, StringPiece value) { + ProtoWriter* RenderString(StringPiece name, StringPiece value) override { return RenderDataPiece(name, DataPiece(value, use_strict_base64_decoding())); } - virtual ProtoWriter* RenderBytes(StringPiece name, StringPiece value) { + ProtoWriter* RenderBytes(StringPiece name, StringPiece value) override { return RenderDataPiece( name, DataPiece(value, false, use_strict_base64_decoding())); } - ProtoWriter* RenderNull(StringPiece name) { + ProtoWriter* RenderNull(StringPiece name) override { return RenderDataPiece(name, DataPiece::NullData()); } @@ -126,11 +126,11 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter { // Returns the location tracker to use for tracking locations for errors. const LocationTrackerInterface& location() { - return element_ != NULL ? *element_ : *tracker_; + return element_ != nullptr ? *element_ : *tracker_; } // When true, we finished writing to output a complete message. - bool done() { return done_; } + bool done() override { return done_; } // Returns the proto stream object. google::protobuf::io::CodedOutputStream* stream() { return stream_.get(); } @@ -173,7 +173,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter { ProtoElement* pop(); // Accessors - // parent_field() may be NULL if we are at root. + // parent_field() may be nullptr if we are at root. const google::protobuf::Field* parent_field() const { return parent_field_; } @@ -204,7 +204,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter { ProtoWriter* ow_; // Describes the element as a field in the parent message. - // parent_field_ is NULL if and only if this element is the root element. + // parent_field_ is nullptr if and only if this element is the root element. const google::protobuf::Field* parent_field_; // TypeInfo to lookup types. @@ -242,7 +242,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter { ProtoWriter(const TypeInfo* typeinfo, const google::protobuf::Type& type, strings::ByteSink* output, ErrorListener* listener); - ProtoElement* element() { return element_.get(); } + ProtoElement* element() override { return element_.get(); } // Helper methods for calling ErrorListener. See error_listener.h. void InvalidName(StringPiece unknown_name, StringPiece message); @@ -259,7 +259,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter { // extensions are found. const google::protobuf::Field* Lookup(StringPiece name); - // Lookup the field type in the type descriptor. Returns NULL if the type + // Lookup the field type in the type descriptor. Returns nullptr if the type // is not known. const google::protobuf::Type* LookupType( const google::protobuf::Field* field); @@ -309,7 +309,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter { // Indicates whether we finished writing root message completely. bool done_; - // If true, don't report unknown field names to the listener. + // If true, don't report unknown field names and enum values to the listener. bool ignore_unknown_fields_; // If true, check if enum name in camel case or without underscore matches the @@ -321,7 +321,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter { // size_insert_: sizes of nested messages. // pos - position to insert the size field. // size - size value to be inserted. - google::protobuf::scoped_ptr<ProtoElement> element_; + std::unique_ptr<ProtoElement> element_; std::deque<SizeInfo> size_insert_; // Variables for output generation: @@ -332,7 +332,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter { strings::ByteSink* output_; string buffer_; google::protobuf::io::StringOutputStream adapter_; - google::protobuf::scoped_ptr<google::protobuf::io::CodedOutputStream> stream_; + std::unique_ptr<google::protobuf::io::CodedOutputStream> stream_; // Variables for error tracking and reporting: // listener_ : a place to report any errors found. @@ -340,7 +340,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter { // tracker_ : the root location tracker interface. ErrorListener* listener_; int invalid_depth_; - google::protobuf::scoped_ptr<LocationTrackerInterface> tracker_; + std::unique_ptr<LocationTrackerInterface> tracker_; GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(ProtoWriter); }; diff --git a/src/google/protobuf/util/internal/protostream_objectsource.cc b/src/google/protobuf/util/internal/protostream_objectsource.cc index 72ad5a7a..b0d86c17 100644 --- a/src/google/protobuf/util/internal/protostream_objectsource.cc +++ b/src/google/protobuf/util/internal/protostream_objectsource.cc @@ -73,14 +73,14 @@ namespace { static int kDefaultMaxRecursionDepth = 64; -// Finds a field with the given number. NULL if none found. +// Finds a field with the given number. nullptr if none found. const google::protobuf::Field* FindFieldByNumber( const google::protobuf::Type& type, int number); // Returns true if the field is packable. bool IsPackable(const google::protobuf::Field& field); -// Finds an enum value with the given number. NULL if none found. +// Finds an enum value with the given number. nullptr if none found. const google::protobuf::EnumValue* FindEnumValueByNumber( const google::protobuf::Enum& tech_enum, int number); @@ -127,7 +127,7 @@ ProtoStreamObjectSource::ProtoStreamObjectSource( render_unknown_fields_(false), render_unknown_enum_values_(true), add_trailing_zeros_for_timestamp_and_duration_(false) { - GOOGLE_LOG_IF(DFATAL, stream == NULL) << "Input stream is NULL."; + GOOGLE_LOG_IF(DFATAL, stream == nullptr) << "Input stream is nullptr."; } ProtoStreamObjectSource::ProtoStreamObjectSource( @@ -145,7 +145,7 @@ ProtoStreamObjectSource::ProtoStreamObjectSource( render_unknown_fields_(false), render_unknown_enum_values_(true), add_trailing_zeros_for_timestamp_and_duration_(false) { - GOOGLE_LOG_IF(DFATAL, stream == NULL) << "Input stream is NULL."; + GOOGLE_LOG_IF(DFATAL, stream == nullptr) << "Input stream is nullptr."; } ProtoStreamObjectSource::~ProtoStreamObjectSource() { @@ -165,7 +165,7 @@ const google::protobuf::Field* ProtoStreamObjectSource::FindAndVerifyField( const google::protobuf::Field* field = FindFieldByNumber(type, tag >> 3); // Verify if the field corresponds to the wire type in tag. // If there is any discrepancy, mark the field as not found. - if (field != NULL) { + if (field != nullptr) { WireFormatLite::WireType expected_type = WireFormatLite::WireTypeForFieldType( static_cast<WireFormatLite::FieldType>(field->kind())); @@ -173,7 +173,7 @@ const google::protobuf::Field* ProtoStreamObjectSource::FindAndVerifyField( if (actual_type != expected_type && (!IsPackable(*field) || actual_type != WireFormatLite::WIRETYPE_LENGTH_DELIMITED)) { - field = NULL; + field = nullptr; } } return field; @@ -186,11 +186,11 @@ Status ProtoStreamObjectSource::WriteMessage(const google::protobuf::Type& type, ObjectWriter* ow) const { const TypeRenderer* type_renderer = FindTypeRenderer(type.name()); - if (type_renderer != NULL) { + if (type_renderer != nullptr) { return (*type_renderer)(this, type, name, ow); } - const google::protobuf::Field* field = NULL; + const google::protobuf::Field* field = nullptr; string field_name; // last_tag set to dummy value that is different from tag. uint32 tag = stream_->ReadTag(), last_tag = tag + 1; @@ -203,7 +203,7 @@ Status ProtoStreamObjectSource::WriteMessage(const google::protobuf::Type& type, if (tag != last_tag) { // Update field only if tag is changed. last_tag = tag; field = FindAndVerifyField(type, tag); - if (field != NULL) { + if (field != nullptr) { if (preserve_proto_field_names_) { field_name = field->name(); } else { @@ -211,11 +211,11 @@ Status ProtoStreamObjectSource::WriteMessage(const google::protobuf::Type& type, } } } - if (field == NULL) { + if (field == nullptr) { // If we didn't find a field, skip this unknown tag. // TODO(wpoon): Check return boolean value. WireFormat::SkipField(stream_, tag, - render_unknown_fields_ ? &unknown_fields : NULL); + render_unknown_fields_ ? &unknown_fields : nullptr); tag = stream_->ReadTag(); continue; } @@ -282,8 +282,8 @@ StatusOr<uint32> ProtoStreamObjectSource::RenderMap( for (uint32 tag = stream_->ReadTag(); tag != 0; tag = stream_->ReadTag()) { const google::protobuf::Field* field = FindAndVerifyField(*field_type, tag); - if (field == NULL) { - WireFormat::SkipField(stream_, tag, NULL); + if (field == nullptr) { + WireFormat::SkipField(stream_, tag, nullptr); continue; } // Map field numbers are key = 1 and value = 2 @@ -294,7 +294,7 @@ StatusOr<uint32> ProtoStreamObjectSource::RenderMap( // An absent map key is treated as the default. const google::protobuf::Field* key_field = FindFieldByNumber(*field_type, 1); - if (key_field == NULL) { + if (key_field == nullptr) { // The Type info for this map entry is incorrect. It should always // have a field named "key" and with field number 1. return Status(util::error::INTERNAL, "Invalid map entry."); @@ -525,7 +525,7 @@ Status ProtoStreamObjectSource::RenderStruct(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece field_name, ObjectWriter* ow) { - const google::protobuf::Field* field = NULL; + const google::protobuf::Field* field = nullptr; uint32 tag = os->stream_->ReadTag(); ow->StartObject(field_name); while (tag != 0) { @@ -543,12 +543,12 @@ Status ProtoStreamObjectSource::RenderStruct(const ProtoStreamObjectSource* os, Status ProtoStreamObjectSource::RenderStructValue( const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece field_name, ObjectWriter* ow) { - const google::protobuf::Field* field = NULL; + const google::protobuf::Field* field = nullptr; for (uint32 tag = os->stream_->ReadTag(); tag != 0; tag = os->stream_->ReadTag()) { field = os->FindAndVerifyField(type, tag); - if (field == NULL) { - WireFormat::SkipField(os->stream_, tag, NULL); + if (field == nullptr) { + WireFormat::SkipField(os->stream_, tag, nullptr); continue; } RETURN_IF_ERROR(os->RenderField(field, field_name, ow)); @@ -571,8 +571,8 @@ Status ProtoStreamObjectSource::RenderStructListValue( while (tag != 0) { const google::protobuf::Field* field = os->FindAndVerifyField(type, tag); - if (field == NULL) { - WireFormat::SkipField(os->stream_, tag, NULL); + if (field == nullptr) { + WireFormat::SkipField(os->stream_, tag, nullptr); tag = os->stream_->ReadTag(); continue; } @@ -593,8 +593,8 @@ Status ProtoStreamObjectSource::RenderAny(const ProtoStreamObjectSource* os, // First read out the type_url and value from the proto stream for (tag = os->stream_->ReadTag(); tag != 0; tag = os->stream_->ReadTag()) { const google::protobuf::Field* field = os->FindAndVerifyField(type, tag); - if (field == NULL) { - WireFormat::SkipField(os->stream_, tag, NULL); + if (field == nullptr) { + WireFormat::SkipField(os->stream_, tag, nullptr); continue; } // 'type_url' has field number of 1 and 'value' has field number 2 @@ -648,6 +648,13 @@ Status ProtoStreamObjectSource::RenderAny(const ProtoStreamObjectSource* os, // using a nested ProtoStreamObjectSource using our nested type information. ProtoStreamObjectSource nested_os(&in_stream, os->typeinfo_, *nested_type); + // TODO(htuch): This is somewhat fragile, since new options may be omitted. + // We should probably do this via the constructor or some object grouping + // options. + nested_os.set_use_lower_camel_for_enums(os->use_lower_camel_for_enums_); + nested_os.set_use_ints_for_enums(os->use_ints_for_enums_); + nested_os.set_preserve_proto_field_names(os->preserve_proto_field_names_); + // We manually call start and end object here so we can inject the @type. ow->StartObject(field_name); ow->RenderString("@type", type_url); @@ -667,7 +674,7 @@ Status ProtoStreamObjectSource::RenderFieldMask( tag = os->stream_->ReadTag()) { if (paths_field_tag == 0) { const google::protobuf::Field* field = os->FindAndVerifyField(type, tag); - if (field != NULL && field->number() == 1 && + if (field != nullptr && field->number() == 1 && field->name() == "paths") { paths_field_tag = tag; } @@ -754,7 +761,7 @@ Status ProtoStreamObjectSource::RenderField( // Get the nested message type for this field. const google::protobuf::Type* type = typeinfo_->GetTypeByTypeUrl(field->type_url()); - if (type == NULL) { + if (type == nullptr) { return Status(util::error::INTERNAL, StrCat("Invalid configuration. Could not find the type: ", field->type_url())); @@ -763,7 +770,7 @@ Status ProtoStreamObjectSource::RenderField( // Short-circuit any special type rendering to save call-stack space. const TypeRenderer* type_renderer = FindTypeRenderer(type->name()); - bool use_type_renderer = type_renderer != NULL; + bool use_type_renderer = type_renderer != nullptr; if (use_type_renderer) { RETURN_IF_ERROR((*type_renderer)(this, *type, field_name, ow)); @@ -873,14 +880,15 @@ Status ProtoStreamObjectSource::RenderNonMessageField( typeinfo_->GetEnumByTypeUrl(field->type_url()); // Lookup the name of the enum, and render that. Unknown enum values // are printed as integers. - if (en != NULL) { + if (en != nullptr) { const google::protobuf::EnumValue* enum_value = FindEnumValueByNumber(*en, buffer32); - if (enum_value != NULL) { + if (enum_value != nullptr) { if (use_ints_for_enums_) { ow->RenderInt32(field_name, buffer32); } else if (use_lower_camel_for_enums_) { - ow->RenderString(field_name, ToCamelCase(enum_value->name())); + ow->RenderString(field_name, + EnumValueNameToLowerCamelCase(enum_value->name())); } else { ow->RenderString(field_name, enum_value->name()); } @@ -1002,10 +1010,10 @@ const string ProtoStreamObjectSource::ReadFieldValueAsString( const google::protobuf::Enum* en = typeinfo_->GetEnumByTypeUrl(field.type_url()); // Lookup the name of the enum, and render that. Skips unknown enums. - if (en != NULL) { + if (en != nullptr) { const google::protobuf::EnumValue* enum_value = FindEnumValueByNumber(*en, buffer32); - if (enum_value != NULL) { + if (enum_value != nullptr) { result = enum_value->name(); } } @@ -1049,8 +1057,8 @@ std::pair<int64, int32> ProtoStreamObjectSource::ReadSecondsAndNanos( for (tag = stream_->ReadTag(); tag != 0; tag = stream_->ReadTag()) { const google::protobuf::Field* field = FindAndVerifyField(type, tag); - if (field == NULL) { - WireFormat::SkipField(stream_, tag, NULL); + if (field == nullptr) { + WireFormat::SkipField(stream_, tag, nullptr); continue; } // 'seconds' has field number of 1 and 'nanos' has field number 2 @@ -1088,7 +1096,7 @@ const google::protobuf::Field* FindFieldByNumber( return &type.fields(i); } } - return NULL; + return nullptr; } // TODO(skarvaje): Replace FieldDescriptor by implementing IsTypePackable() @@ -1109,7 +1117,7 @@ const google::protobuf::EnumValue* FindEnumValueByNumber( return &ev; } } - return NULL; + return nullptr; } // TODO(skarvaje): Look into optimizing this by not doing computation on diff --git a/src/google/protobuf/util/internal/protostream_objectsource_test.cc b/src/google/protobuf/util/internal/protostream_objectsource_test.cc index 36bb1ba9..4d86b856 100644 --- a/src/google/protobuf/util/internal/protostream_objectsource_test.cc +++ b/src/google/protobuf/util/internal/protostream_objectsource_test.cc @@ -31,9 +31,6 @@ #include <google/protobuf/util/internal/protostream_objectsource.h> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <sstream> #include <google/protobuf/stubs/casts.h> @@ -103,6 +100,7 @@ class ProtostreamObjectSourceTest ow_(&mock_), use_lower_camel_for_enums_(false), use_ints_for_enums_(false), + use_preserve_proto_field_names_(false), add_trailing_zeros_(false), render_unknown_enum_values_(true) { helper_.ResetTypeInfo(Book::descriptor(), Proto3Message::descriptor()); @@ -122,10 +120,11 @@ class ProtostreamObjectSourceTest ArrayInputStream arr_stream(proto.data(), proto.size()); CodedInputStream in_stream(&arr_stream); - google::protobuf::scoped_ptr<ProtoStreamObjectSource> os( + std::unique_ptr<ProtoStreamObjectSource> os( helper_.NewProtoSource(&in_stream, GetTypeUrl(descriptor))); if (use_lower_camel_for_enums_) os->set_use_lower_camel_for_enums(true); if (use_ints_for_enums_) os->set_use_ints_for_enums(true); + if (use_preserve_proto_field_names_) os->set_preserve_proto_field_names(true); os->set_max_recursion_depth(64); return os->WriteTo(&mock_); } @@ -275,6 +274,8 @@ class ProtostreamObjectSourceTest void UseIntsForEnums() { use_ints_for_enums_ = true; } + void UsePreserveProtoFieldNames() { use_preserve_proto_field_names_ = true; } + void AddTrailingZeros() { add_trailing_zeros_ = true; } void SetRenderUnknownEnumValues(bool value) { @@ -287,6 +288,7 @@ class ProtostreamObjectSourceTest ExpectingObjectWriter ow_; bool use_lower_camel_for_enums_; bool use_ints_for_enums_; + bool use_preserve_proto_field_names_; bool add_trailing_zeros_; bool render_unknown_enum_values_; }; @@ -490,7 +492,7 @@ TEST_P(ProtostreamObjectSourceTest, DoTest(book, Book::descriptor()); } -TEST_P(ProtostreamObjectSourceTest, LowerCamelEnumOutputTest) { +TEST_P(ProtostreamObjectSourceTest, LowerCamelEnumOutputMacroCase) { Book book; book.set_type(Book::ACTION_AND_ADVENTURE); @@ -500,6 +502,26 @@ TEST_P(ProtostreamObjectSourceTest, LowerCamelEnumOutputTest) { DoTest(book, Book::descriptor()); } +TEST_P(ProtostreamObjectSourceTest, LowerCamelEnumOutputSnakeCase) { + Book book; + book.set_type(Book::arts_and_photography); + + UseLowerCamelForEnums(); + + ow_.StartObject("")->RenderString("type", "artsAndPhotography")->EndObject(); + DoTest(book, Book::descriptor()); +} + +TEST_P(ProtostreamObjectSourceTest, LowerCamelEnumOutputWithNumber) { + Book book; + book.set_type(Book::I18N_Tech); + + UseLowerCamelForEnums(); + + ow_.StartObject("")->RenderString("type", "i18nTech")->EndObject(); + DoTest(book, Book::descriptor()); +} + TEST_P(ProtostreamObjectSourceTest, EnumCaseIsUnchangedByDefault) { Book book; book.set_type(Book::ACTION_AND_ADVENTURE); @@ -519,6 +541,16 @@ TEST_P(ProtostreamObjectSourceTest, UseIntsForEnumsTest) { DoTest(book, Book::descriptor()); } +TEST_P(ProtostreamObjectSourceTest, UsePreserveProtoFieldNames) { + Book book; + book.set_snake_field("foo"); + + UsePreserveProtoFieldNames(); + + ow_.StartObject("")->RenderString("snake_field", "foo")->EndObject(); + DoTest(book, Book::descriptor()); +} + TEST_P(ProtostreamObjectSourceTest, UnknownEnumAreDroppedWhenRenderUnknownEnumValuesIsUnset) { Proto3Message message; @@ -752,6 +784,69 @@ TEST_P(ProtostreamObjectSourceAnysTest, BasicAny) { DoTest(out, AnyOut::descriptor()); } +TEST_P(ProtostreamObjectSourceAnysTest, LowerCamelEnumOutputSnakeCase) { + AnyOut out; + ::google::protobuf::Any* any = out.mutable_any(); + + Book book; + book.set_type(Book::arts_and_photography); + any->PackFrom(book); + + UseLowerCamelForEnums(); + + ow_.StartObject("") + ->StartObject("any") + ->RenderString("@type", + "type.googleapis.com/google.protobuf.testing.Book") + ->RenderString("type", "artsAndPhotography") + ->EndObject() + ->EndObject(); + + DoTest(out, AnyOut::descriptor()); +} + +TEST_P(ProtostreamObjectSourceAnysTest, UseIntsForEnumsTest) { + AnyOut out; + ::google::protobuf::Any* any = out.mutable_any(); + + Book book; + book.set_type(Book::ACTION_AND_ADVENTURE); + any->PackFrom(book); + + UseIntsForEnums(); + + ow_.StartObject("") + ->StartObject("any") + ->RenderString("@type", + "type.googleapis.com/google.protobuf.testing.Book") + ->RenderInt32("type", 3) + ->EndObject() + ->EndObject(); + + DoTest(out, AnyOut::descriptor()); +} + +TEST_P(ProtostreamObjectSourceAnysTest, UsePreserveProtoFieldNames) { + AnyOut out; + ::google::protobuf::Any* any = out.mutable_any(); + + Book book; + book.set_snake_field("foo"); + any->PackFrom(book); + + UsePreserveProtoFieldNames(); + + ow_.StartObject("") + ->StartObject("any") + ->RenderString("@type", + "type.googleapis.com/google.protobuf.testing.Book") + ->RenderString("snake_field", "foo") + ->EndObject() + ->EndObject(); + + DoTest(out, AnyOut::descriptor()); +} + TEST_P(ProtostreamObjectSourceAnysTest, RecursiveAny) { AnyOut out; ::google::protobuf::Any* any = out.mutable_any(); diff --git a/src/google/protobuf/util/internal/protostream_objectwriter.cc b/src/google/protobuf/util/internal/protostream_objectwriter.cc index 97f96819..a1a7030a 100644 --- a/src/google/protobuf/util/internal/protostream_objectwriter.cc +++ b/src/google/protobuf/util/internal/protostream_objectwriter.cc @@ -62,7 +62,7 @@ ProtoStreamObjectWriter::ProtoStreamObjectWriter( const ProtoStreamObjectWriter::Options& options) : ProtoWriter(type_resolver, type, output, listener), master_type_(type), - current_(NULL), + current_(nullptr), options_(options) { set_ignore_unknown_fields(options_.ignore_unknown_fields); set_use_lower_camel_for_enums(options_.use_lower_camel_for_enums); @@ -73,18 +73,18 @@ ProtoStreamObjectWriter::ProtoStreamObjectWriter( strings::ByteSink* output, ErrorListener* listener) : ProtoWriter(typeinfo, type, output, listener), master_type_(type), - current_(NULL), + current_(nullptr), options_(ProtoStreamObjectWriter::Options::Defaults()) {} ProtoStreamObjectWriter::~ProtoStreamObjectWriter() { - if (current_ == NULL) return; + if (current_ == nullptr) return; // Cleanup explicitly in order to avoid destructor stack overflow when input // is deeply nested. // Cast to BaseElement to avoid doing additional checks (like missing fields) // during pop(). - google::protobuf::scoped_ptr<BaseElement> element( + std::unique_ptr<BaseElement> element( static_cast<BaseElement*>(current_.get())->pop<BaseElement>()); - while (element != NULL) { + while (element != nullptr) { element.reset(element->pop<BaseElement>()); } } @@ -186,7 +186,7 @@ ProtoStreamObjectWriter::AnyWriter::AnyWriter(ProtoStreamObjectWriter* parent) output_(&data_), depth_(0), is_well_known_type_(false), - well_known_type_render_(NULL) {} + well_known_type_render_(nullptr) {} ProtoStreamObjectWriter::AnyWriter::~AnyWriter() {} @@ -195,7 +195,7 @@ void ProtoStreamObjectWriter::AnyWriter::StartObject(StringPiece name) { // If an object writer is absent, that means we have not called StartAny() // before reaching here, which happens when we have data before the "@type" // field. - if (ow_ == NULL) { + if (ow_ == nullptr) { // Save data before the "@type" field for later replay. uninterpreted_events_.push_back(Event(Event::START_OBJECT, name)); } else if (is_well_known_type_ && depth_ == 1) { @@ -217,7 +217,7 @@ void ProtoStreamObjectWriter::AnyWriter::StartObject(StringPiece name) { bool ProtoStreamObjectWriter::AnyWriter::EndObject() { --depth_; - if (ow_ == NULL) { + if (ow_ == nullptr) { if (depth_ >= 0) { // Save data before the "@type" field for later replay. uninterpreted_events_.push_back(Event(Event::END_OBJECT)); @@ -239,7 +239,7 @@ bool ProtoStreamObjectWriter::AnyWriter::EndObject() { void ProtoStreamObjectWriter::AnyWriter::StartList(StringPiece name) { ++depth_; - if (ow_ == NULL) { + if (ow_ == nullptr) { // Save data before the "@type" field for later replay. uninterpreted_events_.push_back(Event(Event::START_LIST, name)); } else if (is_well_known_type_ && depth_ == 1) { @@ -260,7 +260,7 @@ void ProtoStreamObjectWriter::AnyWriter::EndList() { GOOGLE_LOG(DFATAL) << "Mismatched EndList found, should not be possible"; depth_ = 0; } - if (ow_ == NULL) { + if (ow_ == nullptr) { // Save data before the "@type" field for later replay. uninterpreted_events_.push_back(Event(Event::END_LIST)); } else { @@ -272,9 +272,9 @@ void ProtoStreamObjectWriter::AnyWriter::RenderDataPiece( StringPiece name, const DataPiece& value) { // Start an Any only at depth_ 0. Other RenderDataPiece calls with "@type" // should go to the contained ow_ as they indicate nested Anys. - if (depth_ == 0 && ow_ == NULL && name == "@type") { + if (depth_ == 0 && ow_ == nullptr && name == "@type") { StartAny(value); - } else if (ow_ == NULL) { + } else if (ow_ == nullptr) { // Save data before the "@type" field. uninterpreted_events_.push_back(Event(name, value)); } else if (depth_ == 0 && is_well_known_type_) { @@ -283,7 +283,7 @@ void ProtoStreamObjectWriter::AnyWriter::RenderDataPiece( "Expect a \"value\" field for well-known types."); invalid_ = true; } - if (well_known_type_render_ == NULL) { + if (well_known_type_render_ == nullptr) { // Only Any and Struct don't have a special type render but both of // them expect a JSON object (i.e., a StartObject() call). if (value.type() != DataPiece::TYPE_NULL && !invalid_) { @@ -327,7 +327,7 @@ void ProtoStreamObjectWriter::AnyWriter::StartAny(const DataPiece& value) { const google::protobuf::Type* type = resolved_type.ValueOrDie(); well_known_type_render_ = FindTypeRenderer(type_url_); - if (well_known_type_render_ != NULL || + if (well_known_type_render_ != nullptr || // Explicitly list Any and Struct here because they don't have a // custom renderer. type->name() == kAnyType || type->name() == kStructType) { @@ -360,7 +360,7 @@ void ProtoStreamObjectWriter::AnyWriter::StartAny(const DataPiece& value) { } void ProtoStreamObjectWriter::AnyWriter::WriteAny() { - if (ow_ == NULL) { + if (ow_ == nullptr) { if (uninterpreted_events_.empty()) { // We never got any content, so just return immediately, which is // equivalent to writing an empty Any. @@ -421,7 +421,7 @@ void ProtoStreamObjectWriter::AnyWriter::Event::DeepCopy() { ProtoStreamObjectWriter::Item::Item(ProtoStreamObjectWriter* enclosing, ItemType item_type, bool is_placeholder, bool is_list) - : BaseElement(NULL), + : BaseElement(nullptr), ow_(enclosing), any_(), item_type_(item_type), @@ -467,7 +467,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartObject( // Starting the root message. Create the root Item and return. // ANY message type does not need special handling, just set the ItemType // to ANY. - if (current_ == NULL) { + if (current_ == nullptr) { ProtoWriter::StartObject(name); current_.reset(new Item( this, master_type_.name() == kAnyType ? Item::ANY : Item::MESSAGE, @@ -534,21 +534,21 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartObject( Push("", Item::MESSAGE, false, false); ProtoWriter::RenderDataPiece("key", DataPiece(name, use_strict_base64_decoding())); - Push("value", Item::MESSAGE, true, false); + Push("value", IsAny(*Lookup("value")) ? Item::ANY : Item::MESSAGE, true, false); // Make sure we are valid so far after starting map fields. if (invalid_depth() > 0) return this; // If top of stack is g.p.Struct type, start the struct the map field within // it. - if (element() != NULL && IsStruct(*element()->parent_field())) { + if (element() != nullptr && IsStruct(*element()->parent_field())) { // Render "fields": [ Push("fields", Item::MAP, true, true); return this; } // If top of stack is g.p.Value type, start the Struct within it. - if (element() != NULL && IsStructValue(*element()->parent_field())) { + if (element() != nullptr && IsStructValue(*element()->parent_field())) { // Render // "struct_value": { // "fields": [ @@ -559,7 +559,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartObject( } const google::protobuf::Field* field = BeginNamed(name, false); - if (field == NULL) return this; + if (field == nullptr) return this; if (IsStruct(*field)) { // Start a struct object. @@ -607,7 +607,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::EndObject() { return this; } - if (current_ == NULL) return this; + if (current_ == nullptr) return this; if (current_->IsAny()) { if (current_->any()->EndObject()) return this; @@ -627,7 +627,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartList(StringPiece name) { // Since we cannot have a top-level repeated item in protobuf, the only way // this is valid is if we start a special type google.protobuf.ListValue or // google.protobuf.Value. - if (current_ == NULL) { + if (current_ == nullptr) { if (!name.empty()) { InvalidName(name, "Root element should not be named."); IncrementInvalidDepth(); @@ -706,7 +706,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartList(StringPiece name) { if (invalid_depth() > 0) return this; // case i and ii above. Start "list_value" field within g.p.Value - if (element() != NULL && element()->parent_field() != NULL) { + if (element() != nullptr && element()->parent_field() != nullptr) { // Render // "list_value": { // "values": [ // Start this list @@ -734,7 +734,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartList(StringPiece name) { // When name is empty and stack is not empty, we are rendering an item within // a list. if (name.empty()) { - if (element() != NULL && element()->parent_field() != NULL) { + if (element() != nullptr && element()->parent_field() != nullptr) { if (IsStructValue(*element()->parent_field())) { // Since it is g.p.Value, we bind directly to the list_value. // Render @@ -765,7 +765,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartList(StringPiece name) { // name is not empty const google::protobuf::Field* field = Lookup(name); - if (field == NULL) { + if (field == nullptr) { IncrementInvalidDepth(); return this; } @@ -837,7 +837,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::EndList() { return this; } - if (current_ == NULL) return this; + if (current_ == nullptr) return this; if (current_->IsAny()) { current_->any()->EndList(); @@ -961,7 +961,7 @@ Status ProtoStreamObjectWriter::RenderFieldMask(ProtoStreamObjectWriter* ow, // TODO(tsun): figure out how to do proto descriptor based snake case // conversions as much as possible. Because ToSnakeCase sometimes returns the // wrong value. - google::protobuf::scoped_ptr<ResultCallback1<util::Status, StringPiece> > callback( + std::unique_ptr<ResultCallback1<util::Status, StringPiece> > callback( ::google::protobuf::NewPermanentCallback(&RenderOneFieldPath, ow)); return DecodeCompactFieldMaskPaths(data.str(), callback.get()); } @@ -977,13 +977,13 @@ Status ProtoStreamObjectWriter::RenderDuration(ProtoStreamObjectWriter* ow, StringPiece value(data.str()); - if (!value.ends_with("s")) { + if (!StringEndsWith(value, "s")) { return Status(INVALID_ARGUMENT, "Illegal duration format; duration must end with 's'"); } value = value.substr(0, value.size() - 1); int sign = 1; - if (value.starts_with("-")) { + if (StringStartsWith(value, "-")) { sign = -1; value = value.substr(1); } @@ -1028,10 +1028,10 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::RenderDataPiece( Status status; if (invalid_depth() > 0) return this; - if (current_ == NULL) { + if (current_ == nullptr) { const TypeRenderer* type_renderer = FindTypeRenderer(GetFullTypeWithUrl(master_type_.name())); - if (type_renderer == NULL) { + if (type_renderer == nullptr) { InvalidName(name, "Root element must be a message."); return this; } @@ -1054,7 +1054,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::RenderDataPiece( return this; } - const google::protobuf::Field* field = NULL; + const google::protobuf::Field* field = nullptr; if (current_->IsMap()) { if (!ValidMapKey(name)) return this; @@ -1064,14 +1064,14 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::RenderDataPiece( ProtoWriter::RenderDataPiece("key", DataPiece(name, use_strict_base64_decoding())); field = Lookup("value"); - if (field == NULL) { + if (field == nullptr) { Pop(); GOOGLE_LOG(DFATAL) << "Map does not have a value field."; return this; } const TypeRenderer* type_renderer = FindTypeRenderer(field->type_url()); - if (type_renderer != NULL) { + if (type_renderer != nullptr) { // Map's value type is a special type. Render it like a message: // "value": { // ... Render special type ... @@ -1101,11 +1101,11 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::RenderDataPiece( } field = Lookup(name); - if (field == NULL) return this; + if (field == nullptr) return this; // Check if the field is of special type. Render it accordingly if so. const TypeRenderer* type_renderer = FindTypeRenderer(field->type_url()); - if (type_renderer != NULL) { + if (type_renderer != nullptr) { // Pass through null value only for google.protobuf.Value. For other // types we ignore null value just like for regular field types. if (data.type() != DataPiece::TYPE_NULL || @@ -1199,7 +1199,7 @@ ProtoStreamObjectWriter::FindTypeRenderer(const string& type_url) { } bool ProtoStreamObjectWriter::ValidMapKey(StringPiece unnormalized_name) { - if (current_ == NULL) return true; + if (current_ == nullptr) return true; if (!current_->InsertMapKeyIfNotPresent(unnormalized_name)) { listener()->InvalidName( @@ -1224,10 +1224,10 @@ void ProtoStreamObjectWriter::Push(StringPiece name, Item::ItemType item_type, void ProtoStreamObjectWriter::Pop() { // Pop all placeholder items sending StartObject or StartList events to // ProtoWriter according to is_list value. - while (current_ != NULL && current_->is_placeholder()) { + while (current_ != nullptr && current_->is_placeholder()) { PopOneElement(); } - if (current_ != NULL) { + if (current_ != nullptr) { PopOneElement(); } } diff --git a/src/google/protobuf/util/internal/protostream_objectwriter.h b/src/google/protobuf/util/internal/protostream_objectwriter.h index ab534912..c33a4639 100644 --- a/src/google/protobuf/util/internal/protostream_objectwriter.h +++ b/src/google/protobuf/util/internal/protostream_objectwriter.h @@ -216,7 +216,7 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter { ProtoStreamObjectWriter* parent_; // The nested object writer, used to write events. - google::protobuf::scoped_ptr<ProtoStreamObjectWriter> ow_; + std::unique_ptr<ProtoStreamObjectWriter> ow_; // The type_url_ that this Any represents. string type_url_; @@ -292,14 +292,14 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter { ProtoStreamObjectWriter* ow_; // A writer for Any objects, handles all Any-related nonsense. - google::protobuf::scoped_ptr<AnyWriter> any_; + std::unique_ptr<AnyWriter> any_; // The type of this element, see enum for permissible types. ItemType item_type_; // Set of map keys already seen for the type_. Used to validate incoming // messages so no map key appears more than once. - google::protobuf::scoped_ptr<hash_set<string> > map_keys_; + std::unique_ptr<hash_set<string> > map_keys_; // Conveys whether this Item is a placeholder or not. Placeholder items are // pushed to stack to account for special types. @@ -392,7 +392,7 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter { const google::protobuf::Type& master_type_; // The current element, variable for internal state processing. - google::protobuf::scoped_ptr<Item> current_; + std::unique_ptr<Item> current_; // Reference to the options that control this class's behavior. const ProtoStreamObjectWriter::Options options_; diff --git a/src/google/protobuf/util/internal/protostream_objectwriter_test.cc b/src/google/protobuf/util/internal/protostream_objectwriter_test.cc index 87d35b08..9c50e7dd 100644 --- a/src/google/protobuf/util/internal/protostream_objectwriter_test.cc +++ b/src/google/protobuf/util/internal/protostream_objectwriter_test.cc @@ -146,7 +146,7 @@ class BaseProtoStreamObjectWriterTest void CheckOutput(const Message& expected, int expected_length) { size_t nbytes; - google::protobuf::scoped_array<char> buffer(output_->GetBuffer(&nbytes)); + std::unique_ptr<char[]> buffer(output_->GetBuffer(&nbytes)); if (expected_length >= 0) { EXPECT_EQ(expected_length, nbytes); } @@ -154,7 +154,7 @@ class BaseProtoStreamObjectWriterTest std::stringbuf str_buf(str, std::ios_base::in); std::istream istream(&str_buf); - google::protobuf::scoped_ptr<Message> message(expected.New()); + std::unique_ptr<Message> message(expected.New()); message->ParsePartialFromIstream(&istream); if (!MessageDifferencer::Equivalent(expected, *message)) { @@ -170,8 +170,8 @@ class BaseProtoStreamObjectWriterTest testing::TypeInfoTestHelper helper_; MockErrorListener listener_; - google::protobuf::scoped_ptr<GrowingArrayByteSink> output_; - google::protobuf::scoped_ptr<ProtoStreamObjectWriter> ow_; + std::unique_ptr<GrowingArrayByteSink> output_; + std::unique_ptr<ProtoStreamObjectWriter> ow_; ProtoStreamObjectWriter::Options options_; }; @@ -1679,6 +1679,22 @@ TEST_P(ProtoStreamObjectWriterMapTest, RepeatedMapKeyTest) { ->EndObject(); } +TEST_P(ProtoStreamObjectWriterMapTest, AnyInMap) { + MapIn mm; + google::protobuf::DoubleValue d; + d.set_value(40.2); + (*mm.mutable_map_any())["foo"].PackFrom(d); + ow_->StartObject("") + ->StartObject("map_any") + ->StartObject("foo") + ->RenderString("@type", "type.googleapis.com/google.protobuf.DoubleValue") + ->RenderDouble("value", 40.2) + ->EndObject() + ->EndObject() + ->EndObject(); + CheckOutput(mm); +} + class ProtoStreamObjectWriterAnyTest : public BaseProtoStreamObjectWriterTest { protected: ProtoStreamObjectWriterAnyTest() { diff --git a/src/google/protobuf/util/internal/structured_objectwriter.h b/src/google/protobuf/util/internal/structured_objectwriter.h index 3f065d6b..8e63222b 100644 --- a/src/google/protobuf/util/internal/structured_objectwriter.h +++ b/src/google/protobuf/util/internal/structured_objectwriter.h @@ -32,9 +32,6 @@ #define GOOGLE_PROTOBUF_UTIL_CONVERTER_STRUCTURED_OBJECTWRITER_H__ #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <google/protobuf/stubs/casts.h> #include <google/protobuf/stubs/common.h> @@ -80,7 +77,7 @@ class LIBPROTOBUF_EXPORT StructuredObjectWriter : public ObjectWriter { } // Returns true if this element is the root. - bool is_root() const { return parent_ == NULL; } + bool is_root() const { return parent_ == nullptr; } // Returns the number of hops from this element to the root element. int level() const { return level_; } @@ -91,10 +88,10 @@ class LIBPROTOBUF_EXPORT StructuredObjectWriter : public ObjectWriter { private: // Pointer to the parent Element. - google::protobuf::scoped_ptr<BaseElement> parent_; + std::unique_ptr<BaseElement> parent_; // Number of hops to the root Element. - // The root Element has NULL parent_ and a level_ of 0. + // The root Element has nullptr parent_ and a level_ of 0. const int level_; GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(BaseElement); diff --git a/src/google/protobuf/util/internal/testdata/books.proto b/src/google/protobuf/util/internal/testdata/books.proto index 869271f4..5e08a291 100644 --- a/src/google/protobuf/util/internal/testdata/books.proto +++ b/src/google/protobuf/util/internal/testdata/books.proto @@ -65,9 +65,13 @@ message Book { KIDS = 2; ACTION_AND_ADVENTURE = 3; arts_and_photography = 4; + I18N_Tech = 5; } optional Type type = 11; + // Useful for testing JSON snake/camel-case conversions. + optional string snake_field = 12; + extensions 200 to 499; } diff --git a/src/google/protobuf/util/internal/testdata/maps.proto b/src/google/protobuf/util/internal/testdata/maps.proto index 0f381b32..765254ea 100644 --- a/src/google/protobuf/util/internal/testdata/maps.proto +++ b/src/google/protobuf/util/internal/testdata/maps.proto @@ -32,6 +32,8 @@ syntax = "proto3"; package google.protobuf.testing; +import "google/protobuf/any.proto"; + // Top-level test cases proto used by MarshallingTest. See description // at the top of the class MarshallingTest for details on how to write // test cases. @@ -103,6 +105,7 @@ message MapIn { string other = 1; repeated string things = 2; map<string, string> map_input = 3; + map<string, google.protobuf.Any> map_any = 4; } message MapOut { diff --git a/src/google/protobuf/util/internal/type_info.cc b/src/google/protobuf/util/internal/type_info.cc index 85d0d5c9..3847b179 100644 --- a/src/google/protobuf/util/internal/type_info.cc +++ b/src/google/protobuf/util/internal/type_info.cc @@ -69,7 +69,7 @@ class TypeInfoForTypeResolver : public TypeInfo { // cached_types_ map. const string& string_type_url = *string_storage_.insert(type_url.ToString()).first; - google::protobuf::scoped_ptr<google::protobuf::Type> type(new google::protobuf::Type()); + std::unique_ptr<google::protobuf::Type> type(new google::protobuf::Type()); util::Status status = type_resolver_->ResolveMessageType(string_type_url, type.get()); StatusOrType result = @@ -95,7 +95,7 @@ class TypeInfoForTypeResolver : public TypeInfo { // cached_enums_ map. const string& string_type_url = *string_storage_.insert(type_url.ToString()).first; - google::protobuf::scoped_ptr<google::protobuf::Enum> enum_type( + std::unique_ptr<google::protobuf::Enum> enum_type( new google::protobuf::Enum()); util::Status status = type_resolver_->ResolveEnumType(string_type_url, enum_type.get()); diff --git a/src/google/protobuf/util/internal/type_info_test_helper.cc b/src/google/protobuf/util/internal/type_info_test_helper.cc index 737ba9e4..281a7f58 100644 --- a/src/google/protobuf/util/internal/type_info_test_helper.cc +++ b/src/google/protobuf/util/internal/type_info_test_helper.cc @@ -31,9 +31,6 @@ #include <google/protobuf/util/internal/type_info_test_helper.h> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <vector> #include <google/protobuf/stubs/logging.h> diff --git a/src/google/protobuf/util/internal/type_info_test_helper.h b/src/google/protobuf/util/internal/type_info_test_helper.h index 1a196715..5a077e04 100644 --- a/src/google/protobuf/util/internal/type_info_test_helper.h +++ b/src/google/protobuf/util/internal/type_info_test_helper.h @@ -32,9 +32,6 @@ #define GOOGLE_PROTOBUF_UTIL_CONVERTER_TYPE_INFO_TEST_HELPER_H__ #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <vector> #include <google/protobuf/io/coded_stream.h> @@ -86,8 +83,8 @@ class TypeInfoTestHelper { private: TypeInfoSource type_; - google::protobuf::scoped_ptr<TypeInfo> typeinfo_; - google::protobuf::scoped_ptr<TypeResolver> type_resolver_; + std::unique_ptr<TypeInfo> typeinfo_; + std::unique_ptr<TypeResolver> type_resolver_; }; } // namespace testing } // namespace converter diff --git a/src/google/protobuf/util/internal/utility.cc b/src/google/protobuf/util/internal/utility.cc index b1007765..b8d917ce 100644 --- a/src/google/protobuf/util/internal/utility.cc +++ b/src/google/protobuf/util/internal/utility.cc @@ -52,7 +52,7 @@ bool GetBoolOptionOrDefault( const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options, const string& option_name, bool default_value) { const google::protobuf::Option* opt = FindOptionOrNull(options, option_name); - if (opt == NULL) { + if (opt == nullptr) { return default_value; } return GetBoolFromAny(opt->value()); @@ -62,7 +62,7 @@ int64 GetInt64OptionOrDefault( const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options, const string& option_name, int64 default_value) { const google::protobuf::Option* opt = FindOptionOrNull(options, option_name); - if (opt == NULL) { + if (opt == nullptr) { return default_value; } return GetInt64FromAny(opt->value()); @@ -72,7 +72,7 @@ double GetDoubleOptionOrDefault( const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options, const string& option_name, double default_value) { const google::protobuf::Option* opt = FindOptionOrNull(options, option_name); - if (opt == NULL) { + if (opt == nullptr) { return default_value; } return GetDoubleFromAny(opt->value()); @@ -82,7 +82,7 @@ string GetStringOptionOrDefault( const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options, const string& option_name, const string& default_value) { const google::protobuf::Option* opt = FindOptionOrNull(options, option_name); - if (opt == NULL) { + if (opt == nullptr) { return default_value; } return GetStringFromAny(opt->value()); @@ -144,12 +144,12 @@ const google::protobuf::Option* FindOptionOrNull( return &opt; } } - return NULL; + return nullptr; } const google::protobuf::Field* FindFieldInTypeOrNull( const google::protobuf::Type* type, StringPiece field_name) { - if (type != NULL) { + if (type != nullptr) { for (int i = 0; i < type->fields_size(); ++i) { const google::protobuf::Field& field = type->fields(i); if (field.name() == field_name) { @@ -157,12 +157,12 @@ const google::protobuf::Field* FindFieldInTypeOrNull( } } } - return NULL; + return nullptr; } const google::protobuf::Field* FindJsonFieldInTypeOrNull( const google::protobuf::Type* type, StringPiece json_name) { - if (type != NULL) { + if (type != nullptr) { for (int i = 0; i < type->fields_size(); ++i) { const google::protobuf::Field& field = type->fields(i); if (field.json_name() == json_name) { @@ -170,12 +170,12 @@ const google::protobuf::Field* FindJsonFieldInTypeOrNull( } } } - return NULL; + return nullptr; } const google::protobuf::Field* FindFieldInTypeByNumberOrNull( const google::protobuf::Type* type, int32 number) { - if (type != NULL) { + if (type != nullptr) { for (int i = 0; i < type->fields_size(); ++i) { const google::protobuf::Field& field = type->fields(i); if (field.number() == number) { @@ -183,12 +183,12 @@ const google::protobuf::Field* FindFieldInTypeByNumberOrNull( } } } - return NULL; + return nullptr; } const google::protobuf::EnumValue* FindEnumValueByNameOrNull( const google::protobuf::Enum* enum_type, StringPiece enum_name) { - if (enum_type != NULL) { + if (enum_type != nullptr) { for (int i = 0; i < enum_type->enumvalue_size(); ++i) { const google::protobuf::EnumValue& enum_value = enum_type->enumvalue(i); if (enum_value.name() == enum_name) { @@ -196,12 +196,12 @@ const google::protobuf::EnumValue* FindEnumValueByNameOrNull( } } } - return NULL; + return nullptr; } const google::protobuf::EnumValue* FindEnumValueByNumberOrNull( const google::protobuf::Enum* enum_type, int32 value) { - if (enum_type != NULL) { + if (enum_type != nullptr) { for (int i = 0; i < enum_type->enumvalue_size(); ++i) { const google::protobuf::EnumValue& enum_value = enum_type->enumvalue(i); if (enum_value.number() == value) { @@ -209,12 +209,12 @@ const google::protobuf::EnumValue* FindEnumValueByNumberOrNull( } } } - return NULL; + return nullptr; } const google::protobuf::EnumValue* FindEnumValueByNameWithoutUnderscoreOrNull( const google::protobuf::Enum* enum_type, StringPiece enum_name) { - if (enum_type != NULL) { + if (enum_type != nullptr) { for (int i = 0; i < enum_type->enumvalue_size(); ++i) { const google::protobuf::EnumValue& enum_value = enum_type->enumvalue(i); string enum_name_without_underscore = enum_value.name(); @@ -235,7 +235,14 @@ const google::protobuf::EnumValue* FindEnumValueByNameWithoutUnderscoreOrNull( } } } - return NULL; + return nullptr; +} + +string EnumValueNameToLowerCamelCase(const StringPiece input) { + string input_string(input); + std::transform(input_string.begin(), input_string.end(), input_string.begin(), + ::tolower); + return ToCamelCase(input_string); } string ToCamelCase(const StringPiece input) { @@ -398,6 +405,13 @@ bool SafeStrToFloat(StringPiece str, float* value) { return true; } +bool StringStartsWith(StringPiece text, StringPiece prefix) { + return text.starts_with(prefix); +} + +bool StringEndsWith(StringPiece text, StringPiece suffix) { + return text.ends_with(suffix); +} } // namespace converter } // namespace util } // namespace protobuf diff --git a/src/google/protobuf/util/internal/utility.h b/src/google/protobuf/util/internal/utility.h index 667e660c..d8e06a97 100644 --- a/src/google/protobuf/util/internal/utility.h +++ b/src/google/protobuf/util/internal/utility.h @@ -32,9 +32,6 @@ #define GOOGLE_PROTOBUF_UTIL_CONVERTER_UTILITY_H__ #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <string> #include <utility> @@ -121,13 +118,13 @@ LIBPROTOBUF_EXPORT const StringPiece GetTypeWithoutUrl(StringPiece type_url); LIBPROTOBUF_EXPORT const string GetFullTypeWithUrl(StringPiece simple_type); // Finds and returns option identified by name and option_name within the -// provided map. Returns NULL if none found. +// provided map. Returns nullptr if none found. const google::protobuf::Option* FindOptionOrNull( const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options, const string& option_name); // Finds and returns the field identified by field_name in the passed tech Type -// object. Returns NULL if none found. +// object. Returns nullptr if none found. const google::protobuf::Field* FindFieldInTypeOrNull( const google::protobuf::Type* type, StringPiece field_name); @@ -141,17 +138,17 @@ const google::protobuf::Field* FindFieldInTypeByNumberOrNull( const google::protobuf::Type* type, int32 number); // Finds and returns the EnumValue identified by enum_name in the passed tech -// Enum object. Returns NULL if none found. +// Enum object. Returns nullptr if none found. const google::protobuf::EnumValue* FindEnumValueByNameOrNull( const google::protobuf::Enum* enum_type, StringPiece enum_name); // Finds and returns the EnumValue identified by value in the passed tech -// Enum object. Returns NULL if none found. +// Enum object. Returns nullptr if none found. const google::protobuf::EnumValue* FindEnumValueByNumberOrNull( const google::protobuf::Enum* enum_type, int32 value); // Finds and returns the EnumValue identified by enum_name without underscore in -// the passed tech Enum object. Returns NULL if none found. +// the passed tech Enum object. Returns nullptr if none found. // For Ex. if enum_name is ACTIONANDADVENTURE it can get accepted if // EnumValue's name is action_and_adventure or ACTION_AND_ADVENTURE. const google::protobuf::EnumValue* FindEnumValueByNameWithoutUnderscoreOrNull( @@ -160,6 +157,9 @@ const google::protobuf::EnumValue* FindEnumValueByNameWithoutUnderscoreOrNull( // Converts input to camel-case and returns it. LIBPROTOBUF_EXPORT string ToCamelCase(const StringPiece input); +// Converts enum name string to camel-case and returns it. +string EnumValueNameToLowerCamelCase(const StringPiece input); + // Converts input to snake_case and returns it. LIBPROTOBUF_EXPORT string ToSnakeCase(StringPiece input); @@ -200,6 +200,12 @@ inline string ValueAsString(double value) { // Converts a string to float. Unlike safe_strtof, conversion will fail if the // value fits into double but not float (e.g., DBL_MAX). LIBPROTOBUF_EXPORT bool SafeStrToFloat(StringPiece str, float* value); + +// Returns whether a StringPiece begins with the provided prefix. +bool StringStartsWith(StringPiece text, StringPiece prefix); + +// Returns whether a StringPiece ends with the provided suffix. +bool StringEndsWith(StringPiece text, StringPiece suffix); } // namespace converter } // namespace util } // namespace protobuf 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 25e78a65..9ad073d8 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); @@ -125,22 +127,23 @@ class StatusErrorListener : public converter::ErrorListener { virtual void InvalidName(const converter::LocationTrackerInterface& loc, StringPiece unknown_name, StringPiece message) { status_ = util::Status(util::error::INVALID_ARGUMENT, - loc.ToString() + ": " + message.ToString()); + loc.ToString() + ": invalid name " + + string(unknown_name) + ": " + string(message)); } virtual void InvalidValue(const converter::LocationTrackerInterface& loc, StringPiece type_name, StringPiece value) { status_ = util::Status(util::error::INVALID_ARGUMENT, - loc.ToString() + ": invalid value " + value.ToString() + - " for type " + type_name.ToString()); + loc.ToString() + ": invalid value " + string(value) + + " for type " + string(type_name)); } virtual void MissingField(const converter::LocationTrackerInterface& loc, StringPiece missing_name) { status_ = util::Status( util::error::INVALID_ARGUMENT, - loc.ToString() + ": missing field " + missing_name.ToString()); + loc.ToString() + ": missing field " + string(missing_name)); } private: diff --git a/src/google/protobuf/util/json_util_test.cc b/src/google/protobuf/util/json_util_test.cc index 5b714bb1..a2a84b57 100644 --- a/src/google/protobuf/util/json_util_test.cc +++ b/src/google/protobuf/util/json_util_test.cc @@ -34,13 +34,13 @@ #include <string> #include <google/protobuf/io/zero_copy_stream.h> +#include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/descriptor_database.h> #include <google/protobuf/dynamic_message.h> #include <google/protobuf/util/internal/testdata/maps.pb.h> #include <google/protobuf/util/json_format_proto3.pb.h> #include <google/protobuf/util/type_resolver.h> #include <google/protobuf/util/type_resolver_util.h> -#include <google/protobuf/io/zero_copy_stream_impl.h> #include <gtest/gtest.h> namespace google { @@ -48,12 +48,13 @@ namespace protobuf { namespace util { namespace { +using google::protobuf::testing::MapIn; using proto3::FOO; using proto3::BAR; using proto3::TestMessage; using proto3::TestMap; using proto3::TestOneof; -using google::protobuf::testing::MapIn; +using proto3::TestEnumValue; static const char kTypeUrlPrefix[] = "type.googleapis.com"; @@ -82,7 +83,7 @@ class JsonUtilTest : public ::testing::Test { return FromJson(json, message, JsonParseOptions()); } - google::protobuf::scoped_ptr<TypeResolver> resolver_; + std::unique_ptr<TypeResolver> resolver_; }; TEST_F(JsonUtilTest, TestWhitespaces) { @@ -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. @@ -260,7 +284,7 @@ TEST_F(JsonUtilTest, ParsePrimitiveMapIn) { JsonPrintOptions print_options; print_options.always_print_primitive_fields = true; JsonParseOptions parse_options; - EXPECT_EQ("{\"other\":\"\",\"things\":[],\"mapInput\":{}}", + EXPECT_EQ("{\"other\":\"\",\"things\":[],\"mapInput\":{},\"mapAny\":{}}", ToJson(message, print_options)); MapIn other; ASSERT_TRUE(FromJson(ToJson(message, print_options), &other, parse_options)); @@ -313,7 +337,7 @@ TEST_F(JsonUtilTest, TestDynamicMessage) { DescriptorPool pool(&database); // A dynamic version of the test proto. DynamicMessageFactory factory; - google::protobuf::scoped_ptr<Message> message(factory.GetPrototype( + std::unique_ptr<Message> message(factory.GetPrototype( pool.FindMessageTypeByName("proto3.TestMessage"))->New()); EXPECT_TRUE(FromJson(input, message.get())); @@ -333,6 +357,64 @@ TEST_F(JsonUtilTest, TestDynamicMessage) { EXPECT_EQ(ToJson(generated, options), ToJson(*message, options)); } +TEST_F(JsonUtilTest, TestParsingUnknownEnumsAs0) { + TestMessage m; + { + JsonParseOptions options; + ASSERT_FALSE(options.ignore_unknown_fields); + string input = + "{\n" + " \"enum_value\":\"UNKNOWN_VALUE\"\n" + "}"; + m.set_enum_value(proto3::BAR); + EXPECT_FALSE(FromJson(input, &m, options)); + ASSERT_EQ(proto3::BAR, m.enum_value()); // Keep previous value + + options.ignore_unknown_fields = true; + EXPECT_TRUE(FromJson(input, &m, options)); + EXPECT_EQ(0, m.enum_value()); // Unknown enum value must be decoded as 0 + } + // Integer values are read as usual + { + JsonParseOptions options; + string input = + "{\n" + " \"enum_value\":12345\n" + "}"; + m.set_enum_value(proto3::BAR); + EXPECT_TRUE(FromJson(input, &m, options)); + ASSERT_EQ(12345, m.enum_value()); + + options.ignore_unknown_fields = true; + EXPECT_TRUE(FromJson(input, &m, options)); + EXPECT_EQ(12345, m.enum_value()); + } + + // Trying to pass an object as an enum field value is always treated as an error + { + JsonParseOptions options; + string input = + "{\n" + " \"enum_value\":{}\n" + "}"; + options.ignore_unknown_fields = true; + EXPECT_FALSE(FromJson(input, &m, options)); + options.ignore_unknown_fields = false; + EXPECT_FALSE(FromJson(input, &m, options)); + } + // Trying to pass an array as an enum field value is always treated as an error + { + JsonParseOptions options; + string input = + "{\n" + " \"enum_value\":[]\n" + "}"; + EXPECT_FALSE(FromJson(input, &m, options)); + options.ignore_unknown_fields = true; + EXPECT_FALSE(FromJson(input, &m, options)); + } +} + typedef std::pair<char*, int> Segment; // A ZeroCopyOutputStream that writes to multiple buffers. class SegmentedZeroCopyOutputStream : public io::ZeroCopyOutputStream { @@ -459,26 +541,22 @@ TEST(ZeroCopyStreamByteSinkTest, TestAllInputOutputPatterns) { } TEST_F(JsonUtilTest, TestWrongJsonInput) { - using namespace google::protobuf; const char json[] = "{\"unknown_field\":\"some_value\"}"; io::ArrayInputStream input_stream(json, strlen(json)); char proto_buffer[10000]; io::ArrayOutputStream output_stream(proto_buffer, sizeof(proto_buffer)); - std::string message_type = "type.googleapis.com/proto3.TestMessage"; + std::string message_type = "type.googleapis.com/proto3.TestMessage"; TypeResolver* resolver = NewTypeResolverForDescriptorPool( - "type.googleapis.com", - DescriptorPool::generated_pool()); - - util::Status result_status = util::JsonToBinaryStream(resolver, - message_type, - &input_stream, - &output_stream); - + "type.googleapis.com", DescriptorPool::generated_pool()); + + auto result_status = util::JsonToBinaryStream( + resolver, message_type, &input_stream, &output_stream); + delete resolver; EXPECT_FALSE(result_status.ok()); - EXPECT_EQ(result_status.error_code(), - google::protobuf::util::error::INVALID_ARGUMENT); + EXPECT_EQ(result_status.error_code(), + util::error::INVALID_ARGUMENT); } } // namespace diff --git a/src/google/protobuf/util/message_differencer.cc b/src/google/protobuf/util/message_differencer.cc index c32e941c..9842f64c 100644 --- a/src/google/protobuf/util/message_differencer.cc +++ b/src/google/protobuf/util/message_differencer.cc @@ -40,9 +40,6 @@ #include <algorithm> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <utility> #include <google/protobuf/stubs/callback.h> @@ -490,8 +487,8 @@ bool MessageDifferencer::Compare( } // Expand google.protobuf.Any payload if possible. if (descriptor1->full_name() == internal::kAnyFullTypeName) { - google::protobuf::scoped_ptr<Message> data1; - google::protobuf::scoped_ptr<Message> data2; + std::unique_ptr<Message> data1; + std::unique_ptr<Message> data2; if (UnpackAny(message1, &data1) && UnpackAny(message2, &data2)) { // Avoid DFATAL for different descriptors in google.protobuf.Any payloads. if (data1->GetDescriptor() != data2->GetDescriptor()) { @@ -1068,7 +1065,7 @@ struct UnknownFieldOrdering { } // namespace bool MessageDifferencer::UnpackAny(const Message& any, - google::protobuf::scoped_ptr<Message>* data) { + std::unique_ptr<Message>* data) { const Reflection* reflection = any.GetReflection(); const FieldDescriptor* type_url_field; const FieldDescriptor* value_field; @@ -1341,7 +1338,7 @@ class MaximumMatcher { int count1_; int count2_; - google::protobuf::scoped_ptr<NodeMatchCallback> match_callback_; + std::unique_ptr<NodeMatchCallback> match_callback_; std::map<std::pair<int, int>, bool> cached_match_results_; std::vector<int>* match_list1_; std::vector<int>* match_list2_; @@ -1459,11 +1456,27 @@ bool MessageDifferencer::MatchRepeatedFieldIndices( if (match_count != count1 && reporter_ == NULL) return false; success = success && (match_count == count1); } else { - for (int i = 0; i < count1; ++i) { + int start_offset = 0; + // If the two repeated fields are treated as sets, optimize for the case + // where both start with same items stored in the same order. + if (IsTreatedAsSet(repeated_field)) { + start_offset = std::min(count1, count2); + for (int i = 0; i < count1 && i < count2; i++) { + if (IsMatch(repeated_field, key_comparator, &message1, &message2, + parent_fields, i, i)) { + match_list1->at(i) = i; + match_list2->at(i) = i; + } else { + start_offset = i; + break; + } + } + } + for (int i = start_offset; i < count1; ++i) { // Indicates any matched elements for this repeated field. bool match = false; - for (int j = 0; j < count2; j++) { + for (int j = start_offset; j < count2; j++) { if (match_list2->at(j) != -1) continue; match = IsMatch(repeated_field, key_comparator, diff --git a/src/google/protobuf/util/message_differencer.h b/src/google/protobuf/util/message_differencer.h index 11d6cc03..bbcf8498 100644 --- a/src/google/protobuf/util/message_differencer.h +++ b/src/google/protobuf/util/message_differencer.h @@ -175,10 +175,8 @@ class LIBPROTOBUF_EXPORT MessageDifferencer { // If "field" is a repeated field which is being treated as a map or // a set (see TreatAsMap() and TreatAsSet(), below), new_index indicates - // the index the position to which the element has moved. This only - // applies to ReportMoved() and (in the case of TreatAsMap()) - // ReportModified(). In all other cases, "new_index" will have the same - // value as "index". + // the index the position to which the element has moved. If the element + // has not moved, "new_index" will have the same value as "index". int new_index; // For unknown fields, these are the pointers to the UnknownFieldSet @@ -823,7 +821,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer { // If "any" is of type google.protobuf.Any, extract its payload using // DynamicMessageFactory and store in "data". - bool UnpackAny(const Message& any, google::protobuf::scoped_ptr<Message>* data); + bool UnpackAny(const Message& any, std::unique_ptr<Message>* data); // Checks if index is equal to new_index in all the specific fields. static bool CheckPathChanged(const std::vector<SpecificField>& parent_fields); @@ -864,7 +862,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer { string* output_string_; - google::protobuf::scoped_ptr<DynamicMessageFactory> dynamic_message_factory_; + std::unique_ptr<DynamicMessageFactory> dynamic_message_factory_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageDifferencer); }; diff --git a/src/google/protobuf/util/message_differencer_unittest.cc b/src/google/protobuf/util/message_differencer_unittest.cc index 75cffd9f..a263d983 100755 --- a/src/google/protobuf/util/message_differencer_unittest.cc +++ b/src/google/protobuf/util/message_differencer_unittest.cc @@ -127,6 +127,27 @@ TEST(MessageDifferencerTest, RepeatedFieldInequalityTest) { EXPECT_FALSE(util::MessageDifferencer::Equals(msg1, msg2)); } +TEST(MessageDifferencerTest, RepeatedFieldSetOptimizationTest) { + util::MessageDifferencer differencer; + protobuf_unittest::TestDiffMessage msg1; + protobuf_unittest::TestDiffMessage msg2; + protobuf_unittest::TestDiffMessage::Item* item1 = msg1.add_item(); + protobuf_unittest::TestDiffMessage::Item* item2 = msg2.add_item(); + differencer.TreatAsSet(item1->GetDescriptor()->FindFieldByName("ra")); + differencer.TreatAsSet(item2->GetDescriptor()->FindFieldByName("ra")); + for (int i = 0; i < 1000; i++) { + item1->add_ra(i); + item2->add_ra(i); + } + EXPECT_TRUE(differencer.Compare(msg1, msg2)); + item2->add_ra(1001); + EXPECT_FALSE(differencer.Compare(msg1, msg2)); + item1->add_ra(1001); + EXPECT_TRUE(differencer.Compare(msg1, msg2)); + item1->add_ra(1002); + EXPECT_FALSE(differencer.Compare(msg1, msg2)); +} + TEST(MessageDifferencerTest, MapFieldEqualityTest) { // Create the testing protos unittest::TestMap msg1; diff --git a/src/google/protobuf/util/package_info.h b/src/google/protobuf/util/package_info.h index e37e6dc0..96019203 100644 --- a/src/google/protobuf/util/package_info.h +++ b/src/google/protobuf/util/package_info.h @@ -38,7 +38,7 @@ namespace protobuf { // Utility classes. // -// This package contains various utilities for message comprasion, JSON +// This package contains various utilities for message comparison, JSON // conversion, well known types, etc. namespace util {} diff --git a/src/google/protobuf/util/time_util.cc b/src/google/protobuf/util/time_util.cc index 46a6f5a8..d4912837 100644 --- a/src/google/protobuf/util/time_util.cc +++ b/src/google/protobuf/util/time_util.cc @@ -30,13 +30,14 @@ #include <google/protobuf/util/time_util.h> -#include <google/protobuf/stubs/time.h> #include <google/protobuf/stubs/int128.h> -#include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/stringprintf.h> +#include <google/protobuf/stubs/strutil.h> +#include <google/protobuf/stubs/time.h> #include <google/protobuf/duration.pb.h> #include <google/protobuf/timestamp.pb.h> + namespace google { namespace protobuf { namespace util { diff --git a/src/google/protobuf/util/type_resolver_util.cc b/src/google/protobuf/util/type_resolver_util.cc index febaa41f..a69ed58c 100644 --- a/src/google/protobuf/util/type_resolver_util.cc +++ b/src/google/protobuf/util/type_resolver_util.cc @@ -95,11 +95,6 @@ class DescriptorPoolTypeResolver : public TypeResolver { type->Clear(); type->set_name(descriptor->full_name()); for (int i = 0; i < descriptor->field_count(); ++i) { - const FieldDescriptor* field = descriptor->field(i); - if (field->type() == FieldDescriptor::TYPE_GROUP) { - // Group fields cannot be represented with Type. We discard them. - continue; - } ConvertFieldDescriptor(descriptor->field(i), type->add_fields()); } for (int i = 0; i < descriptor->oneof_decl_count(); ++i) { @@ -141,7 +136,8 @@ class DescriptorPoolTypeResolver : public TypeResolver { if (descriptor->has_default_value()) { field->set_default_value(DefaultValueAsString(descriptor)); } - if (descriptor->type() == FieldDescriptor::TYPE_MESSAGE) { + if (descriptor->type() == FieldDescriptor::TYPE_MESSAGE || + descriptor->type() == FieldDescriptor::TYPE_GROUP) { field->set_type_url(GetTypeUrl(descriptor->message_type())); } else if (descriptor->type() == FieldDescriptor::TYPE_ENUM) { field->set_type_url(GetTypeUrl(descriptor->enum_type())); diff --git a/src/google/protobuf/util/type_resolver_util_test.cc b/src/google/protobuf/util/type_resolver_util_test.cc index 8a0bf652..9dea17ae 100644 --- a/src/google/protobuf/util/type_resolver_util_test.cc +++ b/src/google/protobuf/util/type_resolver_util_test.cc @@ -32,9 +32,6 @@ #include <limits> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <string> #include <vector> @@ -153,7 +150,7 @@ class DescriptorPoolTypeResolverTest : public testing::Test { } protected: - google::protobuf::scoped_ptr<TypeResolver> resolver_; + std::unique_ptr<TypeResolver> resolver_; }; TEST_F(DescriptorPoolTypeResolverTest, TestAllTypes) { @@ -193,6 +190,13 @@ TEST_F(DescriptorPoolTypeResolverTest, TestAllTypes) { Field::TYPE_BYTES, "optional_bytes", 15)); EXPECT_TRUE(HasField(type, Field::CARDINALITY_OPTIONAL, + Field::TYPE_GROUP, "optionalgroup", 16)); + + EXPECT_TRUE(CheckFieldTypeUrl( + type, "optionalgroup", + GetTypeUrl<protobuf_unittest::TestAllTypes::OptionalGroup>())); + + EXPECT_TRUE(HasField(type, Field::CARDINALITY_OPTIONAL, Field::TYPE_MESSAGE, "optional_nested_message", 18)); EXPECT_TRUE(HasField(type, Field::CARDINALITY_OPTIONAL, Field::TYPE_MESSAGE, "optional_foreign_message", 19)); @@ -249,6 +253,13 @@ TEST_F(DescriptorPoolTypeResolverTest, TestAllTypes) { Field::TYPE_BYTES, "repeated_bytes", 45)); EXPECT_TRUE(HasField(type, Field::CARDINALITY_REPEATED, + Field::TYPE_GROUP, "repeatedgroup", 46)); + + EXPECT_TRUE(CheckFieldTypeUrl( + type, "repeatedgroup", + GetTypeUrl<protobuf_unittest::TestAllTypes::RepeatedGroup>())); + + EXPECT_TRUE(HasField(type, Field::CARDINALITY_REPEATED, Field::TYPE_MESSAGE, "repeated_nested_message", 48)); EXPECT_TRUE(HasField(type, Field::CARDINALITY_REPEATED, Field::TYPE_MESSAGE, "repeated_foreign_message", 49)); @@ -271,13 +282,6 @@ TEST_F(DescriptorPoolTypeResolverTest, TestAllTypes) { EXPECT_TRUE(CheckFieldTypeUrl( type, "repeated_foreign_enum", GetTypeUrl("protobuf_unittest.ForeignEnum"))); - - // Groups are discarded when converting to Type. - const Descriptor* descriptor = protobuf_unittest::TestAllTypes::descriptor(); - EXPECT_TRUE(descriptor->FindFieldByName("optionalgroup") != NULL); - EXPECT_TRUE(descriptor->FindFieldByName("repeatedgroup") != NULL); - ASSERT_FALSE(HasField(type, "optionalgroup")); - ASSERT_FALSE(HasField(type, "repeatedgroup")); } TEST_F(DescriptorPoolTypeResolverTest, TestPackedField) { diff --git a/src/google/protobuf/wire_format.cc b/src/google/protobuf/wire_format.cc index 01704c94..3fdf84ed 100644 --- a/src/google/protobuf/wire_format.cc +++ b/src/google/protobuf/wire_format.cc @@ -41,16 +41,15 @@ #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/stringprintf.h> -#include <google/protobuf/descriptor.h> -#include <google/protobuf/dynamic_message.h> -#include <google/protobuf/map_field.h> -#include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> +#include <google/protobuf/descriptor.h> +#include <google/protobuf/dynamic_message.h> +#include <google/protobuf/map_field.h> #include <google/protobuf/unknown_field_set.h> - +#include <google/protobuf/wire_format_lite_inl.h> namespace google { diff --git a/src/google/protobuf/wire_format_lite.h b/src/google/protobuf/wire_format_lite.h index 76275518..77eaa9a6 100644 --- a/src/google/protobuf/wire_format_lite.h +++ b/src/google/protobuf/wire_format_lite.h @@ -346,32 +346,27 @@ class LIBPROTOBUF_EXPORT WireFormatLite { Operation op, const char* field_name); + template <typename MessageType> static inline bool ReadGroup(int field_number, io::CodedInputStream* input, - MessageLite* value); + MessageType* value); + + template <typename MessageType> static inline bool ReadMessage(io::CodedInputStream* input, - MessageLite* value); + MessageType* value); - // Like above, but de-virtualize the call to MergePartialFromCodedStream(). - // The pointer must point at an instance of MessageType, *not* a subclass (or - // the subclass must not override MergePartialFromCodedStream()). + // Do not use. template <typename MessageType> static inline bool ReadGroupNoVirtual(int field_number, io::CodedInputStream* input, - MessageType* value); - template<typename MessageType> - static inline bool ReadMessageNoVirtual(io::CodedInputStream* input, - MessageType* value); - - // The same, but do not modify input's recursion depth. This is useful - // when reading a bunch of groups or messages in a loop, because then the - // recursion depth can be incremented before the loop and decremented after. - template<typename MessageType> - static inline bool ReadGroupNoVirtualNoRecursionDepth( - int field_number, io::CodedInputStream* input, MessageType* value); + MessageType* value) { + return ReadGroup(field_number, input, value); + } template<typename MessageType> - static inline bool ReadMessageNoVirtualNoRecursionDepth( - io::CodedInputStream* input, MessageType* value); + static inline bool ReadMessageNoVirtual(io::CodedInputStream* input, + MessageType* value) { + return ReadMessage(input, value); + } // Write a tag. The Write*() functions typically include the tag, so // normally there's no need to call this unless using the Write*NoTag() @@ -612,12 +607,14 @@ class LIBPROTOBUF_EXPORT WireFormatLite { // of serialization, the "ToArray" variants may be invoked. But they don't // have a CodedOutputStream available, so they get an additional parameter // telling them whether to serialize deterministically. + template<typename MessageType> INL static uint8* InternalWriteGroupToArray(int field_number, - const MessageLite& value, + const MessageType& value, bool deterministic, uint8* target); + template<typename MessageType> INL static uint8* InternalWriteMessageToArray(int field_number, - const MessageLite& value, + const MessageType& value, bool deterministic, uint8* target); @@ -694,8 +691,10 @@ class LIBPROTOBUF_EXPORT WireFormatLite { static inline size_t StringSize(const string& value); static inline size_t BytesSize (const string& value); - static inline size_t GroupSize (const MessageLite& value); - static inline size_t MessageSize(const MessageLite& value); + template<typename MessageType> + static inline size_t GroupSize (const MessageType& value); + template<typename MessageType> + static inline size_t MessageSize(const MessageType& value); // Like above, but de-virtualize the call to ByteSize(). The // pointer must point at an instance of MessageType, *not* a subclass (or diff --git a/src/google/protobuf/wire_format_lite_inl.h b/src/google/protobuf/wire_format_lite_inl.h index 82fb62ae..6cd2c2fb 100644 --- a/src/google/protobuf/wire_format_lite_inl.h +++ b/src/google/protobuf/wire_format_lite_inl.h @@ -426,48 +426,12 @@ bool WireFormatLite::ReadPackedPrimitiveNoInline(io::CodedInputStream* input, } -inline bool WireFormatLite::ReadGroup(int field_number, - io::CodedInputStream* input, - MessageLite* value) { - if (!input->IncrementRecursionDepth()) return false; - if (!value->MergePartialFromCodedStream(input)) return false; - input->DecrementRecursionDepth(); - // Make sure the last thing read was an end tag for this group. - if (!input->LastTagWas(MakeTag(field_number, WIRETYPE_END_GROUP))) { - return false; - } - return true; -} -inline bool WireFormatLite::ReadMessage(io::CodedInputStream* input, - MessageLite* value) { - int length; - if (!input->ReadVarintSizeAsInt(&length)) return false; - std::pair<io::CodedInputStream::Limit, int> p = - input->IncrementRecursionDepthAndPushLimit(length); - if (p.second < 0 || !value->MergePartialFromCodedStream(input)) return false; - // Make sure that parsing stopped when the limit was hit, not at an endgroup - // tag. - return input->DecrementRecursionDepthAndPopLimit(p.first); -} - -// We name the template parameter something long and extremely unlikely to occur -// elsewhere because a *qualified* member access expression designed to avoid -// virtual dispatch, C++03 [basic.lookup.classref] 3.4.5/4 requires that the -// name of the qualifying class to be looked up both in the context of the full -// expression (finding the template parameter) and in the context of the object -// whose member we are accessing. This could potentially find a nested type -// within that object. The standard goes on to require these names to refer to -// the same entity, which this collision would violate. The lack of a safe way -// to avoid this collision appears to be a defect in the standard, but until it -// is corrected, we choose the name to avoid accidental collisions. -template<typename MessageType_WorkAroundCppLookupDefect> -inline bool WireFormatLite::ReadGroupNoVirtual( +template<typename MessageType> +inline bool WireFormatLite::ReadGroup( int field_number, io::CodedInputStream* input, - MessageType_WorkAroundCppLookupDefect* value) { + MessageType* value) { if (!input->IncrementRecursionDepth()) return false; - if (!value-> - MessageType_WorkAroundCppLookupDefect::MergePartialFromCodedStream(input)) - return false; + if (!value->MergePartialFromCodedStream(input)) return false; input->UnsafeDecrementRecursionDepth(); // Make sure the last thing read was an end tag for this group. if (!input->LastTagWas(MakeTag(field_number, WIRETYPE_END_GROUP))) { @@ -475,41 +439,19 @@ inline bool WireFormatLite::ReadGroupNoVirtual( } return true; } -template<typename MessageType_WorkAroundCppLookupDefect> -inline bool WireFormatLite::ReadGroupNoVirtualNoRecursionDepth( - int field_number, io::CodedInputStream* input, - MessageType_WorkAroundCppLookupDefect* value) { - return value->MessageType_WorkAroundCppLookupDefect:: - MergePartialFromCodedStream(input) && - input->LastTagWas(MakeTag(field_number, WIRETYPE_END_GROUP)); -} -template<typename MessageType_WorkAroundCppLookupDefect> -inline bool WireFormatLite::ReadMessageNoVirtual( - io::CodedInputStream* input, MessageType_WorkAroundCppLookupDefect* value) { +template<typename MessageType> +inline bool WireFormatLite::ReadMessage( + io::CodedInputStream* input, MessageType* value) { int length; if (!input->ReadVarintSizeAsInt(&length)) return false; std::pair<io::CodedInputStream::Limit, int> p = input->IncrementRecursionDepthAndPushLimit(length); - if (p.second < 0 || !value-> - MessageType_WorkAroundCppLookupDefect::MergePartialFromCodedStream(input)) - return false; + if (p.second < 0 || !value->MergePartialFromCodedStream(input)) return false; // Make sure that parsing stopped when the limit was hit, not at an endgroup // tag. return input->DecrementRecursionDepthAndPopLimit(p.first); } -template<typename MessageType_WorkAroundCppLookupDefect> -inline bool WireFormatLite::ReadMessageNoVirtualNoRecursionDepth( - io::CodedInputStream* input, MessageType_WorkAroundCppLookupDefect* value) { - io::CodedInputStream::Limit old_limit = input->ReadLengthAndPushLimit(); - if (!value-> - MessageType_WorkAroundCppLookupDefect::MergePartialFromCodedStream(input)) - return false; - // Make sure that parsing stopped when the limit was hit, not at an endgroup - // tag. - return input->CheckEntireMessageConsumedAndPopLimit(old_limit); -} - // =================================================================== inline void WireFormatLite::WriteTag(int field_number, WireType type, @@ -941,15 +883,17 @@ inline uint8* WireFormatLite::WriteBytesToArray(int field_number, } +template<typename MessageType> inline uint8* WireFormatLite::InternalWriteGroupToArray( - int field_number, const MessageLite& value, bool deterministic, + int field_number, const MessageType& value, bool deterministic, uint8* target) { target = WriteTagToArray(field_number, WIRETYPE_START_GROUP, target); target = value.InternalSerializeWithCachedSizesToArray(deterministic, target); return WriteTagToArray(field_number, WIRETYPE_END_GROUP, target); } +template<typename MessageType> inline uint8* WireFormatLite::InternalWriteMessageToArray( - int field_number, const MessageLite& value, bool deterministic, + int field_number, const MessageType& value, bool deterministic, uint8* target) { target = WriteTagToArray(field_number, WIRETYPE_LENGTH_DELIMITED, target); target = io::CodedOutputStream::WriteVarint32ToArray( @@ -1013,10 +957,12 @@ inline size_t WireFormatLite::BytesSize(const string& value) { } -inline size_t WireFormatLite::GroupSize(const MessageLite& value) { +template<typename MessageType> +inline size_t WireFormatLite::GroupSize(const MessageType& value) { return value.ByteSizeLong(); } -inline size_t WireFormatLite::MessageSize(const MessageLite& value) { +template<typename MessageType> +inline size_t WireFormatLite::MessageSize(const MessageType& value) { return LengthDelimitedSize(value.ByteSizeLong()); } diff --git a/src/google/protobuf/wrappers.pb.cc b/src/google/protobuf/wrappers.pb.cc index 34c6fed1..386be61d 100644 --- a/src/google/protobuf/wrappers.pb.cc +++ b/src/google/protobuf/wrappers.pb.cc @@ -7,7 +7,6 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> -#include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> @@ -19,6 +18,7 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + namespace google { namespace protobuf { class DoubleValueDefaultTypeInternal { @@ -69,14 +69,9 @@ class BytesValueDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2fwrappers_2eproto { -void InitDefaultsDoubleValueImpl() { +static void InitDefaultsDoubleValue() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_DoubleValue_default_instance_; new (ptr) ::google::protobuf::DoubleValue(); @@ -85,19 +80,12 @@ void InitDefaultsDoubleValueImpl() { ::google::protobuf::DoubleValue::InitAsDefaultInstance(); } -void InitDefaultsDoubleValue() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDoubleValueImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_DoubleValue = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDoubleValue}, {}}; -void InitDefaultsFloatValueImpl() { +static void InitDefaultsFloatValue() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_FloatValue_default_instance_; new (ptr) ::google::protobuf::FloatValue(); @@ -106,19 +94,12 @@ void InitDefaultsFloatValueImpl() { ::google::protobuf::FloatValue::InitAsDefaultInstance(); } -void InitDefaultsFloatValue() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFloatValueImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_FloatValue = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsFloatValue}, {}}; -void InitDefaultsInt64ValueImpl() { +static void InitDefaultsInt64Value() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_Int64Value_default_instance_; new (ptr) ::google::protobuf::Int64Value(); @@ -127,19 +108,12 @@ void InitDefaultsInt64ValueImpl() { ::google::protobuf::Int64Value::InitAsDefaultInstance(); } -void InitDefaultsInt64Value() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsInt64ValueImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Int64Value = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsInt64Value}, {}}; -void InitDefaultsUInt64ValueImpl() { +static void InitDefaultsUInt64Value() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_UInt64Value_default_instance_; new (ptr) ::google::protobuf::UInt64Value(); @@ -148,19 +122,12 @@ void InitDefaultsUInt64ValueImpl() { ::google::protobuf::UInt64Value::InitAsDefaultInstance(); } -void InitDefaultsUInt64Value() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsUInt64ValueImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_UInt64Value = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsUInt64Value}, {}}; -void InitDefaultsInt32ValueImpl() { +static void InitDefaultsInt32Value() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_Int32Value_default_instance_; new (ptr) ::google::protobuf::Int32Value(); @@ -169,19 +136,12 @@ void InitDefaultsInt32ValueImpl() { ::google::protobuf::Int32Value::InitAsDefaultInstance(); } -void InitDefaultsInt32Value() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsInt32ValueImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Int32Value = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsInt32Value}, {}}; -void InitDefaultsUInt32ValueImpl() { +static void InitDefaultsUInt32Value() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_UInt32Value_default_instance_; new (ptr) ::google::protobuf::UInt32Value(); @@ -190,19 +150,12 @@ void InitDefaultsUInt32ValueImpl() { ::google::protobuf::UInt32Value::InitAsDefaultInstance(); } -void InitDefaultsUInt32Value() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsUInt32ValueImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_UInt32Value = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsUInt32Value}, {}}; -void InitDefaultsBoolValueImpl() { +static void InitDefaultsBoolValue() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_BoolValue_default_instance_; new (ptr) ::google::protobuf::BoolValue(); @@ -211,19 +164,12 @@ void InitDefaultsBoolValueImpl() { ::google::protobuf::BoolValue::InitAsDefaultInstance(); } -void InitDefaultsBoolValue() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsBoolValueImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_BoolValue = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsBoolValue}, {}}; -void InitDefaultsStringValueImpl() { +static void InitDefaultsStringValue() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_StringValue_default_instance_; new (ptr) ::google::protobuf::StringValue(); @@ -232,19 +178,12 @@ void InitDefaultsStringValueImpl() { ::google::protobuf::StringValue::InitAsDefaultInstance(); } -void InitDefaultsStringValue() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsStringValueImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_StringValue = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsStringValue}, {}}; -void InitDefaultsBytesValueImpl() { +static void InitDefaultsBytesValue() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_BytesValue_default_instance_; new (ptr) ::google::protobuf::BytesValue(); @@ -253,9 +192,19 @@ void InitDefaultsBytesValueImpl() { ::google::protobuf::BytesValue::InitAsDefaultInstance(); } -void InitDefaultsBytesValue() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsBytesValueImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_BytesValue = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsBytesValue}, {}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_DoubleValue.base); + ::google::protobuf::internal::InitSCC(&scc_info_FloatValue.base); + ::google::protobuf::internal::InitSCC(&scc_info_Int64Value.base); + ::google::protobuf::internal::InitSCC(&scc_info_UInt64Value.base); + ::google::protobuf::internal::InitSCC(&scc_info_Int32Value.base); + ::google::protobuf::internal::InitSCC(&scc_info_UInt32Value.base); + ::google::protobuf::internal::InitSCC(&scc_info_BoolValue.base); + ::google::protobuf::internal::InitSCC(&scc_info_StringValue.base); + ::google::protobuf::internal::InitSCC(&scc_info_BytesValue.base); } ::google::protobuf::Metadata file_level_metadata[9]; @@ -340,17 +289,16 @@ static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_BytesValue_default_instance_), }; -void protobuf_AssignDescriptors() { +static void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/wrappers.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/wrappers.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } -void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); +static void protobuf_AssignDescriptorsOnce() { + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -359,7 +307,7 @@ void protobuf_RegisterTypes(const ::std::string&) { ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 9); } -void AddDescriptorsImpl() { +static void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n\036google/protobuf/wrappers.proto\022\017google" @@ -382,8 +330,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -405,24 +353,22 @@ const int DoubleValue::kValueFieldNumber; DoubleValue::DoubleValue() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsDoubleValue(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_DoubleValue.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.DoubleValue) } DoubleValue::DoubleValue(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsDoubleValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_DoubleValue.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.DoubleValue) } DoubleValue::DoubleValue(const DoubleValue& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); value_ = from.value_; // @@protoc_insertion_point(copy_constructor:google.protobuf.DoubleValue) @@ -430,7 +376,6 @@ DoubleValue::DoubleValue(const DoubleValue& from) void DoubleValue::SharedCtor() { value_ = 0; - _cached_size_ = 0; } DoubleValue::~DoubleValue() { @@ -449,9 +394,7 @@ void DoubleValue::ArenaDtor(void* object) { void DoubleValue::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void DoubleValue::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* DoubleValue::descriptor() { ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce(); @@ -459,7 +402,7 @@ const ::google::protobuf::Descriptor* DoubleValue::descriptor() { } const DoubleValue& DoubleValue::default_instance() { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsDoubleValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_DoubleValue.base); return *internal_default_instance(); } @@ -480,7 +423,7 @@ bool DoubleValue::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.DoubleValue) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -571,9 +514,7 @@ size_t DoubleValue::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -645,7 +586,6 @@ void DoubleValue::InternalSwap(DoubleValue* other) { using std::swap; swap(value_, other->value_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata DoubleValue::GetMetadata() const { @@ -664,24 +604,22 @@ const int FloatValue::kValueFieldNumber; FloatValue::FloatValue() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsFloatValue(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_FloatValue.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FloatValue) } FloatValue::FloatValue(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsFloatValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_FloatValue.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.FloatValue) } FloatValue::FloatValue(const FloatValue& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); value_ = from.value_; // @@protoc_insertion_point(copy_constructor:google.protobuf.FloatValue) @@ -689,7 +627,6 @@ FloatValue::FloatValue(const FloatValue& from) void FloatValue::SharedCtor() { value_ = 0; - _cached_size_ = 0; } FloatValue::~FloatValue() { @@ -708,9 +645,7 @@ void FloatValue::ArenaDtor(void* object) { void FloatValue::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void FloatValue::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* FloatValue::descriptor() { ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce(); @@ -718,7 +653,7 @@ const ::google::protobuf::Descriptor* FloatValue::descriptor() { } const FloatValue& FloatValue::default_instance() { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsFloatValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_FloatValue.base); return *internal_default_instance(); } @@ -739,7 +674,7 @@ bool FloatValue::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FloatValue) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -830,9 +765,7 @@ size_t FloatValue::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -904,7 +837,6 @@ void FloatValue::InternalSwap(FloatValue* other) { using std::swap; swap(value_, other->value_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata FloatValue::GetMetadata() const { @@ -923,24 +855,22 @@ const int Int64Value::kValueFieldNumber; Int64Value::Int64Value() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt64Value(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_Int64Value.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Int64Value) } Int64Value::Int64Value(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt64Value(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_Int64Value.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Int64Value) } Int64Value::Int64Value(const Int64Value& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); value_ = from.value_; // @@protoc_insertion_point(copy_constructor:google.protobuf.Int64Value) @@ -948,7 +878,6 @@ Int64Value::Int64Value(const Int64Value& from) void Int64Value::SharedCtor() { value_ = GOOGLE_LONGLONG(0); - _cached_size_ = 0; } Int64Value::~Int64Value() { @@ -967,9 +896,7 @@ void Int64Value::ArenaDtor(void* object) { void Int64Value::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Int64Value::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Int64Value::descriptor() { ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce(); @@ -977,7 +904,7 @@ const ::google::protobuf::Descriptor* Int64Value::descriptor() { } const Int64Value& Int64Value::default_instance() { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt64Value(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_Int64Value.base); return *internal_default_instance(); } @@ -998,7 +925,7 @@ bool Int64Value::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Int64Value) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1091,9 +1018,7 @@ size_t Int64Value::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1165,7 +1090,6 @@ void Int64Value::InternalSwap(Int64Value* other) { using std::swap; swap(value_, other->value_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Int64Value::GetMetadata() const { @@ -1184,24 +1108,22 @@ const int UInt64Value::kValueFieldNumber; UInt64Value::UInt64Value() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt64Value(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_UInt64Value.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.UInt64Value) } UInt64Value::UInt64Value(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt64Value(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_UInt64Value.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.UInt64Value) } UInt64Value::UInt64Value(const UInt64Value& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); value_ = from.value_; // @@protoc_insertion_point(copy_constructor:google.protobuf.UInt64Value) @@ -1209,7 +1131,6 @@ UInt64Value::UInt64Value(const UInt64Value& from) void UInt64Value::SharedCtor() { value_ = GOOGLE_ULONGLONG(0); - _cached_size_ = 0; } UInt64Value::~UInt64Value() { @@ -1228,9 +1149,7 @@ void UInt64Value::ArenaDtor(void* object) { void UInt64Value::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void UInt64Value::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* UInt64Value::descriptor() { ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1238,7 +1157,7 @@ const ::google::protobuf::Descriptor* UInt64Value::descriptor() { } const UInt64Value& UInt64Value::default_instance() { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt64Value(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_UInt64Value.base); return *internal_default_instance(); } @@ -1259,7 +1178,7 @@ bool UInt64Value::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.UInt64Value) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1352,9 +1271,7 @@ size_t UInt64Value::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1426,7 +1343,6 @@ void UInt64Value::InternalSwap(UInt64Value* other) { using std::swap; swap(value_, other->value_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata UInt64Value::GetMetadata() const { @@ -1445,24 +1361,22 @@ const int Int32Value::kValueFieldNumber; Int32Value::Int32Value() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt32Value(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_Int32Value.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Int32Value) } Int32Value::Int32Value(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt32Value(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_Int32Value.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Int32Value) } Int32Value::Int32Value(const Int32Value& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); value_ = from.value_; // @@protoc_insertion_point(copy_constructor:google.protobuf.Int32Value) @@ -1470,7 +1384,6 @@ Int32Value::Int32Value(const Int32Value& from) void Int32Value::SharedCtor() { value_ = 0; - _cached_size_ = 0; } Int32Value::~Int32Value() { @@ -1489,9 +1402,7 @@ void Int32Value::ArenaDtor(void* object) { void Int32Value::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Int32Value::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Int32Value::descriptor() { ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1499,7 +1410,7 @@ const ::google::protobuf::Descriptor* Int32Value::descriptor() { } const Int32Value& Int32Value::default_instance() { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt32Value(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_Int32Value.base); return *internal_default_instance(); } @@ -1520,7 +1431,7 @@ bool Int32Value::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Int32Value) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1613,9 +1524,7 @@ size_t Int32Value::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1687,7 +1596,6 @@ void Int32Value::InternalSwap(Int32Value* other) { using std::swap; swap(value_, other->value_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Int32Value::GetMetadata() const { @@ -1706,24 +1614,22 @@ const int UInt32Value::kValueFieldNumber; UInt32Value::UInt32Value() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt32Value(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_UInt32Value.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.UInt32Value) } UInt32Value::UInt32Value(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt32Value(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_UInt32Value.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.UInt32Value) } UInt32Value::UInt32Value(const UInt32Value& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); value_ = from.value_; // @@protoc_insertion_point(copy_constructor:google.protobuf.UInt32Value) @@ -1731,7 +1637,6 @@ UInt32Value::UInt32Value(const UInt32Value& from) void UInt32Value::SharedCtor() { value_ = 0u; - _cached_size_ = 0; } UInt32Value::~UInt32Value() { @@ -1750,9 +1655,7 @@ void UInt32Value::ArenaDtor(void* object) { void UInt32Value::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void UInt32Value::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* UInt32Value::descriptor() { ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1760,7 +1663,7 @@ const ::google::protobuf::Descriptor* UInt32Value::descriptor() { } const UInt32Value& UInt32Value::default_instance() { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt32Value(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_UInt32Value.base); return *internal_default_instance(); } @@ -1781,7 +1684,7 @@ bool UInt32Value::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.UInt32Value) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1874,9 +1777,7 @@ size_t UInt32Value::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1948,7 +1849,6 @@ void UInt32Value::InternalSwap(UInt32Value* other) { using std::swap; swap(value_, other->value_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata UInt32Value::GetMetadata() const { @@ -1967,24 +1867,22 @@ const int BoolValue::kValueFieldNumber; BoolValue::BoolValue() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBoolValue(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_BoolValue.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.BoolValue) } BoolValue::BoolValue(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBoolValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_BoolValue.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.BoolValue) } BoolValue::BoolValue(const BoolValue& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); value_ = from.value_; // @@protoc_insertion_point(copy_constructor:google.protobuf.BoolValue) @@ -1992,7 +1890,6 @@ BoolValue::BoolValue(const BoolValue& from) void BoolValue::SharedCtor() { value_ = false; - _cached_size_ = 0; } BoolValue::~BoolValue() { @@ -2011,9 +1908,7 @@ void BoolValue::ArenaDtor(void* object) { void BoolValue::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void BoolValue::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* BoolValue::descriptor() { ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce(); @@ -2021,7 +1916,7 @@ const ::google::protobuf::Descriptor* BoolValue::descriptor() { } const BoolValue& BoolValue::default_instance() { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBoolValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_BoolValue.base); return *internal_default_instance(); } @@ -2042,7 +1937,7 @@ bool BoolValue::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.BoolValue) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -2133,9 +2028,7 @@ size_t BoolValue::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -2207,7 +2100,6 @@ void BoolValue::InternalSwap(BoolValue* other) { using std::swap; swap(value_, other->value_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata BoolValue::GetMetadata() const { @@ -2226,24 +2118,22 @@ const int StringValue::kValueFieldNumber; StringValue::StringValue() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsStringValue(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_StringValue.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.StringValue) } StringValue::StringValue(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsStringValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_StringValue.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.StringValue) } StringValue::StringValue(const StringValue& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.value().size() > 0) { @@ -2255,7 +2145,6 @@ StringValue::StringValue(const StringValue& from) void StringValue::SharedCtor() { value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - _cached_size_ = 0; } StringValue::~StringValue() { @@ -2275,9 +2164,7 @@ void StringValue::ArenaDtor(void* object) { void StringValue::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void StringValue::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* StringValue::descriptor() { ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce(); @@ -2285,7 +2172,7 @@ const ::google::protobuf::Descriptor* StringValue::descriptor() { } const StringValue& StringValue::default_instance() { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsStringValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_StringValue.base); return *internal_default_instance(); } @@ -2306,7 +2193,7 @@ bool StringValue::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.StringValue) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -2412,9 +2299,7 @@ size_t StringValue::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -2484,9 +2369,9 @@ void StringValue::UnsafeArenaSwap(StringValue* other) { } void StringValue::InternalSwap(StringValue* other) { using std::swap; - value_.Swap(&other->value_); + value_.Swap(&other->value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata StringValue::GetMetadata() const { @@ -2505,24 +2390,22 @@ const int BytesValue::kValueFieldNumber; BytesValue::BytesValue() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBytesValue(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_BytesValue.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.BytesValue) } BytesValue::BytesValue(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBytesValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_BytesValue.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.BytesValue) } BytesValue::BytesValue(const BytesValue& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.value().size() > 0) { @@ -2534,7 +2417,6 @@ BytesValue::BytesValue(const BytesValue& from) void BytesValue::SharedCtor() { value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - _cached_size_ = 0; } BytesValue::~BytesValue() { @@ -2554,9 +2436,7 @@ void BytesValue::ArenaDtor(void* object) { void BytesValue::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void BytesValue::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* BytesValue::descriptor() { ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce(); @@ -2564,7 +2444,7 @@ const ::google::protobuf::Descriptor* BytesValue::descriptor() { } const BytesValue& BytesValue::default_instance() { - ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBytesValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_BytesValue.base); return *internal_default_instance(); } @@ -2585,7 +2465,7 @@ bool BytesValue::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.BytesValue) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -2679,9 +2559,7 @@ size_t BytesValue::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -2751,9 +2629,9 @@ void BytesValue::UnsafeArenaSwap(BytesValue* other) { } void BytesValue::InternalSwap(BytesValue* other) { using std::swap; - value_.Swap(&other->value_); + value_.Swap(&other->value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata BytesValue::GetMetadata() const { @@ -2767,31 +2645,31 @@ void BytesValue::InternalSwap(BytesValue* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DoubleValue* Arena::CreateMessage< ::google::protobuf::DoubleValue >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DoubleValue* Arena::CreateMaybeMessage< ::google::protobuf::DoubleValue >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::DoubleValue >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FloatValue* Arena::CreateMessage< ::google::protobuf::FloatValue >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FloatValue* Arena::CreateMaybeMessage< ::google::protobuf::FloatValue >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::FloatValue >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Int64Value* Arena::CreateMessage< ::google::protobuf::Int64Value >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Int64Value* Arena::CreateMaybeMessage< ::google::protobuf::Int64Value >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Int64Value >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UInt64Value* Arena::CreateMessage< ::google::protobuf::UInt64Value >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UInt64Value* Arena::CreateMaybeMessage< ::google::protobuf::UInt64Value >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::UInt64Value >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Int32Value* Arena::CreateMessage< ::google::protobuf::Int32Value >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Int32Value* Arena::CreateMaybeMessage< ::google::protobuf::Int32Value >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Int32Value >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UInt32Value* Arena::CreateMessage< ::google::protobuf::UInt32Value >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UInt32Value* Arena::CreateMaybeMessage< ::google::protobuf::UInt32Value >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::UInt32Value >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::BoolValue* Arena::CreateMessage< ::google::protobuf::BoolValue >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::BoolValue* Arena::CreateMaybeMessage< ::google::protobuf::BoolValue >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::BoolValue >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::StringValue* Arena::CreateMessage< ::google::protobuf::StringValue >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::StringValue* Arena::CreateMaybeMessage< ::google::protobuf::StringValue >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::StringValue >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::BytesValue* Arena::CreateMessage< ::google::protobuf::BytesValue >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::BytesValue* Arena::CreateMaybeMessage< ::google::protobuf::BytesValue >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::BytesValue >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/wrappers.pb.h b/src/google/protobuf/wrappers.pb.h index 876bf39b..9f51a062 100644 --- a/src/google/protobuf/wrappers.pb.h +++ b/src/google/protobuf/wrappers.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/wrappers.proto -#ifndef PROTOBUF_google_2fprotobuf_2fwrappers_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2fwrappers_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fwrappers_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2fwrappers_2eproto #include <string> @@ -24,12 +24,14 @@ #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> +#include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fwrappers_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2fwrappers_2eproto { // Internal implementation detail -- do not use these members. @@ -42,35 +44,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsDoubleValueImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsDoubleValue(); -void LIBPROTOBUF_EXPORT InitDefaultsFloatValueImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsFloatValue(); -void LIBPROTOBUF_EXPORT InitDefaultsInt64ValueImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsInt64Value(); -void LIBPROTOBUF_EXPORT InitDefaultsUInt64ValueImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsUInt64Value(); -void LIBPROTOBUF_EXPORT InitDefaultsInt32ValueImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsInt32Value(); -void LIBPROTOBUF_EXPORT InitDefaultsUInt32ValueImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsUInt32Value(); -void LIBPROTOBUF_EXPORT InitDefaultsBoolValueImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsBoolValue(); -void LIBPROTOBUF_EXPORT InitDefaultsStringValueImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsStringValue(); -void LIBPROTOBUF_EXPORT InitDefaultsBytesValueImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsBytesValue(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsDoubleValue(); - InitDefaultsFloatValue(); - InitDefaultsInt64Value(); - InitDefaultsUInt64Value(); - InitDefaultsInt32Value(); - InitDefaultsUInt32Value(); - InitDefaultsBoolValue(); - InitDefaultsStringValue(); - InitDefaultsBytesValue(); -} } // namespace protobuf_google_2fprotobuf_2fwrappers_2eproto namespace google { namespace protobuf { @@ -105,15 +78,15 @@ LIBPROTOBUF_EXPORT extern UInt64ValueDefaultTypeInternal _UInt64Value_default_in } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::BoolValue* Arena::CreateMessage< ::google::protobuf::BoolValue>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::BytesValue* Arena::CreateMessage< ::google::protobuf::BytesValue>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::DoubleValue* Arena::CreateMessage< ::google::protobuf::DoubleValue>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FloatValue* Arena::CreateMessage< ::google::protobuf::FloatValue>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Int32Value* Arena::CreateMessage< ::google::protobuf::Int32Value>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Int64Value* Arena::CreateMessage< ::google::protobuf::Int64Value>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::StringValue* Arena::CreateMessage< ::google::protobuf::StringValue>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::UInt32Value* Arena::CreateMessage< ::google::protobuf::UInt32Value>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::UInt64Value* Arena::CreateMessage< ::google::protobuf::UInt64Value>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::BoolValue* Arena::CreateMaybeMessage<::google::protobuf::BoolValue>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::BytesValue* Arena::CreateMaybeMessage<::google::protobuf::BytesValue>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::DoubleValue* Arena::CreateMaybeMessage<::google::protobuf::DoubleValue>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::FloatValue* Arena::CreateMaybeMessage<::google::protobuf::FloatValue>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Int32Value* Arena::CreateMaybeMessage<::google::protobuf::Int32Value>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Int64Value* Arena::CreateMaybeMessage<::google::protobuf::Int64Value>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::StringValue* Arena::CreateMaybeMessage<::google::protobuf::StringValue>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::UInt32Value* Arena::CreateMaybeMessage<::google::protobuf::UInt32Value>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::UInt64Value* Arena::CreateMaybeMessage<::google::protobuf::UInt64Value>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -147,10 +120,10 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -161,7 +134,7 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p return reinterpret_cast<const DoubleValue*>( &_DoubleValue_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void UnsafeArenaSwap(DoubleValue* other); @@ -172,32 +145,33 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p // implements Message ---------------------------------------------- - inline DoubleValue* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<DoubleValue>(NULL); + inline DoubleValue* New() const final { + return CreateMaybeMessage<DoubleValue>(NULL); } - DoubleValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<DoubleValue>(arena); + DoubleValue* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<DoubleValue>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const DoubleValue& from); void MergeFrom(const DoubleValue& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(DoubleValue* other); protected: explicit DoubleValue(::google::protobuf::Arena* arena); @@ -213,7 +187,7 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -233,9 +207,8 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; double value_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsDoubleValueImpl(); }; // ------------------------------------------------------------------- @@ -265,10 +238,10 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -279,7 +252,7 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr return reinterpret_cast<const FloatValue*>( &_FloatValue_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 1; void UnsafeArenaSwap(FloatValue* other); @@ -290,32 +263,33 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr // implements Message ---------------------------------------------- - inline FloatValue* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<FloatValue>(NULL); + inline FloatValue* New() const final { + return CreateMaybeMessage<FloatValue>(NULL); } - FloatValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<FloatValue>(arena); + FloatValue* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<FloatValue>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const FloatValue& from); void MergeFrom(const FloatValue& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(FloatValue* other); protected: explicit FloatValue(::google::protobuf::Arena* arena); @@ -331,7 +305,7 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -351,9 +325,8 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; float value_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsFloatValueImpl(); }; // ------------------------------------------------------------------- @@ -383,10 +356,10 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -397,7 +370,7 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr return reinterpret_cast<const Int64Value*>( &_Int64Value_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 2; void UnsafeArenaSwap(Int64Value* other); @@ -408,32 +381,33 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr // implements Message ---------------------------------------------- - inline Int64Value* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Int64Value>(NULL); + inline Int64Value* New() const final { + return CreateMaybeMessage<Int64Value>(NULL); } - Int64Value* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Int64Value>(arena); + Int64Value* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<Int64Value>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Int64Value& from); void MergeFrom(const Int64Value& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Int64Value* other); protected: explicit Int64Value(::google::protobuf::Arena* arena); @@ -449,7 +423,7 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -469,9 +443,8 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::int64 value_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt64ValueImpl(); }; // ------------------------------------------------------------------- @@ -501,10 +474,10 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -515,7 +488,7 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p return reinterpret_cast<const UInt64Value*>( &_UInt64Value_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 3; void UnsafeArenaSwap(UInt64Value* other); @@ -526,32 +499,33 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p // implements Message ---------------------------------------------- - inline UInt64Value* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<UInt64Value>(NULL); + inline UInt64Value* New() const final { + return CreateMaybeMessage<UInt64Value>(NULL); } - UInt64Value* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<UInt64Value>(arena); + UInt64Value* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<UInt64Value>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const UInt64Value& from); void MergeFrom(const UInt64Value& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(UInt64Value* other); protected: explicit UInt64Value(::google::protobuf::Arena* arena); @@ -567,7 +541,7 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -587,9 +561,8 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::uint64 value_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt64ValueImpl(); }; // ------------------------------------------------------------------- @@ -619,10 +592,10 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -633,7 +606,7 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr return reinterpret_cast<const Int32Value*>( &_Int32Value_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 4; void UnsafeArenaSwap(Int32Value* other); @@ -644,32 +617,33 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr // implements Message ---------------------------------------------- - inline Int32Value* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Int32Value>(NULL); + inline Int32Value* New() const final { + return CreateMaybeMessage<Int32Value>(NULL); } - Int32Value* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<Int32Value>(arena); + Int32Value* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<Int32Value>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Int32Value& from); void MergeFrom(const Int32Value& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Int32Value* other); protected: explicit Int32Value(::google::protobuf::Arena* arena); @@ -685,7 +659,7 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -705,9 +679,8 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::int32 value_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt32ValueImpl(); }; // ------------------------------------------------------------------- @@ -737,10 +710,10 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -751,7 +724,7 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p return reinterpret_cast<const UInt32Value*>( &_UInt32Value_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 5; void UnsafeArenaSwap(UInt32Value* other); @@ -762,32 +735,33 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p // implements Message ---------------------------------------------- - inline UInt32Value* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<UInt32Value>(NULL); + inline UInt32Value* New() const final { + return CreateMaybeMessage<UInt32Value>(NULL); } - UInt32Value* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<UInt32Value>(arena); + UInt32Value* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<UInt32Value>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const UInt32Value& from); void MergeFrom(const UInt32Value& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(UInt32Value* other); protected: explicit UInt32Value(::google::protobuf::Arena* arena); @@ -803,7 +777,7 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -823,9 +797,8 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::uint32 value_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt32ValueImpl(); }; // ------------------------------------------------------------------- @@ -855,10 +828,10 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -869,7 +842,7 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro return reinterpret_cast<const BoolValue*>( &_BoolValue_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 6; void UnsafeArenaSwap(BoolValue* other); @@ -880,32 +853,33 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro // implements Message ---------------------------------------------- - inline BoolValue* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<BoolValue>(NULL); + inline BoolValue* New() const final { + return CreateMaybeMessage<BoolValue>(NULL); } - BoolValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<BoolValue>(arena); + BoolValue* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<BoolValue>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const BoolValue& from); void MergeFrom(const BoolValue& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(BoolValue* other); protected: explicit BoolValue(::google::protobuf::Arena* arena); @@ -921,7 +895,7 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -941,9 +915,8 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; bool value_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBoolValueImpl(); }; // ------------------------------------------------------------------- @@ -973,10 +946,10 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -987,7 +960,7 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p return reinterpret_cast<const StringValue*>( &_StringValue_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 7; void UnsafeArenaSwap(StringValue* other); @@ -998,32 +971,33 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p // implements Message ---------------------------------------------- - inline StringValue* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<StringValue>(NULL); + inline StringValue* New() const final { + return CreateMaybeMessage<StringValue>(NULL); } - StringValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<StringValue>(arena); + StringValue* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<StringValue>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const StringValue& from); void MergeFrom(const StringValue& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(StringValue* other); protected: explicit StringValue(::google::protobuf::Arena* arena); @@ -1039,7 +1013,7 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -1076,9 +1050,8 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::ArenaStringPtr value_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsStringValueImpl(); }; // ------------------------------------------------------------------- @@ -1108,10 +1081,10 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -1122,7 +1095,7 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr return reinterpret_cast<const BytesValue*>( &_BytesValue_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 8; void UnsafeArenaSwap(BytesValue* other); @@ -1133,32 +1106,33 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr // implements Message ---------------------------------------------- - inline BytesValue* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<BytesValue>(NULL); + inline BytesValue* New() const final { + return CreateMaybeMessage<BytesValue>(NULL); } - BytesValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage<BytesValue>(arena); + BytesValue* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage<BytesValue>(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const BytesValue& from); void MergeFrom(const BytesValue& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(BytesValue* other); protected: explicit BytesValue(::google::protobuf::Arena* arena); @@ -1174,7 +1148,7 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -1211,9 +1185,8 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::ArenaStringPtr value_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBytesValueImpl(); }; // =================================================================== @@ -1533,4 +1506,4 @@ inline void BytesValue::unsafe_arena_set_allocated_value( // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2fwrappers_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fwrappers_2eproto |