diff --git a/Makefile.am b/Makefile.am index b7c013bf64..d770b9c00f 100644 --- a/Makefile.am +++ b/Makefile.am @@ -92,6 +92,7 @@ csharp_EXTRA_DIST= \ csharp/src/AddressBook/ListPeople.cs \ csharp/src/AddressBook/Program.cs \ csharp/src/AddressBook/SampleUsage.cs \ + csharp/src/Directory.Build.props \ csharp/src/Google.Protobuf.Benchmarks/BenchmarkDatasetConfig.cs \ csharp/src/Google.Protobuf.Benchmarks/BenchmarkMessage1Proto3.cs \ csharp/src/Google.Protobuf.Benchmarks/Benchmarks.cs \ diff --git a/Protobuf-C++.podspec b/Protobuf-C++.podspec index 68571e14b6..c8a516bb05 100644 --- a/Protobuf-C++.podspec +++ b/Protobuf-C++.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'Protobuf-C++' - s.version = '3.21.1' + s.version = '3.21.2' s.summary = 'Protocol Buffers v3 runtime library for C++.' s.homepage = 'https://github.com/google/protobuf' s.license = 'BSD-3-Clause' diff --git a/cmake/install.cmake b/cmake/install.cmake index 825cb25fc1..2da8170544 100644 --- a/cmake/install.cmake +++ b/cmake/install.cmake @@ -102,47 +102,55 @@ foreach(_file ${nobase_dist_proto_DATA}) endforeach() # Install configuration -set(_cmakedir_desc "Directory relative to CMAKE_INSTALL to install the cmake configuration files") +set(_install_cmakedir_desc "Directory relative to CMAKE_INSTALL to install the cmake configuration files") +set(_build_cmakedir_desc "Directory relative to CMAKE_CURRENT_BINARY_DIR for cmake configuration files") set(_exampledir_desc "Directory relative to CMAKE_INSTALL_DATA to install examples") +set(_protobuf_subdir_desc "Subdirectory in which to install cmake configuration files") if(NOT MSVC) - set(CMAKE_INSTALL_CMAKEDIR "${CMAKE_INSTALL_LIBDIR}/cmake/protobuf" CACHE STRING "${_cmakedir_desc}") + set(protobuf_CMAKE_SUBDIR "cmake/protobuf" CACHE STRING "${_protobuf_subdir_desc}") + set(CMAKE_INSTALL_CMAKEDIR "${CMAKE_INSTALL_LIBDIR}/${protobuf_CMAKE_SUBDIR}" CACHE STRING "${_install_cmakedir_desc}") set(CMAKE_INSTALL_EXAMPLEDIR "${CMAKE_INSTALL_DATADIR}/protobuf/examples" CACHE STRING "${_exampledir_desc}") else() + set(protobuf_CMAKE_SUBDIR "cmake" CACHE STRING "${_protobuf_subdir_desc}") set(CMAKE_INSTALL_CMAKEDIR "cmake" CACHE STRING "${_cmakedir_desc}") set(CMAKE_INSTALL_EXAMPLEDIR "examples" CACHE STRING "${_exampledir_desc}") endif() +set(CMAKE_BUILD_CMAKEDIR "${CMAKE_CURRENT_BINARY_DIR}/${protobuf_CMAKE_SUBDIR}" CACHE STRING "${_build_cmakedir_desc}") +mark_as_advanced(protobuf_CMAKE_SUBDIR) +mark_as_advanced(CMAKE_BUILD_CMAKEDIR) mark_as_advanced(CMAKE_INSTALL_CMAKEDIR) mark_as_advanced(CMAKE_INSTALL_EXAMPLEDIR) configure_file(${protobuf_SOURCE_DIR}/cmake/protobuf-config.cmake.in - ${CMAKE_INSTALL_CMAKEDIR}/protobuf-config.cmake @ONLY) + ${CMAKE_BUILD_CMAKEDIR}/protobuf-config.cmake @ONLY) configure_file(${protobuf_SOURCE_DIR}/cmake/protobuf-config-version.cmake.in - ${CMAKE_INSTALL_CMAKEDIR}/protobuf-config-version.cmake @ONLY) + ${CMAKE_BUILD_CMAKEDIR}/protobuf-config-version.cmake @ONLY) configure_file(${protobuf_SOURCE_DIR}/cmake/protobuf-module.cmake.in - ${CMAKE_INSTALL_CMAKEDIR}/protobuf-module.cmake @ONLY) + ${CMAKE_BUILD_CMAKEDIR}/protobuf-module.cmake @ONLY) configure_file(${protobuf_SOURCE_DIR}/cmake/protobuf-options.cmake - ${CMAKE_INSTALL_CMAKEDIR}/protobuf-options.cmake @ONLY) + ${CMAKE_BUILD_CMAKEDIR}/protobuf-options.cmake @ONLY) # Allows the build directory to be used as a find directory. if (protobuf_BUILD_PROTOC_BINARIES) export(TARGETS libprotobuf-lite libprotobuf libprotoc protoc NAMESPACE protobuf:: - FILE ${CMAKE_INSTALL_CMAKEDIR}/protobuf-targets.cmake + FILE ${CMAKE_BUILD_CMAKEDIR}/protobuf-targets.cmake ) else (protobuf_BUILD_PROTOC_BINARIES) export(TARGETS libprotobuf-lite libprotobuf NAMESPACE protobuf:: - FILE ${CMAKE_INSTALL_CMAKEDIR}/protobuf-targets.cmake + FILE ${CMAKE_BUILD_CMAKEDIR}/protobuf-targets.cmake ) endif (protobuf_BUILD_PROTOC_BINARIES) install(EXPORT protobuf-targets DESTINATION "${CMAKE_INSTALL_CMAKEDIR}" NAMESPACE protobuf:: - COMPONENT protobuf-export) + COMPONENT protobuf-export +) -install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_CMAKEDIR}/ +install(DIRECTORY ${CMAKE_BUILD_CMAKEDIR}/ DESTINATION "${CMAKE_INSTALL_CMAKEDIR}" COMPONENT protobuf-export PATTERN protobuf-targets.cmake EXCLUDE diff --git a/configure.ac b/configure.ac index 55e606478a..c55a6a2c2f 100644 --- a/configure.ac +++ b/configure.ac @@ -17,7 +17,7 @@ AC_PREREQ(2.59) # In the SVN trunk, the version should always be the next anticipated release # version with the "-pre" suffix. (We used to use "-SNAPSHOT" but this pushed # the size of one file name in the dist tarfile over the 99-char limit.) -AC_INIT([Protocol Buffers],[3.21.1],[protobuf@googlegroups.com],[protobuf]) +AC_INIT([Protocol Buffers],[3.21.2],[protobuf@googlegroups.com],[protobuf]) AM_MAINTAINER_MODE([enable]) diff --git a/csharp/src/Google.Protobuf/Google.Protobuf.csproj b/csharp/src/Google.Protobuf/Google.Protobuf.csproj index 5517b0030c..37d86ce043 100644 --- a/csharp/src/Google.Protobuf/Google.Protobuf.csproj +++ b/csharp/src/Google.Protobuf/Google.Protobuf.csproj @@ -5,8 +5,7 @@ Copyright 2015, Google Inc. Google Protocol Buffers 3.21.2 - - 7.2 + 10.0 Google Inc. netstandard1.1;netstandard2.0;net45;net50 true diff --git a/docs/jvm_aot.md b/docs/jvm_aot.md index 304c82961c..d9c1b6be2d 100644 --- a/docs/jvm_aot.md +++ b/docs/jvm_aot.md @@ -1,8 +1,8 @@ -# Ahead Of Time (AOT) compilation for the Java Virtual Machine (JVM)" +# Ahead Of Time (AOT) compilation for the Java Virtual Machine (JVM) Ahead Of Time (AOT) compilation build tools such as those provided by [GraalVM's `native-image`](https://www.graalvm.org/reference-manual/native-image/) can require some configuration when using protobuf. -Protobuf for the JVM uses reflection and some of its target classes are not possible to determine in advance. -Historically, there were good reasons to use reflection based on APIs that were published effectively requiring them, and this situation is unlikely to change. +Protobuf for the JVM uses reflection, and some of its target classes are not possible to determine in advance. +This situation is unlikely to change. [The Lite version of protobuf for the JVM](https://github.com/protocolbuffers/protobuf/blob/main/java/lite.md) avoids reflection and may be better suited for use with AOT compilation tooling. This Lite version was originally targeted for use on Android which has similar AOT compilation @@ -10,9 +10,11 @@ goals as GraalVM's native-image tool. ## GraalVM native-image -This section addresses GraalVM's `native-image` configuration specifically as this AOT compilation tool due to its popularity. The `native-image` tool can be configured -with respect to: the [Java Native Interface](https://en.wikipedia.org/wiki/Java_Native_Interface) (JNI), http proxying, reflection, and other resources. While these -considerations can be manually declared as JSON files, we recommend that a JVM application is exercised along with +The GraalVM `native-image` tool can be configured with options for the +[Java Native Interface](https://www.graalvm.org/22.0/reference-manual/native-image/JNI/) (JNI), +http proxying, reflection, and other resources. While these +configuration options can be manually specified in JSON files, we recommend +that you exercise the application with [the assisted configuration agent](https://www.graalvm.org/reference-manual/native-image/BuildConfiguration/#assisted-configuration-of-native-image-builds). The agent -will generate files that you can then subsequently point at when invoking `native-image`. We recommend that the generated files are retained with a project's source -code. +will generate native-image.properties files that you add to the project's +META-INF/native-image/ directory. The Native Image builder uses configuration options provided in META-INF/native-image/ to construct native-image command line arguments. diff --git a/java/core/src/main/java/com/google/protobuf/GeneratedMessage.java b/java/core/src/main/java/com/google/protobuf/GeneratedMessage.java index de0ee11b7e..26cc5bb759 100644 --- a/java/core/src/main/java/com/google/protobuf/GeneratedMessage.java +++ b/java/core/src/main/java/com/google/protobuf/GeneratedMessage.java @@ -36,7 +36,6 @@ import com.google.protobuf.Descriptors.EnumValueDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.OneofDescriptor; - import java.io.IOException; import java.io.InputStream; import java.io.ObjectStreamException; @@ -51,25 +50,23 @@ import java.util.Map; import java.util.TreeMap; /** - * All generated protocol message classes extend this class. This class - * implements most of the Message and Builder interfaces using Java reflection. - * Users can ignore this class and pretend that generated messages implement - * the Message interface directly. + * All generated protocol message classes extend this class. This class implements most of the + * Message and Builder interfaces using Java reflection. Users can ignore this class and pretend + * that generated messages implement the Message interface directly. * * @author kenton@google.com Kenton Varda */ -public abstract class GeneratedMessage extends AbstractMessage - implements Serializable { +public abstract class GeneratedMessage extends AbstractMessage implements Serializable { private static final long serialVersionUID = 1L; /** - * For testing. Allows a test to disable the optimization that avoids using - * field builders for nested messages until they are requested. By disabling - * this optimization, existing tests can be reused to test the field builders. + * For testing. Allows a test to disable the optimization that avoids using field builders for + * nested messages until they are requested. By disabling this optimization, existing tests can be + * reused to test the field builders. */ protected static boolean alwaysUseFieldBuilders = false; - /** For use by generated code only. */ + /** For use by generated code only. */ protected UnknownFieldSet unknownFields; protected GeneratedMessage() { @@ -82,24 +79,22 @@ public abstract class GeneratedMessage extends AbstractMessage @Override public Parser getParserForType() { - throw new UnsupportedOperationException( - "This is supposed to be overridden by subclasses."); + throw new UnsupportedOperationException("This is supposed to be overridden by subclasses."); } - /** - * For testing. Allows a test to disable the optimization that avoids using - * field builders for nested messages until they are requested. By disabling - * this optimization, existing tests can be reused to test the field builders. - * See {@link RepeatedFieldBuilder} and {@link SingleFieldBuilder}. - */ + /** + * For testing. Allows a test to disable the optimization that avoids using field builders for + * nested messages until they are requested. By disabling this optimization, existing tests can be + * reused to test the field builders. See {@link RepeatedFieldBuilder} and {@link + * SingleFieldBuilder}. + */ static void enableAlwaysUseFieldBuildersForTesting() { alwaysUseFieldBuilders = true; } /** - * Get the FieldAccessorTable for this type. We can't have the message - * class pass this in to the constructor because of bootstrapping trouble - * with DescriptorProtos. + * Get the FieldAccessorTable for this type. We can't have the message class pass this in to the + * constructor because of bootstrapping trouble with DescriptorProtos. */ protected abstract FieldAccessorTable internalGetFieldAccessorTable(); @@ -109,16 +104,14 @@ public abstract class GeneratedMessage extends AbstractMessage } /** - * Internal helper to return a modifiable map containing all the fields. - * The returned Map is modifialbe so that the caller can add additional - * extension fields to implement {@link #getAllFields()}. + * Internal helper to return a modifiable map containing all the fields. The returned Map is + * modifialbe so that the caller can add additional extension fields to implement {@link + * #getAllFields()}. * * @param getBytesForString whether to generate ByteString for string fields */ - private Map getAllFieldsMutable( - boolean getBytesForString) { - final TreeMap result = - new TreeMap(); + private Map getAllFieldsMutable(boolean getBytesForString) { + final TreeMap result = new TreeMap(); final Descriptor descriptor = internalGetFieldAccessorTable().descriptor; final List fields = descriptor.getFields(); @@ -174,8 +167,8 @@ public abstract class GeneratedMessage extends AbstractMessage // Check that embedded messages are initialized. if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { if (field.isRepeated()) { - @SuppressWarnings("unchecked") final - List messageList = (List) getField(field); + @SuppressWarnings("unchecked") + final List messageList = (List) getField(field); for (final Message element : messageList) { if (!element.isInitialized()) { return false; @@ -194,23 +187,19 @@ public abstract class GeneratedMessage extends AbstractMessage @Override public Map getAllFields() { - return Collections.unmodifiableMap( - getAllFieldsMutable(/* getBytesForString = */ false)); + return Collections.unmodifiableMap(getAllFieldsMutable(/* getBytesForString = */ false)); } /** - * Returns a collection of all the fields in this message which are set - * and their corresponding values. A singular ("required" or "optional") - * field is set iff hasField() returns true for that field. A "repeated" - * field is set iff getRepeatedFieldCount() is greater than zero. The - * values are exactly what would be returned by calling - * {@link #getFieldRaw(Descriptors.FieldDescriptor)} for each field. The map - * is guaranteed to be a sorted map, so iterating over it will return fields - * in order by field number. + * Returns a collection of all the fields in this message which are set and their corresponding + * values. A singular ("required" or "optional") field is set iff hasField() returns true for that + * field. A "repeated" field is set iff getRepeatedFieldCount() is greater than zero. The values + * are exactly what would be returned by calling {@link #getFieldRaw(Descriptors.FieldDescriptor)} + * for each field. The map is guaranteed to be a sorted map, so iterating over it will return + * fields in order by field number. */ Map getAllFieldsRaw() { - return Collections.unmodifiableMap( - getAllFieldsMutable(/* getBytesForString = */ true)); + return Collections.unmodifiableMap(getAllFieldsMutable(/* getBytesForString = */ true)); } @Override @@ -234,12 +223,11 @@ public abstract class GeneratedMessage extends AbstractMessage } /** - * Obtains the value of the given field, or the default value if it is - * not set. For primitive fields, the boxed primitive value is returned. - * For enum fields, the EnumValueDescriptor for the value is returned. For - * embedded message fields, the sub-message is returned. For repeated - * fields, a java.util.List is returned. For present string fields, a - * ByteString is returned representing the bytes that the field contains. + * Obtains the value of the given field, or the default value if it is not set. For primitive + * fields, the boxed primitive value is returned. For enum fields, the EnumValueDescriptor for the + * value is returned. For embedded message fields, the sub-message is returned. For repeated + * fields, a java.util.List is returned. For present string fields, a ByteString is returned + * representing the bytes that the field contains. */ Object getFieldRaw(final FieldDescriptor field) { return internalGetFieldAccessorTable().getField(field).getRaw(this); @@ -247,31 +235,30 @@ public abstract class GeneratedMessage extends AbstractMessage @Override public int getRepeatedFieldCount(final FieldDescriptor field) { - return internalGetFieldAccessorTable().getField(field) - .getRepeatedCount(this); + return internalGetFieldAccessorTable().getField(field).getRepeatedCount(this); } @Override public Object getRepeatedField(final FieldDescriptor field, final int index) { - return internalGetFieldAccessorTable().getField(field) - .getRepeated(this, index); + return internalGetFieldAccessorTable().getField(field).getRepeated(this, index); } @Override public UnknownFieldSet getUnknownFields() { - throw new UnsupportedOperationException( - "This is supposed to be overridden by subclasses."); + throw new UnsupportedOperationException("This is supposed to be overridden by subclasses."); } /** * Called by subclasses to parse an unknown field. + * * @return {@code true} unless the tag is an end-group tag. */ protected boolean parseUnknownField( CodedInputStream input, UnknownFieldSet.Builder unknownFields, ExtensionRegistryLite extensionRegistry, - int tag) throws IOException { + int tag) + throws IOException { return unknownFields.mergeFieldFrom(tag, input); } @@ -284,8 +271,8 @@ public abstract class GeneratedMessage extends AbstractMessage } } - protected static M parseWithIOException(Parser parser, InputStream input, - ExtensionRegistryLite extensions) throws IOException { + protected static M parseWithIOException( + Parser parser, InputStream input, ExtensionRegistryLite extensions) throws IOException { try { return parser.parseFrom(input, extensions); } catch (InvalidProtocolBufferException e) { @@ -293,8 +280,8 @@ public abstract class GeneratedMessage extends AbstractMessage } } - protected static M parseWithIOException(Parser parser, - CodedInputStream input) throws IOException { + protected static M parseWithIOException( + Parser parser, CodedInputStream input) throws IOException { try { return parser.parseFrom(input); } catch (InvalidProtocolBufferException e) { @@ -302,8 +289,9 @@ public abstract class GeneratedMessage extends AbstractMessage } } - protected static M parseWithIOException(Parser parser, - CodedInputStream input, ExtensionRegistryLite extensions) throws IOException { + protected static M parseWithIOException( + Parser parser, CodedInputStream input, ExtensionRegistryLite extensions) + throws IOException { try { return parser.parseFrom(input, extensions); } catch (InvalidProtocolBufferException e) { @@ -311,8 +299,8 @@ public abstract class GeneratedMessage extends AbstractMessage } } - protected static M parseDelimitedWithIOException(Parser parser, - InputStream input) throws IOException { + protected static M parseDelimitedWithIOException( + Parser parser, InputStream input) throws IOException { try { return parser.parseDelimitedFrom(input); } catch (InvalidProtocolBufferException e) { @@ -320,8 +308,8 @@ public abstract class GeneratedMessage extends AbstractMessage } } - protected static M parseDelimitedWithIOException(Parser parser, - InputStream input, ExtensionRegistryLite extensions) throws IOException { + protected static M parseDelimitedWithIOException( + Parser parser, InputStream input, ExtensionRegistryLite extensions) throws IOException { try { return parser.parseDelimitedFrom(input, extensions); } catch (InvalidProtocolBufferException e) { @@ -341,46 +329,38 @@ public abstract class GeneratedMessage extends AbstractMessage return size; } - memoizedSize = MessageReflection.getSerializedSize( - this, getAllFieldsRaw()); + memoizedSize = MessageReflection.getSerializedSize(this, getAllFieldsRaw()); return memoizedSize; } - - - /** - * Used by parsing constructors in generated classes. - */ + /** Used by parsing constructors in generated classes. */ protected void makeExtensionsImmutable() { // Noop for messages without extensions. } /** - * TODO(xiaofeng): remove this after b/29368482 is fixed. We need to move this - * interface to AbstractMessage in order to versioning GeneratedMessage but - * this move breaks binary compatibility for AppEngine. After AppEngine is - * fixed we can exclude this from google3. + * TODO(xiaofeng): remove this after b/29368482 is fixed. We need to move this interface to + * AbstractMessage in order to versioning GeneratedMessage but this move breaks binary + * compatibility for AppEngine. After AppEngine is fixed we can exclude this from google3. */ protected interface BuilderParent extends AbstractMessage.BuilderParent {} - /** - * TODO(xiaofeng): remove this together with GeneratedMessage.BuilderParent. - */ + /** TODO(xiaofeng): remove this together with GeneratedMessage.BuilderParent. */ protected abstract Message.Builder newBuilderForType(BuilderParent parent); @Override protected Message.Builder newBuilderForType(final AbstractMessage.BuilderParent parent) { - return newBuilderForType(new BuilderParent() { - @Override - public void markDirty() { - parent.markDirty(); - } - }); + return newBuilderForType( + new BuilderParent() { + @Override + public void markDirty() { + parent.markDirty(); + } + }); } - @SuppressWarnings("unchecked") - public abstract static class Builder > + public abstract static class Builder> extends AbstractMessage.Builder { private BuilderParent builderParent; @@ -391,8 +371,7 @@ public abstract class GeneratedMessage extends AbstractMessage // to dispatch dirty invalidations. See GeneratedMessage.BuilderListener. private boolean isClean; - private UnknownFieldSet unknownFields = - UnknownFieldSet.getDefaultInstance(); + private UnknownFieldSet unknownFields = UnknownFieldSet.getDefaultInstance(); protected Builder() { this(null); @@ -407,9 +386,7 @@ public abstract class GeneratedMessage extends AbstractMessage builderParent = null; } - /** - * Called by the subclass when a message is built. - */ + /** Called by the subclass when a message is built. */ protected void onBuilt() { if (builderParent != null) { markClean(); @@ -417,8 +394,8 @@ public abstract class GeneratedMessage extends AbstractMessage } /** - * Called by the subclass or a builder to notify us that a message was - * built and may be cached and therefore invalidations are needed. + * Called by the subclass or a builder to notify us that a message was built and may be cached + * and therefore invalidations are needed. */ @Override protected void markClean() { @@ -436,15 +413,14 @@ public abstract class GeneratedMessage extends AbstractMessage @Override public BuilderType clone() { - BuilderType builder = - (BuilderType) getDefaultInstanceForType().newBuilderForType(); + BuilderType builder = (BuilderType) getDefaultInstanceForType().newBuilderForType(); builder.mergeFrom(buildPartial()); return builder; } /** - * Called by the initialization and clear code paths to allow subclasses to - * reset any of their builtin fields back to the initial values. + * Called by the initialization and clear code paths to allow subclasses to reset any of their + * builtin fields back to the initial values. */ @Override public BuilderType clear() { @@ -454,9 +430,8 @@ public abstract class GeneratedMessage extends AbstractMessage } /** - * Get the FieldAccessorTable for this type. We can't have the message - * class pass this in to the constructor because of bootstrapping trouble - * with DescriptorProtos. + * Get the FieldAccessorTable for this type. We can't have the message class pass this in to the + * constructor because of bootstrapping trouble with DescriptorProtos. */ protected abstract FieldAccessorTable internalGetFieldAccessorTable(); @@ -472,8 +447,7 @@ public abstract class GeneratedMessage extends AbstractMessage /** Internal helper which returns a mutable map. */ private Map getAllFieldsMutable() { - final TreeMap result = - new TreeMap(); + final TreeMap result = new TreeMap(); final Descriptor descriptor = internalGetFieldAccessorTable().descriptor; final List fields = descriptor.getFields(); @@ -525,8 +499,7 @@ public abstract class GeneratedMessage extends AbstractMessage @Override public Message.Builder getRepeatedFieldBuilder(final FieldDescriptor field, int index) { - return internalGetFieldAccessorTable().getField(field).getRepeatedBuilder( - this, index); + return internalGetFieldAccessorTable().getField(field).getRepeatedBuilder(this, index); } @Override @@ -576,21 +549,18 @@ public abstract class GeneratedMessage extends AbstractMessage @Override public int getRepeatedFieldCount(final FieldDescriptor field) { - return internalGetFieldAccessorTable().getField(field) - .getRepeatedCount(this); + return internalGetFieldAccessorTable().getField(field).getRepeatedCount(this); } @Override public Object getRepeatedField(final FieldDescriptor field, final int index) { - return internalGetFieldAccessorTable().getField(field) - .getRepeated(this, index); + return internalGetFieldAccessorTable().getField(field).getRepeated(this, index); } @Override public BuilderType setRepeatedField( final FieldDescriptor field, final int index, final Object value) { - internalGetFieldAccessorTable().getField(field) - .setRepeated(this, index, value); + internalGetFieldAccessorTable().getField(field).setRepeated(this, index, value); return (BuilderType) this; } @@ -608,12 +578,9 @@ public abstract class GeneratedMessage extends AbstractMessage } @Override - public BuilderType mergeUnknownFields( - final UnknownFieldSet unknownFields) { + public BuilderType mergeUnknownFields(final UnknownFieldSet unknownFields) { this.unknownFields = - UnknownFieldSet.newBuilder(this.unknownFields) - .mergeFrom(unknownFields) - .build(); + UnknownFieldSet.newBuilder(this.unknownFields).mergeFrom(unknownFields).build(); onChanged(); return (BuilderType) this; } @@ -630,16 +597,15 @@ public abstract class GeneratedMessage extends AbstractMessage // Check that embedded messages are initialized. if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { if (field.isRepeated()) { - @SuppressWarnings("unchecked") final - List messageList = (List) getField(field); + @SuppressWarnings("unchecked") + final List messageList = (List) getField(field); for (final Message element : messageList) { if (!element.isInitialized()) { return false; } } } else { - if (hasField(field) && - !((Message) getField(field)).isInitialized()) { + if (hasField(field) && !((Message) getField(field)).isInitialized()) { return false; } } @@ -655,20 +621,21 @@ public abstract class GeneratedMessage extends AbstractMessage /** * Called by subclasses to parse an unknown field. + * * @return {@code true} unless the tag is an end-group tag. */ protected boolean parseUnknownField( final CodedInputStream input, final UnknownFieldSet.Builder unknownFields, final ExtensionRegistryLite extensionRegistry, - final int tag) throws IOException { + final int tag) + throws IOException { return unknownFields.mergeFieldFrom(tag, input); } /** - * Implementation of {@link BuilderParent} for giving to our children. This - * small inner class makes it so we don't publicly expose the BuilderParent - * methods. + * Implementation of {@link BuilderParent} for giving to our children. This small inner class + * makes it so we don't publicly expose the BuilderParent methods. */ private class BuilderParentImpl implements BuilderParent { @@ -680,6 +647,7 @@ public abstract class GeneratedMessage extends AbstractMessage /** * Gets the {@link BuilderParent} for giving to our children. + * * @return The builder parent for our children. */ protected BuilderParent getParentForChildren() { @@ -690,8 +658,8 @@ public abstract class GeneratedMessage extends AbstractMessage } /** - * Called when a the builder or one of its nested children has changed - * and any parent should be notified of its invalidation. + * Called when a the builder or one of its nested children has changed and any parent should be + * notified of its invalidation. */ protected final void onChanged() { if (isClean && builderParent != null) { @@ -703,22 +671,19 @@ public abstract class GeneratedMessage extends AbstractMessage } /** - * Gets the map field with the given field number. This method should be - * overridden in the generated message class if the message contains map - * fields. + * Gets the map field with the given field number. This method should be overridden in the + * generated message class if the message contains map fields. * - * Unlike other field types, reflection support for map fields can't be - * implemented based on generated public API because we need to access a - * map field as a list in reflection API but the generated API only allows - * us to access it as a map. This method returns the underlying map field - * directly and thus enables us to access the map field as a list. + *

Unlike other field types, reflection support for map fields can't be implemented based on + * generated public API because we need to access a map field as a list in reflection API but + * the generated API only allows us to access it as a map. This method returns the underlying + * map field directly and thus enables us to access the map field as a list. */ @SuppressWarnings({"unused", "rawtypes"}) protected MapField internalGetMapField(int fieldNumber) { // Note that we can't use descriptor names here because this method will // be called when descriptor is being initialized. - throw new RuntimeException( - "No map fields found in " + getClass().getName()); + throw new RuntimeException("No map fields found in " + getClass().getName()); } /** Like {@link #internalGetMapField} but return a mutable version. */ @@ -726,76 +691,57 @@ public abstract class GeneratedMessage extends AbstractMessage protected MapField internalGetMutableMapField(int fieldNumber) { // Note that we can't use descriptor names here because this method will // be called when descriptor is being initialized. - throw new RuntimeException( - "No map fields found in " + getClass().getName()); + throw new RuntimeException("No map fields found in " + getClass().getName()); } } // ================================================================= // Extensions-related stuff - public interface ExtendableMessageOrBuilder< - MessageType extends ExtendableMessage> extends MessageOrBuilder { + public interface ExtendableMessageOrBuilder + extends MessageOrBuilder { // Re-define for return type covariance. @Override Message getDefaultInstanceForType(); /** Check if a singular extension is present. */ - boolean hasExtension( - ExtensionLite extension); + boolean hasExtension(ExtensionLite extension); /** Get the number of elements in a repeated extension. */ - int getExtensionCount( - ExtensionLite> extension); + int getExtensionCount(ExtensionLite> extension); /** Get the value of an extension. */ - Type getExtension( - ExtensionLite extension); + Type getExtension(ExtensionLite extension); /** Get one element of a repeated extension. */ - Type getExtension( - ExtensionLite> extension, - int index); + Type getExtension(ExtensionLite> extension, int index); /** Check if a singular extension is present. */ - boolean hasExtension( - Extension extension); + boolean hasExtension(Extension extension); /** Check if a singular extension is present. */ - boolean hasExtension( - GeneratedExtension extension); + boolean hasExtension(GeneratedExtension extension); /** Get the number of elements in a repeated extension. */ - int getExtensionCount( - Extension> extension); + int getExtensionCount(Extension> extension); /** Get the number of elements in a repeated extension. */ - int getExtensionCount( - GeneratedExtension> extension); + int getExtensionCount(GeneratedExtension> extension); /** Get the value of an extension. */ - Type getExtension( - Extension extension); + Type getExtension(Extension extension); /** Get the value of an extension. */ - Type getExtension( - GeneratedExtension extension); + Type getExtension(GeneratedExtension extension); /** Get one element of a repeated extension. */ - Type getExtension( - Extension> extension, - int index); + Type getExtension(Extension> extension, int index); /** Get one element of a repeated extension. */ - Type getExtension( - GeneratedExtension> extension, - int index); + Type getExtension(GeneratedExtension> extension, int index); } /** - * Generated message classes for message types that contain extension ranges - * subclass this. + * Generated message classes for message types that contain extension ranges subclass this. * - *

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

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

For example, imagine you have the {@code .proto} file: * @@ -820,10 +766,8 @@ public abstract class GeneratedMessage extends AbstractMessage * *

See also {@link ExtendableBuilder}. */ - public abstract static class ExtendableMessage< - MessageType extends ExtendableMessage> - extends GeneratedMessage - implements ExtendableMessageOrBuilder { + public abstract static class ExtendableMessage + extends GeneratedMessage implements ExtendableMessageOrBuilder { private static final long serialVersionUID = 1L; @@ -833,22 +777,20 @@ public abstract class GeneratedMessage extends AbstractMessage this.extensions = FieldSet.newFieldSet(); } - protected ExtendableMessage( - ExtendableBuilder builder) { + protected ExtendableMessage(ExtendableBuilder builder) { super(builder); this.extensions = builder.buildExtensions(); } - private void verifyExtensionContainingType( - final Extension extension) { - if (extension.getDescriptor().getContainingType() != - getDescriptorForType()) { + private void verifyExtensionContainingType(final Extension extension) { + if (extension.getDescriptor().getContainingType() != getDescriptorForType()) { // This can only happen if someone uses unchecked operations. throw new IllegalArgumentException( - "Extension is for type \"" + - extension.getDescriptor().getContainingType().getFullName() + - "\" which does not match message type \"" + - getDescriptorForType().getFullName() + "\"."); + "Extension is for type \"" + + extension.getDescriptor().getContainingType().getFullName() + + "\" which does not match message type \"" + + getDescriptorForType().getFullName() + + "\"."); } } @@ -886,12 +828,10 @@ public abstract class GeneratedMessage extends AbstractMessage if (value == null) { if (descriptor.isRepeated()) { return (Type) Collections.emptyList(); - } else if (descriptor.getJavaType() == - FieldDescriptor.JavaType.MESSAGE) { + } else if (descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { return (Type) extension.getMessageDefaultInstance(); } else { - return (Type) extension.fromReflectionType( - descriptor.getDefaultValue()); + return (Type) extension.fromReflectionType(descriptor.getDefaultValue()); } } else { return (Type) extension.fromReflectionType(value); @@ -907,8 +847,8 @@ public abstract class GeneratedMessage extends AbstractMessage verifyExtensionContainingType(extension); FieldDescriptor descriptor = extension.getDescriptor(); - return (Type) extension.singularFromReflectionType( - extensions.getRepeatedField(descriptor, index)); + return (Type) + extension.singularFromReflectionType(extensions.getRepeatedField(descriptor, index)); } /** Check if a singular extension is present. */ @@ -924,8 +864,7 @@ public abstract class GeneratedMessage extends AbstractMessage } /** Get the number of elements in a repeated extension. */ @Override - public final int getExtensionCount( - final Extension> extension) { + public final int getExtensionCount(final Extension> extension) { return getExtensionCount((ExtensionLite>) extension); } /** Get the number of elements in a repeated extension. */ @@ -941,8 +880,7 @@ public abstract class GeneratedMessage extends AbstractMessage } /** Get the value of an extension. */ @Override - public final Type getExtension( - final GeneratedExtension extension) { + public final Type getExtension(final GeneratedExtension extension) { return getExtension((ExtensionLite) extension); } /** Get one element of a repeated extension. */ @@ -973,33 +911,33 @@ public abstract class GeneratedMessage extends AbstractMessage CodedInputStream input, UnknownFieldSet.Builder unknownFields, ExtensionRegistryLite extensionRegistry, - int tag) throws IOException { + int tag) + throws IOException { return MessageReflection.mergeFieldFrom( - input, unknownFields, extensionRegistry, getDescriptorForType(), - new MessageReflection.ExtensionAdapter(extensions), tag); + input, + unknownFields, + extensionRegistry, + getDescriptorForType(), + new MessageReflection.ExtensionAdapter(extensions), + tag); } - - /** - * Used by parsing constructors in generated classes. - */ + /** Used by parsing constructors in generated classes. */ @Override protected void makeExtensionsImmutable() { extensions.makeImmutable(); } /** - * Used by subclasses to serialize extensions. Extension ranges may be - * interleaved with field numbers, but we must write them in canonical - * (sorted by field number) order. ExtensionWriter helps us write - * individual ranges of extensions at once. + * Used by subclasses to serialize extensions. Extension ranges may be interleaved with field + * numbers, but we must write them in canonical (sorted by field number) order. ExtensionWriter + * helps us write individual ranges of extensions at once. */ protected class ExtensionWriter { // Imagine how much simpler this code would be if Java iterators had // a way to get the next element without advancing the iterator. - private final Iterator> iter = - extensions.iterator(); + private final Iterator> iter = extensions.iterator(); private Map.Entry next; private final boolean messageSetWireFormat; @@ -1010,19 +948,18 @@ public abstract class GeneratedMessage extends AbstractMessage this.messageSetWireFormat = messageSetWireFormat; } - public void writeUntil(final int end, final CodedOutputStream output) - throws IOException { + public void writeUntil(final int end, final CodedOutputStream output) throws IOException { while (next != null && next.getKey().getNumber() < end) { FieldDescriptor descriptor = next.getKey(); - if (messageSetWireFormat && descriptor.getLiteJavaType() == - WireFormat.JavaType.MESSAGE && - !descriptor.isRepeated()) { + if (messageSetWireFormat + && descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE + && !descriptor.isRepeated()) { if (next instanceof LazyField.LazyEntry) { - output.writeRawMessageSetExtension(descriptor.getNumber(), + output.writeRawMessageSetExtension( + descriptor.getNumber(), ((LazyField.LazyEntry) next).getField().toByteString()); } else { - output.writeMessageSetExtension(descriptor.getNumber(), - (Message) next.getValue()); + output.writeMessageSetExtension(descriptor.getNumber(), (Message) next.getValue()); } } else { // TODO(xiangl): Taken care of following code, it may cause @@ -1046,6 +983,7 @@ public abstract class GeneratedMessage extends AbstractMessage protected ExtensionWriter newExtensionWriter() { return new ExtensionWriter(false); } + protected ExtensionWriter newMessageSetExtensionWriter() { return new ExtensionWriter(true); } @@ -1054,6 +992,7 @@ public abstract class GeneratedMessage extends AbstractMessage protected int extensionsSerializedSize() { return extensions.getSerializedSize(); } + protected int extensionsSerializedSizeAsMessageSet() { return extensions.getMessageSetSerializedSize(); } @@ -1125,8 +1064,7 @@ public abstract class GeneratedMessage extends AbstractMessage } @Override - public Object getRepeatedField(final FieldDescriptor field, - final int index) { + public Object getRepeatedField(final FieldDescriptor field, final int index) { if (field.isExtension()) { verifyContainingType(field); return extensions.getRepeatedField(field, index); @@ -1137,23 +1075,19 @@ public abstract class GeneratedMessage extends AbstractMessage private void verifyContainingType(final FieldDescriptor field) { if (field.getContainingType() != getDescriptorForType()) { - throw new IllegalArgumentException( - "FieldDescriptor does not match message type."); + throw new IllegalArgumentException("FieldDescriptor does not match message type."); } } } /** - * Generated message builders for message types that contain extension ranges - * subclass this. + * Generated message builders for message types that contain extension ranges subclass this. * - *

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

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

For example, imagine you have the {@code .proto} file: * @@ -1182,17 +1116,15 @@ public abstract class GeneratedMessage extends AbstractMessage */ @SuppressWarnings("unchecked") public abstract static class ExtendableBuilder< - MessageType extends ExtendableMessage, - BuilderType extends ExtendableBuilder> - extends Builder - implements ExtendableMessageOrBuilder { + MessageType extends ExtendableMessage, + BuilderType extends ExtendableBuilder> + extends Builder implements ExtendableMessageOrBuilder { private FieldSet extensions = FieldSet.emptySet(); protected ExtendableBuilder() {} - protected ExtendableBuilder( - BuilderParent parent) { + protected ExtendableBuilder(BuilderParent parent) { super(parent); } @@ -1221,16 +1153,15 @@ public abstract class GeneratedMessage extends AbstractMessage } } - private void verifyExtensionContainingType( - final Extension extension) { - if (extension.getDescriptor().getContainingType() != - getDescriptorForType()) { + private void verifyExtensionContainingType(final Extension extension) { + if (extension.getDescriptor().getContainingType() != getDescriptorForType()) { // This can only happen if someone uses unchecked operations. throw new IllegalArgumentException( - "Extension is for type \"" + - extension.getDescriptor().getContainingType().getFullName() + - "\" which does not match message type \"" + - getDescriptorForType().getFullName() + "\"."); + "Extension is for type \"" + + extension.getDescriptor().getContainingType().getFullName() + + "\" which does not match message type \"" + + getDescriptorForType().getFullName() + + "\"."); } } @@ -1265,12 +1196,10 @@ public abstract class GeneratedMessage extends AbstractMessage if (value == null) { if (descriptor.isRepeated()) { return (Type) Collections.emptyList(); - } else if (descriptor.getJavaType() == - FieldDescriptor.JavaType.MESSAGE) { + } else if (descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { return (Type) extension.getMessageDefaultInstance(); } else { - return (Type) extension.fromReflectionType( - descriptor.getDefaultValue()); + return (Type) extension.fromReflectionType(descriptor.getDefaultValue()); } } else { return (Type) extension.fromReflectionType(value); @@ -1285,14 +1214,13 @@ public abstract class GeneratedMessage extends AbstractMessage verifyExtensionContainingType(extension); FieldDescriptor descriptor = extension.getDescriptor(); - return (Type) extension.singularFromReflectionType( - extensions.getRepeatedField(descriptor, index)); + return (Type) + extension.singularFromReflectionType(extensions.getRepeatedField(descriptor, index)); } /** Set the value of an extension. */ public final BuilderType setExtension( - final ExtensionLite extensionLite, - final Type value) { + final ExtensionLite extensionLite, final Type value) { Extension extension = checkNotLite(extensionLite); verifyExtensionContainingType(extension); @@ -1306,30 +1234,27 @@ public abstract class GeneratedMessage extends AbstractMessage /** Set the value of one element of a repeated extension. */ public final BuilderType setExtension( final ExtensionLite> extensionLite, - final int index, final Type value) { + final int index, + final Type value) { Extension> extension = checkNotLite(extensionLite); verifyExtensionContainingType(extension); ensureExtensionsIsMutable(); final FieldDescriptor descriptor = extension.getDescriptor(); - extensions.setRepeatedField( - descriptor, index, - extension.singularToReflectionType(value)); + extensions.setRepeatedField(descriptor, index, extension.singularToReflectionType(value)); onChanged(); return (BuilderType) this; } /** Append a value to a repeated extension. */ public final BuilderType addExtension( - final ExtensionLite> extensionLite, - final Type value) { + final ExtensionLite> extensionLite, final Type value) { Extension> extension = checkNotLite(extensionLite); verifyExtensionContainingType(extension); ensureExtensionsIsMutable(); final FieldDescriptor descriptor = extension.getDescriptor(); - extensions.addRepeatedField( - descriptor, extension.singularToReflectionType(value)); + extensions.addRepeatedField(descriptor, extension.singularToReflectionType(value)); onChanged(); return (BuilderType) this; } @@ -1359,8 +1284,7 @@ public abstract class GeneratedMessage extends AbstractMessage } /** Get the number of elements in a repeated extension. */ @Override - public final int getExtensionCount( - final Extension> extension) { + public final int getExtensionCount(final Extension> extension) { return getExtensionCount((ExtensionLite>) extension); } /** Get the number of elements in a repeated extension. */ @@ -1376,8 +1300,7 @@ public abstract class GeneratedMessage extends AbstractMessage } /** Get the value of an extension. */ @Override - public final Type getExtension( - final GeneratedExtension extension) { + public final Type getExtension(final GeneratedExtension extension) { return getExtension((ExtensionLite) extension); } /** Get the value of an extension. */ @@ -1404,14 +1327,14 @@ public abstract class GeneratedMessage extends AbstractMessage } /** Set the value of one element of a repeated extension. */ public final BuilderType setExtension( - final Extension> extension, - final int index, final Type value) { + final Extension> extension, final int index, final Type value) { return setExtension((ExtensionLite>) extension, index, value); } /** Set the value of one element of a repeated extension. */ public BuilderType setExtension( final GeneratedExtension> extension, - final int index, final Type value) { + final int index, + final Type value) { return setExtension((ExtensionLite>) extension, index, value); } /** Append a value to a repeated extension. */ @@ -1425,13 +1348,11 @@ public abstract class GeneratedMessage extends AbstractMessage return addExtension((ExtensionLite>) extension, value); } /** Clear an extension. */ - public final BuilderType clearExtension( - final Extension extension) { + public final BuilderType clearExtension(final Extension extension) { return clearExtension((ExtensionLite) extension); } /** Clear an extension. */ - public BuilderType clearExtension( - final GeneratedExtension extension) { + public BuilderType clearExtension(final GeneratedExtension extension) { return clearExtension((ExtensionLite) extension); } @@ -1441,8 +1362,7 @@ public abstract class GeneratedMessage extends AbstractMessage } /** - * Called by the build code path to create a copy of the extensions for - * building the message. + * Called by the build code path to create a copy of the extensions for building the message. */ private FieldSet buildExtensions() { extensions.makeImmutable(); @@ -1456,6 +1376,7 @@ public abstract class GeneratedMessage extends AbstractMessage /** * Called by subclasses to parse an unknown field or an extension. + * * @return {@code true} unless the tag is an end-group tag. */ @Override @@ -1463,10 +1384,15 @@ public abstract class GeneratedMessage extends AbstractMessage final CodedInputStream input, final UnknownFieldSet.Builder unknownFields, final ExtensionRegistryLite extensionRegistry, - final int tag) throws IOException { + final int tag) + throws IOException { return MessageReflection.mergeFieldFrom( - input, unknownFields, extensionRegistry, getDescriptorForType(), - new MessageReflection.BuilderAdapter(this), tag); + input, + unknownFields, + extensionRegistry, + getDescriptorForType(), + new MessageReflection.BuilderAdapter(this), + tag); } // --------------------------------------------------------------- @@ -1511,8 +1437,7 @@ public abstract class GeneratedMessage extends AbstractMessage } @Override - public Object getRepeatedField(final FieldDescriptor field, - final int index) { + public Object getRepeatedField(final FieldDescriptor field, final int index) { if (field.isExtension()) { verifyContainingType(field); return extensions.getRepeatedField(field, index); @@ -1532,8 +1457,7 @@ public abstract class GeneratedMessage extends AbstractMessage } @Override - public BuilderType setField(final FieldDescriptor field, - final Object value) { + public BuilderType setField(final FieldDescriptor field, final Object value) { if (field.isExtension()) { verifyContainingType(field); ensureExtensionsIsMutable(); @@ -1559,8 +1483,8 @@ public abstract class GeneratedMessage extends AbstractMessage } @Override - public BuilderType setRepeatedField(final FieldDescriptor field, - final int index, final Object value) { + public BuilderType setRepeatedField( + final FieldDescriptor field, final int index, final Object value) { if (field.isExtension()) { verifyContainingType(field); ensureExtensionsIsMutable(); @@ -1573,8 +1497,7 @@ public abstract class GeneratedMessage extends AbstractMessage } @Override - public BuilderType addRepeatedField(final FieldDescriptor field, - final Object value) { + public BuilderType addRepeatedField(final FieldDescriptor field, final Object value) { if (field.isExtension()) { verifyContainingType(field); ensureExtensionsIsMutable(); @@ -1594,8 +1517,7 @@ public abstract class GeneratedMessage extends AbstractMessage private void verifyContainingType(final FieldDescriptor field) { if (field.getContainingType() != getDescriptorForType()) { - throw new IllegalArgumentException( - "FieldDescriptor does not match message type."); + throw new IllegalArgumentException("FieldDescriptor does not match message type."); } } } @@ -1603,8 +1525,8 @@ public abstract class GeneratedMessage extends AbstractMessage // ----------------------------------------------------------------- /** - * Gets the descriptor for an extension. The implementation depends on whether - * the extension is scoped in the top level of a file or scoped in a Message. + * Gets the descriptor for an extension. The implementation depends on whether the extension is + * scoped in the top level of a file or scoped in a Message. */ static interface ExtensionDescriptorRetriever { FieldDescriptor getDescriptor(); @@ -1612,11 +1534,11 @@ public abstract class GeneratedMessage extends AbstractMessage /** For use by generated code only. */ public static - GeneratedExtension - newMessageScopedGeneratedExtension(final Message scope, - final int descriptorIndex, - final Class singularType, - final Message defaultInstance) { + GeneratedExtension newMessageScopedGeneratedExtension( + final Message scope, + final int descriptorIndex, + final Class singularType, + final Message defaultInstance) { // For extensions scoped within a Message, we use the Message to resolve // the outer class's descriptor, from which the extension descriptor is // obtained. @@ -1634,22 +1556,21 @@ public abstract class GeneratedMessage extends AbstractMessage /** For use by generated code only. */ public static - GeneratedExtension - newFileScopedGeneratedExtension(final Class singularType, - final Message defaultInstance) { + GeneratedExtension newFileScopedGeneratedExtension( + final Class singularType, final Message defaultInstance) { // For extensions scoped within a file, we rely on the outer class's // static initializer to call internalInit() on the extension when the // descriptor is available. return new GeneratedExtension( - null, // ExtensionDescriptorRetriever is initialized in internalInit(); + null, // ExtensionDescriptorRetriever is initialized in internalInit(); singularType, defaultInstance, Extension.ExtensionType.IMMUTABLE); } - private abstract static class CachedDescriptorRetriever - implements ExtensionDescriptorRetriever { + private abstract static class CachedDescriptorRetriever implements ExtensionDescriptorRetriever { private volatile FieldDescriptor descriptor; + protected abstract FieldDescriptor loadDescriptor(); @Override @@ -1668,15 +1589,16 @@ public abstract class GeneratedMessage extends AbstractMessage /** * Used in proto1 generated code only. * - * After enabling bridge, we can define proto2 extensions (the extended type - * is a proto2 mutable message) in a proto1 .proto file. For these extensions - * we should generate proto2 GeneratedExtensions. + *

After enabling bridge, we can define proto2 extensions (the extended type is a proto2 + * mutable message) in a proto1 .proto file. For these extensions we should generate proto2 + * GeneratedExtensions. */ public static - GeneratedExtension - newMessageScopedGeneratedExtension( - final Message scope, final String name, - final Class singularType, final Message defaultInstance) { + GeneratedExtension newMessageScopedGeneratedExtension( + final Message scope, + final String name, + final Class singularType, + final Message defaultInstance) { // For extensions scoped within a Message, we use the Message to resolve // the outer class's descriptor, from which the extension descriptor is // obtained. @@ -1695,15 +1617,16 @@ public abstract class GeneratedMessage extends AbstractMessage /** * Used in proto1 generated code only. * - * After enabling bridge, we can define proto2 extensions (the extended type - * is a proto2 mutable message) in a proto1 .proto file. For these extensions - * we should generate proto2 GeneratedExtensions. + *

After enabling bridge, we can define proto2 extensions (the extended type is a proto2 + * mutable message) in a proto1 .proto file. For these extensions we should generate proto2 + * GeneratedExtensions. */ public static - GeneratedExtension - newFileScopedGeneratedExtension( - final Class singularType, final Message defaultInstance, - final String descriptorOuterClass, final String extensionName) { + GeneratedExtension newFileScopedGeneratedExtension( + final Class singularType, + final Message defaultInstance, + final String descriptorOuterClass, + final String extensionName) { // For extensions scoped within a file, we load the descriptor outer // class and rely on it to get the FileDescriptor which then can be // used to obtain the extension's FieldDescriptor. @@ -1730,8 +1653,8 @@ public abstract class GeneratedMessage extends AbstractMessage } /** - * Type used to represent generated extensions. The protocol compiler - * generates a static singleton instance of this class for each extension. + * Type used to represent generated extensions. The protocol compiler generates a static singleton + * instance of this class for each extension. * *

For example, imagine you have the {@code .proto} file: * @@ -1747,16 +1670,14 @@ public abstract class GeneratedMessage extends AbstractMessage * } * * - *

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

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

In general, users should ignore the details of this type, and simply use - * these static singletons as parameters to the extension accessors defined - * in {@link ExtendableMessage} and {@link ExtendableBuilder}. + *

In general, users should ignore the details of this type, and simply use these static + * singletons as parameters to the extension accessors defined in {@link ExtendableMessage} and + * {@link ExtendableBuilder}. */ - public static class GeneratedExtension< - ContainingType extends Message, Type> extends - Extension { + public static class GeneratedExtension + extends Extension { // TODO(kenton): Find ways to avoid using Java reflection within this // class. Also try to avoid suppressing unchecked warnings. @@ -1772,12 +1693,13 @@ public abstract class GeneratedMessage extends AbstractMessage // In the case of non-nested extensions, we initialize the // ExtensionDescriptorRetriever to null and rely on the outer class's static // initializer to call internalInit() after the descriptor has been parsed. - GeneratedExtension(ExtensionDescriptorRetriever descriptorRetriever, + GeneratedExtension( + ExtensionDescriptorRetriever descriptorRetriever, Class singularType, Message messageDefaultInstance, ExtensionType extensionType) { - if (Message.class.isAssignableFrom(singularType) && - !singularType.isInstance(messageDefaultInstance)) { + if (Message.class.isAssignableFrom(singularType) + && !singularType.isInstance(messageDefaultInstance)) { throw new IllegalArgumentException( "Bad messageDefaultInstance for " + singularType.getName()); } @@ -1786,10 +1708,8 @@ public abstract class GeneratedMessage extends AbstractMessage this.messageDefaultInstance = messageDefaultInstance; if (ProtocolMessageEnum.class.isAssignableFrom(singularType)) { - this.enumValueOf = getMethodOrDie(singularType, "valueOf", - EnumValueDescriptor.class); - this.enumGetValueDescriptor = - getMethodOrDie(singularType, "getValueDescriptor"); + this.enumValueOf = getMethodOrDie(singularType, "valueOf", EnumValueDescriptor.class); + this.enumGetValueDescriptor = getMethodOrDie(singularType, "getValueDescriptor"); } else { this.enumValueOf = null; this.enumGetValueDescriptor = null; @@ -1821,15 +1741,14 @@ public abstract class GeneratedMessage extends AbstractMessage @Override public FieldDescriptor getDescriptor() { if (descriptorRetriever == null) { - throw new IllegalStateException( - "getDescriptor() called before internalInit()"); + throw new IllegalStateException("getDescriptor() called before internalInit()"); } return descriptorRetriever.getDescriptor(); } /** - * If the extension is an embedded message or group, returns the default - * instance of the message. + * If the extension is an embedded message or group, returns the default instance of the + * message. */ @Override public Message getMessageDefaultInstance() { @@ -1842,18 +1761,17 @@ public abstract class GeneratedMessage extends AbstractMessage } /** - * Convert from the type used by the reflection accessors to the type used - * by native accessors. E.g., for enums, the reflection accessors use - * EnumValueDescriptors but the native accessors use the generated enum - * type. + * Convert from the type used by the reflection accessors to the type used by native accessors. + * E.g., for enums, the reflection accessors use EnumValueDescriptors but the native accessors + * use the generated enum type. */ @Override @SuppressWarnings("unchecked") protected Object fromReflectionType(final Object value) { FieldDescriptor descriptor = getDescriptor(); if (descriptor.isRepeated()) { - if (descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE || - descriptor.getJavaType() == FieldDescriptor.JavaType.ENUM) { + if (descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE + || descriptor.getJavaType() == FieldDescriptor.JavaType.ENUM) { // Must convert the whole list. final List result = new ArrayList(); for (final Object element : (List) value) { @@ -1869,8 +1787,8 @@ public abstract class GeneratedMessage extends AbstractMessage } /** - * Like {@link #fromReflectionType(Object)}, but if the type is a repeated - * type, this converts a single element. + * Like {@link #fromReflectionType(Object)}, but if the type is a repeated type, this converts a + * single element. */ @Override protected Object singularFromReflectionType(final Object value) { @@ -1880,8 +1798,7 @@ public abstract class GeneratedMessage extends AbstractMessage if (singularType.isInstance(value)) { return value; } else { - return messageDefaultInstance.newBuilderForType() - .mergeFrom((Message) value).build(); + return messageDefaultInstance.newBuilderForType().mergeFrom((Message) value).build(); } case ENUM: return invokeOrDie(enumValueOf, null, (EnumValueDescriptor) value); @@ -1891,10 +1808,9 @@ public abstract class GeneratedMessage extends AbstractMessage } /** - * Convert from the type used by the native accessors to the type used - * by reflection accessors. E.g., for enums, the reflection accessors use - * EnumValueDescriptors but the native accessors use the generated enum - * type. + * Convert from the type used by the native accessors to the type used by reflection accessors. + * E.g., for enums, the reflection accessors use EnumValueDescriptors but the native accessors + * use the generated enum type. */ @Override @SuppressWarnings("unchecked") @@ -1917,8 +1833,8 @@ public abstract class GeneratedMessage extends AbstractMessage } /** - * Like {@link #toReflectionType(Object)}, but if the type is a repeated - * type, this converts a single element. + * Like {@link #toReflectionType(Object)}, but if the type is a repeated type, this converts a + * single element. */ @Override protected Object singularToReflectionType(final Object value) { @@ -1955,8 +1871,7 @@ public abstract class GeneratedMessage extends AbstractMessage if (getDescriptor().getJavaType() == FieldDescriptor.JavaType.MESSAGE) { return (Type) messageDefaultInstance; } - return (Type) singularFromReflectionType( - getDescriptor().getDefaultValue()); + return (Type) singularFromReflectionType(getDescriptor().getDefaultValue()); } } @@ -1970,8 +1885,8 @@ public abstract class GeneratedMessage extends AbstractMessage return clazz.getMethod(name, params); } catch (NoSuchMethodException e) { throw new RuntimeException( - "Generated message class \"" + clazz.getName() + - "\" missing method \"" + name + "\".", e); + "Generated message class \"" + clazz.getName() + "\" missing method \"" + name + "\".", + e); } } @@ -1982,8 +1897,7 @@ public abstract class GeneratedMessage extends AbstractMessage return method.invoke(object, params); } catch (IllegalAccessException e) { throw new RuntimeException( - "Couldn't use Java reflection to implement protocol message " + - "reflection.", e); + "Couldn't use Java reflection to implement protocol message " + "reflection.", e); } catch (InvocationTargetException e) { final Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { @@ -1992,45 +1906,42 @@ public abstract class GeneratedMessage extends AbstractMessage throw (Error) cause; } else { throw new RuntimeException( - "Unexpected exception thrown by generated accessor method.", cause); + "Unexpected exception thrown by generated accessor method.", cause); } } } /** - * Gets the map field with the given field number. This method should be - * overridden in the generated message class if the message contains map - * fields. + * Gets the map field with the given field number. This method should be overridden in the + * generated message class if the message contains map fields. * - * Unlike other field types, reflection support for map fields can't be - * implemented based on generated public API because we need to access a - * map field as a list in reflection API but the generated API only allows - * us to access it as a map. This method returns the underlying map field - * directly and thus enables us to access the map field as a list. + *

Unlike other field types, reflection support for map fields can't be implemented based on + * generated public API because we need to access a map field as a list in reflection API but the + * generated API only allows us to access it as a map. This method returns the underlying map + * field directly and thus enables us to access the map field as a list. */ @SuppressWarnings({"rawtypes", "unused"}) protected MapField internalGetMapField(int fieldNumber) { // Note that we can't use descriptor names here because this method will // be called when descriptor is being initialized. - throw new RuntimeException( - "No map fields found in " + getClass().getName()); + throw new RuntimeException("No map fields found in " + getClass().getName()); } /** - * Users should ignore this class. This class provides the implementation - * with access to the fields of a message object using Java reflection. + * Users should ignore this class. This class provides the implementation with access to the + * fields of a message object using Java reflection. */ public static final class FieldAccessorTable { /** - * Construct a FieldAccessorTable for a particular message class. Only - * one FieldAccessorTable should ever be constructed per class. + * Construct a FieldAccessorTable for a particular message class. Only one FieldAccessorTable + * should ever be constructed per class. * - * @param descriptor The type's descriptor. - * @param camelCaseNames The camelcase names of all fields in the message. - * These are used to derive the accessor method names. - * @param messageClass The message type. - * @param builderClass The builder type. + * @param descriptor The type's descriptor. + * @param camelCaseNames The camelcase names of all fields in the message. These are used to + * derive the accessor method names. + * @param messageClass The message type. + * @param builderClass The builder type. */ public FieldAccessorTable( final Descriptor descriptor, @@ -2042,12 +1953,10 @@ public abstract class GeneratedMessage extends AbstractMessage } /** - * Construct a FieldAccessorTable for a particular message class without - * initializing FieldAccessors. + * Construct a FieldAccessorTable for a particular message class without initializing + * FieldAccessors. */ - public FieldAccessorTable( - final Descriptor descriptor, - final String[] camelCaseNames) { + public FieldAccessorTable(final Descriptor descriptor, final String[] camelCaseNames) { this.descriptor = descriptor; this.camelCaseNames = camelCaseNames; fields = new FieldAccessor[descriptor.getFields().size()]; @@ -2063,16 +1972,19 @@ public abstract class GeneratedMessage extends AbstractMessage /** * Ensures the field accessors are initialized. This method is thread-safe. * - * @param messageClass The message type. - * @param builderClass The builder type. + * @param messageClass The message type. + * @param builderClass The builder type. * @return this */ public FieldAccessorTable ensureFieldAccessorsInitialized( - Class messageClass, - Class builderClass) { - if (initialized) { return this; } + Class messageClass, Class builderClass) { + if (initialized) { + return this; + } synchronized (this) { - if (initialized) { return this; } + if (initialized) { + return this; + } int fieldsSize = fields.length; for (int i = 0; i < fieldsSize; i++) { FieldDescriptor field = descriptor.getFields().get(i); @@ -2084,45 +1996,63 @@ public abstract class GeneratedMessage extends AbstractMessage if (field.isRepeated()) { if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { if (field.isMapField() && isMapFieldEnabled(field)) { - fields[i] = new MapFieldAccessor( - field, camelCaseNames[i], messageClass, builderClass); + fields[i] = + new MapFieldAccessor(field, camelCaseNames[i], messageClass, builderClass); } else { - fields[i] = new RepeatedMessageFieldAccessor( - field, camelCaseNames[i], messageClass, builderClass); + fields[i] = + new RepeatedMessageFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass); } } else if (field.getJavaType() == FieldDescriptor.JavaType.ENUM) { - fields[i] = new RepeatedEnumFieldAccessor( - field, camelCaseNames[i], messageClass, builderClass); + fields[i] = + new RepeatedEnumFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass); } else { - fields[i] = new RepeatedFieldAccessor( - field, camelCaseNames[i], messageClass, builderClass); + fields[i] = + new RepeatedFieldAccessor(field, camelCaseNames[i], messageClass, builderClass); } } else { if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { - fields[i] = new SingularMessageFieldAccessor( - field, camelCaseNames[i], messageClass, builderClass, - containingOneofCamelCaseName); + fields[i] = + new SingularMessageFieldAccessor( + field, + camelCaseNames[i], + messageClass, + builderClass, + containingOneofCamelCaseName); } else if (field.getJavaType() == FieldDescriptor.JavaType.ENUM) { - fields[i] = new SingularEnumFieldAccessor( - field, camelCaseNames[i], messageClass, builderClass, - containingOneofCamelCaseName); + fields[i] = + new SingularEnumFieldAccessor( + field, + camelCaseNames[i], + messageClass, + builderClass, + containingOneofCamelCaseName); } else if (field.getJavaType() == FieldDescriptor.JavaType.STRING) { - fields[i] = new SingularStringFieldAccessor( - field, camelCaseNames[i], messageClass, builderClass, - containingOneofCamelCaseName); + fields[i] = + new SingularStringFieldAccessor( + field, + camelCaseNames[i], + messageClass, + builderClass, + containingOneofCamelCaseName); } else { - fields[i] = new SingularFieldAccessor( - field, camelCaseNames[i], messageClass, builderClass, - containingOneofCamelCaseName); + fields[i] = + new SingularFieldAccessor( + field, + camelCaseNames[i], + messageClass, + builderClass, + containingOneofCamelCaseName); } } } int oneofsSize = oneofs.length; for (int i = 0; i < oneofsSize; i++) { - oneofs[i] = new OneofAccessor( - descriptor, camelCaseNames[i + fieldsSize], - messageClass, builderClass); + oneofs[i] = + new OneofAccessor( + descriptor, camelCaseNames[i + fieldsSize], messageClass, builderClass); } initialized = true; camelCaseNames = null; @@ -2139,13 +2069,11 @@ public abstract class GeneratedMessage extends AbstractMessage /** Get the FieldAccessor for a particular field. */ private FieldAccessor getField(final FieldDescriptor field) { if (field.getContainingType() != descriptor) { - throw new IllegalArgumentException( - "FieldDescriptor does not match message type."); + throw new IllegalArgumentException("FieldDescriptor does not match message type."); } else if (field.isExtension()) { // If this type had extensions, it would subclass ExtendableMessage, // which overrides the reflection interface to handle extensions. - throw new IllegalArgumentException( - "This type does not have extensions."); + throw new IllegalArgumentException("This type does not have extensions."); } return fields[field.getIndex()]; } @@ -2153,51 +2081,65 @@ public abstract class GeneratedMessage extends AbstractMessage /** Get the OneofAccessor for a particular oneof. */ private OneofAccessor getOneof(final OneofDescriptor oneof) { if (oneof.getContainingType() != descriptor) { - throw new IllegalArgumentException( - "OneofDescriptor does not match message type."); + throw new IllegalArgumentException("OneofDescriptor does not match message type."); } return oneofs[oneof.getIndex()]; } /** - * Abstract interface that provides access to a single field. This is - * implemented differently depending on the field type and cardinality. + * Abstract interface that provides access to a single field. This is implemented differently + * depending on the field type and cardinality. */ private interface FieldAccessor { Object get(GeneratedMessage message); + Object get(GeneratedMessage.Builder builder); + Object getRaw(GeneratedMessage message); + Object getRaw(GeneratedMessage.Builder builder); + void set(Builder builder, Object value); + Object getRepeated(GeneratedMessage message, int index); + Object getRepeated(GeneratedMessage.Builder builder, int index); + Object getRepeatedRaw(GeneratedMessage message, int index); + Object getRepeatedRaw(GeneratedMessage.Builder builder, int index); - void setRepeated(Builder builder, - int index, Object value); + + void setRepeated(Builder builder, int index, Object value); + void addRepeated(Builder builder, Object value); + boolean has(GeneratedMessage message); + boolean has(GeneratedMessage.Builder builder); + int getRepeatedCount(GeneratedMessage message); + int getRepeatedCount(GeneratedMessage.Builder builder); + void clear(Builder builder); + Message.Builder newBuilder(); + Message.Builder getBuilder(GeneratedMessage.Builder builder); - Message.Builder getRepeatedBuilder(GeneratedMessage.Builder builder, - int index); + + Message.Builder getRepeatedBuilder(GeneratedMessage.Builder builder, int index); } /** OneofAccessor provides access to a single oneof. */ private static class OneofAccessor { OneofAccessor( - final Descriptor descriptor, final String camelCaseName, + final Descriptor descriptor, + final String camelCaseName, final Class messageClass, final Class builderClass) { this.descriptor = descriptor; - caseMethod = - getMethodOrDie(messageClass, "get" + camelCaseName + "Case"); - caseMethodBuilder = - getMethodOrDie(builderClass, "get" + camelCaseName + "Case"); + caseMethod = getMethodOrDie(messageClass, "get" + camelCaseName + "Case"); + caseMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName + "Case"); clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName); } @@ -2249,27 +2191,32 @@ public abstract class GeneratedMessage extends AbstractMessage private static class SingularFieldAccessor implements FieldAccessor { SingularFieldAccessor( - final FieldDescriptor descriptor, final String camelCaseName, + final FieldDescriptor descriptor, + final String camelCaseName, final Class messageClass, final Class builderClass, final String containingOneofCamelCaseName) { field = descriptor; isOneofField = descriptor.getContainingOneof() != null; - hasHasMethod = supportFieldPresence(descriptor.getFile()) - || (!isOneofField && descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE); + hasHasMethod = + supportFieldPresence(descriptor.getFile()) + || (!isOneofField && descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE); getMethod = getMethodOrDie(messageClass, "get" + camelCaseName); getMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName); type = getMethod.getReturnType(); setMethod = getMethodOrDie(builderClass, "set" + camelCaseName, type); - hasMethod = - hasHasMethod ? getMethodOrDie(messageClass, "has" + camelCaseName) : null; + hasMethod = hasHasMethod ? getMethodOrDie(messageClass, "has" + camelCaseName) : null; hasMethodBuilder = hasHasMethod ? getMethodOrDie(builderClass, "has" + camelCaseName) : null; clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName); - caseMethod = isOneofField ? getMethodOrDie( - messageClass, "get" + containingOneofCamelCaseName + "Case") : null; - caseMethodBuilder = isOneofField ? getMethodOrDie( - builderClass, "get" + containingOneofCamelCaseName + "Case") : null; + caseMethod = + isOneofField + ? getMethodOrDie(messageClass, "get" + containingOneofCamelCaseName + "Case") + : null; + caseMethodBuilder = + isOneofField + ? getMethodOrDie(builderClass, "get" + containingOneofCamelCaseName + "Case") + : null; } // Note: We use Java reflection to call public methods rather than @@ -2300,52 +2247,59 @@ public abstract class GeneratedMessage extends AbstractMessage public Object get(final GeneratedMessage message) { return invokeOrDie(getMethod, message); } + @Override public Object get(GeneratedMessage.Builder builder) { return invokeOrDie(getMethodBuilder, builder); } + @Override public Object getRaw(final GeneratedMessage message) { return get(message); } + @Override public Object getRaw(GeneratedMessage.Builder builder) { return get(builder); } + @Override public void set(final Builder builder, final Object value) { invokeOrDie(setMethod, builder, value); } + @Override public Object getRepeated(final GeneratedMessage message, final int index) { - throw new UnsupportedOperationException( - "getRepeatedField() called on a singular field."); + throw new UnsupportedOperationException("getRepeatedField() called on a singular field."); } + @Override public Object getRepeatedRaw(final GeneratedMessage message, final int index) { throw new UnsupportedOperationException( - "getRepeatedFieldRaw() called on a singular field."); + "getRepeatedFieldRaw() called on a singular field."); } + @Override public Object getRepeated(GeneratedMessage.Builder builder, int index) { - throw new UnsupportedOperationException( - "getRepeatedField() called on a singular field."); + throw new UnsupportedOperationException("getRepeatedField() called on a singular field."); } + @Override public Object getRepeatedRaw(GeneratedMessage.Builder builder, int index) { throw new UnsupportedOperationException( - "getRepeatedFieldRaw() called on a singular field."); + "getRepeatedFieldRaw() called on a singular field."); } + @Override public void setRepeated(final Builder builder, final int index, final Object value) { - throw new UnsupportedOperationException( - "setRepeatedField() called on a singular field."); + throw new UnsupportedOperationException("setRepeatedField() called on a singular field."); } + @Override public void addRepeated(final Builder builder, final Object value) { - throw new UnsupportedOperationException( - "addRepeatedField() called on a singular field."); + throw new UnsupportedOperationException("addRepeatedField() called on a singular field."); } + @Override public boolean has(final GeneratedMessage message) { if (!hasHasMethod) { @@ -2356,6 +2310,7 @@ public abstract class GeneratedMessage extends AbstractMessage } return (Boolean) invokeOrDie(hasMethod, message); } + @Override public boolean has(GeneratedMessage.Builder builder) { if (!hasHasMethod) { @@ -2366,34 +2321,39 @@ public abstract class GeneratedMessage extends AbstractMessage } return (Boolean) invokeOrDie(hasMethodBuilder, builder); } + @Override public int getRepeatedCount(final GeneratedMessage message) { throw new UnsupportedOperationException( - "getRepeatedFieldSize() called on a singular field."); + "getRepeatedFieldSize() called on a singular field."); } + @Override public int getRepeatedCount(GeneratedMessage.Builder builder) { throw new UnsupportedOperationException( - "getRepeatedFieldSize() called on a singular field."); + "getRepeatedFieldSize() called on a singular field."); } + @Override public void clear(final Builder builder) { invokeOrDie(clearMethod, builder); } + @Override public Message.Builder newBuilder() { throw new UnsupportedOperationException( - "newBuilderForField() called on a non-Message type."); + "newBuilderForField() called on a non-Message type."); } + @Override public Message.Builder getBuilder(GeneratedMessage.Builder builder) { - throw new UnsupportedOperationException( - "getFieldBuilder() called on a non-Message type."); + throw new UnsupportedOperationException("getFieldBuilder() called on a non-Message type."); } + @Override public Message.Builder getRepeatedBuilder(GeneratedMessage.Builder builder, int index) { throw new UnsupportedOperationException( - "getRepeatedFieldBuilder() called on a non-Message type."); + "getRepeatedFieldBuilder() called on a non-Message type."); } } @@ -2410,27 +2370,20 @@ public abstract class GeneratedMessage extends AbstractMessage protected final Method clearMethod; RepeatedFieldAccessor( - final FieldDescriptor descriptor, final String camelCaseName, + final FieldDescriptor descriptor, + final String camelCaseName, final Class messageClass, final Class builderClass) { - getMethod = getMethodOrDie(messageClass, - "get" + camelCaseName + "List"); - getMethodBuilder = getMethodOrDie(builderClass, - "get" + camelCaseName + "List"); - getRepeatedMethod = - getMethodOrDie(messageClass, "get" + camelCaseName, Integer.TYPE); + getMethod = getMethodOrDie(messageClass, "get" + camelCaseName + "List"); + getMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName + "List"); + getRepeatedMethod = getMethodOrDie(messageClass, "get" + camelCaseName, Integer.TYPE); getRepeatedMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName, Integer.TYPE); type = getRepeatedMethod.getReturnType(); - setRepeatedMethod = - getMethodOrDie(builderClass, "set" + camelCaseName, - Integer.TYPE, type); - addRepeatedMethod = - getMethodOrDie(builderClass, "add" + camelCaseName, type); - getCountMethod = - getMethodOrDie(messageClass, "get" + camelCaseName + "Count"); - getCountMethodBuilder = - getMethodOrDie(builderClass, "get" + camelCaseName + "Count"); + setRepeatedMethod = getMethodOrDie(builderClass, "set" + camelCaseName, Integer.TYPE, type); + addRepeatedMethod = getMethodOrDie(builderClass, "add" + camelCaseName, type); + getCountMethod = getMethodOrDie(messageClass, "get" + camelCaseName + "Count"); + getCountMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName + "Count"); clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName); } @@ -2439,18 +2392,22 @@ public abstract class GeneratedMessage extends AbstractMessage public Object get(final GeneratedMessage message) { return invokeOrDie(getMethod, message); } + @Override public Object get(GeneratedMessage.Builder builder) { return invokeOrDie(getMethodBuilder, builder); } + @Override public Object getRaw(final GeneratedMessage message) { return get(message); } + @Override public Object getRaw(GeneratedMessage.Builder builder) { return get(builder); } + @Override public void set(final Builder builder, final Object value) { // Add all the elements individually. This serves two purposes: @@ -2462,81 +2419,91 @@ public abstract class GeneratedMessage extends AbstractMessage addRepeated(builder, element); } } + @Override public Object getRepeated(final GeneratedMessage message, final int index) { return invokeOrDie(getRepeatedMethod, message, index); } + @Override public Object getRepeated(GeneratedMessage.Builder builder, int index) { return invokeOrDie(getRepeatedMethodBuilder, builder, index); } + @Override public Object getRepeatedRaw(GeneratedMessage message, int index) { return getRepeated(message, index); } + @Override public Object getRepeatedRaw(GeneratedMessage.Builder builder, int index) { return getRepeated(builder, index); } + @Override public void setRepeated(final Builder builder, final int index, final Object value) { invokeOrDie(setRepeatedMethod, builder, index, value); } + @Override public void addRepeated(final Builder builder, final Object value) { invokeOrDie(addRepeatedMethod, builder, value); } + @Override public boolean has(final GeneratedMessage message) { - throw new UnsupportedOperationException( - "hasField() called on a repeated field."); + throw new UnsupportedOperationException("hasField() called on a repeated field."); } + @Override public boolean has(GeneratedMessage.Builder builder) { - throw new UnsupportedOperationException( - "hasField() called on a repeated field."); + throw new UnsupportedOperationException("hasField() called on a repeated field."); } + @Override public int getRepeatedCount(final GeneratedMessage message) { return (Integer) invokeOrDie(getCountMethod, message); } + @Override public int getRepeatedCount(GeneratedMessage.Builder builder) { return (Integer) invokeOrDie(getCountMethodBuilder, builder); } + @Override public void clear(final Builder builder) { invokeOrDie(clearMethod, builder); } + @Override public Message.Builder newBuilder() { throw new UnsupportedOperationException( - "newBuilderForField() called on a non-Message type."); + "newBuilderForField() called on a non-Message type."); } + @Override public Message.Builder getBuilder(GeneratedMessage.Builder builder) { - throw new UnsupportedOperationException( - "getFieldBuilder() called on a non-Message type."); + throw new UnsupportedOperationException("getFieldBuilder() called on a non-Message type."); } + @Override public Message.Builder getRepeatedBuilder(GeneratedMessage.Builder builder, int index) { throw new UnsupportedOperationException( - "getRepeatedFieldBuilder() called on a non-Message type."); + "getRepeatedFieldBuilder() called on a non-Message type."); } } private static class MapFieldAccessor implements FieldAccessor { MapFieldAccessor( - final FieldDescriptor descriptor, final String camelCaseName, + final FieldDescriptor descriptor, + final String camelCaseName, final Class messageClass, final Class builderClass) { field = descriptor; - Method getDefaultInstanceMethod = - getMethodOrDie(messageClass, "getDefaultInstance"); - MapField defaultMapField = getMapField( - (GeneratedMessage) invokeOrDie(getDefaultInstanceMethod, null)); - mapEntryMessageDefaultInstance = - defaultMapField.getMapEntryMessageDefaultInstance(); + Method getDefaultInstanceMethod = getMethodOrDie(messageClass, "getDefaultInstance"); + MapField defaultMapField = + getMapField((GeneratedMessage) invokeOrDie(getDefaultInstanceMethod, null)); + mapEntryMessageDefaultInstance = defaultMapField.getMapEntryMessageDefaultInstance(); } private final FieldDescriptor field; @@ -2550,10 +2517,8 @@ public abstract class GeneratedMessage extends AbstractMessage return (MapField) builder.internalGetMapField(field.getNumber()); } - private MapField getMutableMapField( - GeneratedMessage.Builder builder) { - return (MapField) builder.internalGetMutableMapField( - field.getNumber()); + private MapField getMutableMapField(GeneratedMessage.Builder builder) { + return (MapField) builder.internalGetMutableMapField(field.getNumber()); } @Override @@ -2626,14 +2591,12 @@ public abstract class GeneratedMessage extends AbstractMessage @Override public boolean has(GeneratedMessage message) { - throw new UnsupportedOperationException( - "hasField() is not supported for repeated fields."); + throw new UnsupportedOperationException("hasField() is not supported for repeated fields."); } @Override public boolean has(Builder builder) { - throw new UnsupportedOperationException( - "hasField() is not supported for repeated fields."); + throw new UnsupportedOperationException("hasField() is not supported for repeated fields."); } @Override @@ -2658,23 +2621,21 @@ public abstract class GeneratedMessage extends AbstractMessage @Override public com.google.protobuf.Message.Builder getBuilder(Builder builder) { - throw new UnsupportedOperationException( - "Nested builder not supported for map fields."); + throw new UnsupportedOperationException("Nested builder not supported for map fields."); } @Override public com.google.protobuf.Message.Builder getRepeatedBuilder(Builder builder, int index) { - throw new UnsupportedOperationException( - "Nested builder not supported for map fields."); + throw new UnsupportedOperationException("Nested builder not supported for map fields."); } } // --------------------------------------------------------------- - private static final class SingularEnumFieldAccessor - extends SingularFieldAccessor { + private static final class SingularEnumFieldAccessor extends SingularFieldAccessor { SingularEnumFieldAccessor( - final FieldDescriptor descriptor, final String camelCaseName, + final FieldDescriptor descriptor, + final String camelCaseName, final Class messageClass, final Class builderClass, final String containingOneofCamelCaseName) { @@ -2682,19 +2643,14 @@ public abstract class GeneratedMessage extends AbstractMessage enumDescriptor = descriptor.getEnumType(); - valueOfMethod = getMethodOrDie(type, "valueOf", - EnumValueDescriptor.class); - getValueDescriptorMethod = - getMethodOrDie(type, "getValueDescriptor"); + valueOfMethod = getMethodOrDie(type, "valueOf", EnumValueDescriptor.class); + getValueDescriptorMethod = getMethodOrDie(type, "getValueDescriptor"); supportUnknownEnumValue = descriptor.getFile().supportsUnknownEnumValue(); if (supportUnknownEnumValue) { - getValueMethod = - getMethodOrDie(messageClass, "get" + camelCaseName + "Value"); - getValueMethodBuilder = - getMethodOrDie(builderClass, "get" + camelCaseName + "Value"); - setValueMethod = - getMethodOrDie(builderClass, "set" + camelCaseName + "Value", int.class); + getValueMethod = getMethodOrDie(messageClass, "get" + camelCaseName + "Value"); + getValueMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName + "Value"); + setValueMethod = getMethodOrDie(builderClass, "set" + camelCaseName + "Value", int.class); } } @@ -2729,28 +2685,25 @@ public abstract class GeneratedMessage extends AbstractMessage @Override public void set(final Builder builder, final Object value) { if (supportUnknownEnumValue) { - invokeOrDie(setValueMethod, builder, - ((EnumValueDescriptor) value).getNumber()); + invokeOrDie(setValueMethod, builder, ((EnumValueDescriptor) value).getNumber()); return; } super.set(builder, invokeOrDie(valueOfMethod, null, value)); } } - private static final class RepeatedEnumFieldAccessor - extends RepeatedFieldAccessor { + private static final class RepeatedEnumFieldAccessor extends RepeatedFieldAccessor { RepeatedEnumFieldAccessor( - final FieldDescriptor descriptor, final String camelCaseName, + final FieldDescriptor descriptor, + final String camelCaseName, final Class messageClass, final Class builderClass) { super(descriptor, camelCaseName, messageClass, builderClass); enumDescriptor = descriptor.getEnumType(); - valueOfMethod = getMethodOrDie(type, "valueOf", - EnumValueDescriptor.class); - getValueDescriptorMethod = - getMethodOrDie(type, "getValueDescriptor"); + valueOfMethod = getMethodOrDie(type, "valueOf", EnumValueDescriptor.class); + getValueDescriptorMethod = getMethodOrDie(type, "getValueDescriptor"); supportUnknownEnumValue = descriptor.getFile().supportsUnknownEnumValue(); if (supportUnknownEnumValue) { @@ -2764,6 +2717,7 @@ public abstract class GeneratedMessage extends AbstractMessage getMethodOrDie(builderClass, "add" + camelCaseName + "Value", int.class); } } + private EnumDescriptor enumDescriptor; private final Method valueOfMethod; @@ -2798,41 +2752,37 @@ public abstract class GeneratedMessage extends AbstractMessage } @Override - public Object getRepeated(final GeneratedMessage message, - final int index) { + public Object getRepeated(final GeneratedMessage message, final int index) { if (supportUnknownEnumValue) { int value = (Integer) invokeOrDie(getRepeatedValueMethod, message, index); return enumDescriptor.findValueByNumberCreatingIfUnknown(value); } - return invokeOrDie(getValueDescriptorMethod, - super.getRepeated(message, index)); + return invokeOrDie(getValueDescriptorMethod, super.getRepeated(message, index)); } + @Override - public Object getRepeated(final GeneratedMessage.Builder builder, - final int index) { + public Object getRepeated(final GeneratedMessage.Builder builder, final int index) { if (supportUnknownEnumValue) { int value = (Integer) invokeOrDie(getRepeatedValueMethodBuilder, builder, index); return enumDescriptor.findValueByNumberCreatingIfUnknown(value); } - return invokeOrDie(getValueDescriptorMethod, - super.getRepeated(builder, index)); + return invokeOrDie(getValueDescriptorMethod, super.getRepeated(builder, index)); } + @Override - public void setRepeated(final Builder builder, - final int index, final Object value) { + public void setRepeated(final Builder builder, final int index, final Object value) { if (supportUnknownEnumValue) { - invokeOrDie(setRepeatedValueMethod, builder, index, - ((EnumValueDescriptor) value).getNumber()); + invokeOrDie( + setRepeatedValueMethod, builder, index, ((EnumValueDescriptor) value).getNumber()); return; } - super.setRepeated(builder, index, invokeOrDie(valueOfMethod, null, - value)); + super.setRepeated(builder, index, invokeOrDie(valueOfMethod, null, value)); } + @Override public void addRepeated(final Builder builder, final Object value) { if (supportUnknownEnumValue) { - invokeOrDie(addRepeatedValueMethod, builder, - ((EnumValueDescriptor) value).getNumber()); + invokeOrDie(addRepeatedValueMethod, builder, ((EnumValueDescriptor) value).getNumber()); return; } super.addRepeated(builder, invokeOrDie(valueOfMethod, null, value)); @@ -2844,29 +2794,25 @@ public abstract class GeneratedMessage extends AbstractMessage /** * Field accessor for string fields. * - *

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

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

This ensures the serialize/parse round-trip safety, which is important - * for servers which forward messages. + *

This ensures the serialize/parse round-trip safety, which is important for servers which + * forward messages. */ - private static final class SingularStringFieldAccessor - extends SingularFieldAccessor { + private static final class SingularStringFieldAccessor extends SingularFieldAccessor { SingularStringFieldAccessor( - final FieldDescriptor descriptor, final String camelCaseName, + final FieldDescriptor descriptor, + final String camelCaseName, final Class messageClass, final Class builderClass, final String containingOneofCamelCaseName) { - super(descriptor, camelCaseName, messageClass, builderClass, - containingOneofCamelCaseName); - getBytesMethod = getMethodOrDie(messageClass, - "get" + camelCaseName + "Bytes"); - getBytesMethodBuilder = getMethodOrDie(builderClass, - "get" + camelCaseName + "Bytes"); - setBytesMethodBuilder = getMethodOrDie(builderClass, - "set" + camelCaseName + "Bytes", ByteString.class); + super(descriptor, camelCaseName, messageClass, builderClass, containingOneofCamelCaseName); + getBytesMethod = getMethodOrDie(messageClass, "get" + camelCaseName + "Bytes"); + getBytesMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName + "Bytes"); + setBytesMethodBuilder = + getMethodOrDie(builderClass, "set" + camelCaseName + "Bytes", ByteString.class); } private final Method getBytesMethod; @@ -2895,19 +2841,17 @@ public abstract class GeneratedMessage extends AbstractMessage // --------------------------------------------------------------- - private static final class SingularMessageFieldAccessor - extends SingularFieldAccessor { + private static final class SingularMessageFieldAccessor extends SingularFieldAccessor { SingularMessageFieldAccessor( - final FieldDescriptor descriptor, final String camelCaseName, + final FieldDescriptor descriptor, + final String camelCaseName, final Class messageClass, final Class builderClass, final String containingOneofCamelCaseName) { - super(descriptor, camelCaseName, messageClass, builderClass, - containingOneofCamelCaseName); + super(descriptor, camelCaseName, messageClass, builderClass, containingOneofCamelCaseName); newBuilderMethod = getMethodOrDie(type, "newBuilder"); - getBuilderMethodBuilder = - getMethodOrDie(builderClass, "get" + camelCaseName + "Builder"); + getBuilderMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName + "Builder"); } private final Method newBuilderMethod; @@ -2922,7 +2866,8 @@ public abstract class GeneratedMessage extends AbstractMessage // DynamicMessage -- we should accept it. In this case we can make // a copy of the message. return ((Message.Builder) invokeOrDie(newBuilderMethod, null)) - .mergeFrom((Message) value).buildPartial(); + .mergeFrom((Message) value) + .buildPartial(); } } @@ -2930,27 +2875,29 @@ public abstract class GeneratedMessage extends AbstractMessage public void set(final Builder builder, final Object value) { super.set(builder, coerceType(value)); } + @Override public Message.Builder newBuilder() { return (Message.Builder) invokeOrDie(newBuilderMethod, null); } + @Override public Message.Builder getBuilder(GeneratedMessage.Builder builder) { return (Message.Builder) invokeOrDie(getBuilderMethodBuilder, builder); } } - private static final class RepeatedMessageFieldAccessor - extends RepeatedFieldAccessor { + private static final class RepeatedMessageFieldAccessor extends RepeatedFieldAccessor { RepeatedMessageFieldAccessor( - final FieldDescriptor descriptor, final String camelCaseName, + final FieldDescriptor descriptor, + final String camelCaseName, final Class messageClass, final Class builderClass) { super(descriptor, camelCaseName, messageClass, builderClass); newBuilderMethod = getMethodOrDie(type, "newBuilder"); - getBuilderMethodBuilder = getMethodOrDie(builderClass, - "get" + camelCaseName + "Builder", Integer.TYPE); + getBuilderMethodBuilder = + getMethodOrDie(builderClass, "get" + camelCaseName + "Builder", Integer.TYPE); } private final Method newBuilderMethod; @@ -2965,36 +2912,39 @@ public abstract class GeneratedMessage extends AbstractMessage // DynamicMessage -- we should accept it. In this case we can make // a copy of the message. return ((Message.Builder) invokeOrDie(newBuilderMethod, null)) - .mergeFrom((Message) value).build(); + .mergeFrom((Message) value) + .build(); } } @Override - public void setRepeated(final Builder builder, - final int index, final Object value) { + public void setRepeated(final Builder builder, final int index, final Object value) { super.setRepeated(builder, index, coerceType(value)); } + @Override public void addRepeated(final Builder builder, final Object value) { super.addRepeated(builder, coerceType(value)); } + @Override public Message.Builder newBuilder() { return (Message.Builder) invokeOrDie(newBuilderMethod, null); } + @Override public Message.Builder getRepeatedBuilder( final GeneratedMessage.Builder builder, final int index) { - return (Message.Builder) invokeOrDie( - getBuilderMethodBuilder, builder, index); + return (Message.Builder) invokeOrDie(getBuilderMethodBuilder, builder, index); } } } /** - * Replaces this object in the output stream with a serialized form. - * Part of Java's serialization magic. Generated sub-classes must override - * this method by calling {@code return super.writeReplace();} + * Replaces this object in the output stream with a serialized form. Part of Java's serialization + * magic. Generated sub-classes must override this method by calling {@code return + * super.writeReplace();} + * * @return a SerializedForm of this message */ protected Object writeReplace() throws ObjectStreamException { @@ -3002,12 +2952,10 @@ public abstract class GeneratedMessage extends AbstractMessage } /** - * Checks that the {@link Extension} is non-Lite and returns it as a - * {@link GeneratedExtension}. + * Checks that the {@link Extension} is non-Lite and returns it as a {@link GeneratedExtension}. */ private static , T> - Extension checkNotLite( - ExtensionLite extension) { + Extension checkNotLite(ExtensionLite extension) { if (extension.isLite()) { throw new IllegalArgumentException("Expected non-lite extension."); } @@ -3040,8 +2988,8 @@ public abstract class GeneratedMessage extends AbstractMessage } } - protected static void writeStringNoTag( - CodedOutputStream output, final Object value) throws IOException { + protected static void writeStringNoTag(CodedOutputStream output, final Object value) + throws IOException { if (value instanceof String) { output.writeStringNoTag((String) value); } else { diff --git a/java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java b/java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java index 16521e1bdd..be6f97de75 100644 --- a/java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java +++ b/java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java @@ -43,7 +43,7 @@ import java.nio.ByteBuffer; * ByteString} can lead to unexpected and undesirable consequences in your application, and will * likely be difficult to debug. Proceed with caution! * - *

This can have a number of significant side affects that have spooky-action-at-a-distance-like + *

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

    diff --git a/java/util/src/main/java/com/google/protobuf/util/FieldMaskUtil.java b/java/util/src/main/java/com/google/protobuf/util/FieldMaskUtil.java index 9f36494a71..55e3079f93 100644 --- a/java/util/src/main/java/com/google/protobuf/util/FieldMaskUtil.java +++ b/java/util/src/main/java/com/google/protobuf/util/FieldMaskUtil.java @@ -101,9 +101,8 @@ public final class FieldMaskUtil { /** * Constructs a FieldMask for a list of field paths in a certain type. * - * @throws IllegalArgumentException if any of the field path is not valid. + * @throws IllegalArgumentException if any of the field path is not valid */ - // TODO(xiaofeng): Consider renaming fromStrings() public static FieldMask fromStringList(Class type, Iterable paths) { return fromStringList(Internal.getDefaultInstance(type).getDescriptorForType(), paths); } diff --git a/python/google/protobuf/__init__.py b/python/google/protobuf/__init__.py index 56781369c2..2c3e06cc1b 100644 --- a/python/google/protobuf/__init__.py +++ b/python/google/protobuf/__init__.py @@ -30,4 +30,4 @@ # Copyright 2007 Google Inc. All Rights Reserved. -__version__ = '4.21.1' +__version__ = '4.21.2' diff --git a/python/google/protobuf/descriptor.py b/python/google/protobuf/descriptor.py index f5a0caa6bd..fa7a5b96d5 100644 --- a/python/google/protobuf/descriptor.py +++ b/python/google/protobuf/descriptor.py @@ -873,11 +873,14 @@ class ServiceDescriptor(_NestedDescriptorBase): Args: name (str): Name of the method. + Returns: - MethodDescriptor or None: the descriptor for the requested method, if - found. + MethodDescriptor: The descriptor for the requested method. + + Raises: + KeyError: if the method cannot be found in the service. """ - return self.methods_by_name.get(name, None) + return self.methods_by_name[name] def CopyToProto(self, proto): """Copies this to a descriptor_pb2.ServiceDescriptorProto. diff --git a/python/google/protobuf/internal/descriptor_test.py b/python/google/protobuf/internal/descriptor_test.py index 6a8532c408..1a0a51ce34 100644 --- a/python/google/protobuf/internal/descriptor_test.py +++ b/python/google/protobuf/internal/descriptor_test.py @@ -118,6 +118,14 @@ class DescriptorTest(unittest.TestCase): def GetDescriptorPool(self): return symbol_database.Default().pool + def testFindMethodByName(self): + service_descriptor = (unittest_custom_options_pb2. + TestServiceWithCustomOptions.DESCRIPTOR) + method_descriptor = service_descriptor.FindMethodByName('Foo') + self.assertEqual(method_descriptor.name, 'Foo') + with self.assertRaises(KeyError): + service_descriptor.FindMethodByName('MethodDoesNotExist') + def testEnumValueName(self): self.assertEqual(self.my_message.EnumValueName('ForeignEnum', 4), 'FOREIGN_FOO') diff --git a/src/Makefile.am b/src/Makefile.am index e10ed063d5..9875b1c575 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -18,7 +18,7 @@ else PTHREAD_DEF = endif -PROTOBUF_VERSION = 32:1:0 +PROTOBUF_VERSION = 32:2:0 if GCC # Turn on all warnings except for sign comparison (we ignore sign comparison diff --git a/src/google/protobuf/any.pb.h b/src/google/protobuf/any.pb.h index 6db2ab3d33..2368446bba 100644 --- a/src/google/protobuf/any.pb.h +++ b/src/google/protobuf/any.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021001 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021002 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/api.pb.h b/src/google/protobuf/api.pb.h index a06f93012d..ac805601ae 100644 --- a/src/google/protobuf/api.pb.h +++ b/src/google/protobuf/api.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021001 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021002 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/arena.cc b/src/google/protobuf/arena.cc index 676cd587e4..a773208fd2 100644 --- a/src/google/protobuf/arena.cc +++ b/src/google/protobuf/arena.cc @@ -153,7 +153,8 @@ void* SerialArena::AllocateAlignedWithCleanupFallback( PROTOBUF_NOINLINE void SerialArena::AddCleanupFallback(void* elem, void (*destructor)(void*), const AllocationPolicy* policy) { - AllocateNewBlock(0, policy); + size_t required = cleanup::Size(destructor); + AllocateNewBlock(required, policy); AddCleanupFromExisting(elem, destructor); } diff --git a/src/google/protobuf/arena_impl.h b/src/google/protobuf/arena_impl.h index 743b62c641..2b71b3c7f1 100644 --- a/src/google/protobuf/arena_impl.h +++ b/src/google/protobuf/arena_impl.h @@ -136,6 +136,7 @@ inline PROTOBUF_ALWAYS_INLINE void CreateNode(Tag tag, void* pos, } inline PROTOBUF_ALWAYS_INLINE void PrefetchNode(const void* elem_address) { + (void)elem_address; } inline PROTOBUF_ALWAYS_INLINE void DestroyNode(Tag tag, const void* pos) { diff --git a/src/google/protobuf/compiler/cpp/field.cc b/src/google/protobuf/compiler/cpp/field.cc index 90d20848b3..cf4f14e8bf 100644 --- a/src/google/protobuf/compiler/cpp/field.cc +++ b/src/google/protobuf/compiler/cpp/field.cc @@ -330,6 +330,7 @@ void FieldGenerator::GenerateCopyConstructorCode(io::Printer* printer) const { } } + void SetCommonOneofFieldVariables( const FieldDescriptor* descriptor, std::map* variables) { diff --git a/src/google/protobuf/compiler/cpp/field.h b/src/google/protobuf/compiler/cpp/field.h index 3fcbda371c..3903e79862 100644 --- a/src/google/protobuf/compiler/cpp/field.h +++ b/src/google/protobuf/compiler/cpp/field.h @@ -208,6 +208,7 @@ class FieldGenerator { virtual bool IsInlined() const { return false; } + virtual ArenaDtorNeeds NeedsArenaDestructor() const { return ArenaDtorNeeds::kNone; } diff --git a/src/google/protobuf/compiler/cpp/helpers.cc b/src/google/protobuf/compiler/cpp/helpers.cc index 4b7c5c9d91..2eb20cf057 100644 --- a/src/google/protobuf/compiler/cpp/helpers.cc +++ b/src/google/protobuf/compiler/cpp/helpers.cc @@ -76,7 +76,8 @@ std::string DotsToColons(const std::string& name) { return StringReplace(name, ".", "::", true); } -static const char* const kKeywordList[] = { // +static const char* const kKeywordList[] = { + // "NULL", "alignas", "alignof", @@ -159,7 +160,21 @@ static const char* const kKeywordList[] = { // "wchar_t", "while", "xor", - "xor_eq"}; + "xor_eq", +#ifdef PROTOBUF_FUTURE_CPP20_KEYWORDS // C++20 keywords. + "char8_t", + "char16_t", + "char32_t", + "concept", + "consteval", + "constinit", + "co_await", + "co_return", + "co_yield", + "requires", +#endif // !PROTOBUF_FUTURE_BREAKING_CHANGES +}; + static std::unordered_set* MakeKeywordsMap() { auto* result = new std::unordered_set(); @@ -509,6 +524,7 @@ std::string FieldName(const FieldDescriptor* field) { return result; } + std::string FieldMemberName(const FieldDescriptor* field, bool split) { StringPiece prefix = IsMapEntryMessage(field->containing_type()) ? "" : "_impl_."; @@ -856,6 +872,7 @@ std::string SafeFunctionName(const Descriptor* descriptor, return function_name; } + bool IsStringInlined(const FieldDescriptor* descriptor, const Options& options) { (void)descriptor; diff --git a/src/google/protobuf/compiler/cpp/message.cc b/src/google/protobuf/compiler/cpp/message.cc index af463d58ac..72fde8308a 100644 --- a/src/google/protobuf/compiler/cpp/message.cc +++ b/src/google/protobuf/compiler/cpp/message.cc @@ -790,38 +790,41 @@ void MessageGenerator::GenerateFieldAccessorDeclarations(io::Printer* printer) { std::map vars; SetCommonFieldVariables(field, &vars, options_); + format.AddMap(vars); - if (field->is_repeated()) { - format("$deprecated_attr$int ${1$$name$_size$}$() const$2$\n", field, - !IsFieldStripped(field, options_) ? ";" : " {__builtin_trap();}"); - if (!IsFieldStripped(field, options_)) { - format( - "private:\n" - "int ${1$_internal_$name$_size$}$() const;\n" - "public:\n", - field); - } - } else if (HasHasMethod(field)) { - format("$deprecated_attr$bool ${1$has_$name$$}$() const$2$\n", field, - !IsFieldStripped(field, options_) ? ";" : " {__builtin_trap();}"); - if (!IsFieldStripped(field, options_)) { + if (field->is_repeated()) { format( - "private:\n" - "bool _internal_has_$name$() const;\n" - "public:\n"); - } - } else if (HasPrivateHasMethod(field)) { - if (!IsFieldStripped(field, options_)) { + "$deprecated_attr$int ${1$$name$_size$}$() const$2$\n", field, + !IsFieldStripped(field, options_) ? ";" : " {__builtin_trap();}"); + if (!IsFieldStripped(field, options_)) { + format( + "private:\n" + "int ${1$_internal_$name$_size$}$() const;\n" + "public:\n", + field); + } + } else if (HasHasMethod(field)) { format( - "private:\n" - "bool ${1$_internal_has_$name$$}$() const;\n" - "public:\n", - field); + "$deprecated_attr$bool ${1$has_$name$$}$() const$2$\n", field, + !IsFieldStripped(field, options_) ? ";" : " {__builtin_trap();}"); + if (!IsFieldStripped(field, options_)) { + format( + "private:\n" + "bool _internal_has_$name$() const;\n" + "public:\n"); + } + } else if (HasPrivateHasMethod(field)) { + if (!IsFieldStripped(field, options_)) { + format( + "private:\n" + "bool ${1$_internal_has_$name$$}$() const;\n" + "public:\n", + field); + } } - } - format("$deprecated_attr$void ${1$clear_$name$$}$()$2$\n", field, - !IsFieldStripped(field, options_) ? ";" : "{__builtin_trap();}"); + format("$deprecated_attr$void ${1$clear_$name$$}$()$2$\n", field, + !IsFieldStripped(field, options_) ? ";" : "{__builtin_trap();}"); // Generate type-specific accessor declarations. field_generators_.get(field).GenerateAccessorDeclarations(printer); @@ -1235,37 +1238,36 @@ void MessageGenerator::GenerateFieldAccessorDefinitions(io::Printer* printer) { Formatter::SaveState saver(&format); format.AddMap(vars); - - // Generate has_$name$() or $name$_size(). - if (field->is_repeated()) { - if (IsFieldStripped(field, options_)) { - format( - "inline int $classname$::$name$_size() const { " - "__builtin_trap(); }\n"); + // Generate has_$name$() or $name$_size(). + if (field->is_repeated()) { + if (IsFieldStripped(field, options_)) { + format( + "inline int $classname$::$name$_size() const { " + "__builtin_trap(); }\n"); + } else { + format( + "inline int $classname$::_internal_$name$_size() const {\n" + " return $field$$1$.size();\n" + "}\n" + "inline int $classname$::$name$_size() const {\n" + "$annotate_size$" + " return _internal_$name$_size();\n" + "}\n", + IsImplicitWeakField(field, options_, scc_analyzer_) && + field->message_type() + ? ".weak" + : ""); + } + } else if (field->real_containing_oneof()) { + format.Set("field_name", UnderscoresToCamelCase(field->name(), true)); + format.Set("oneof_name", field->containing_oneof()->name()); + format.Set("oneof_index", + StrCat(field->containing_oneof()->index())); + GenerateOneofMemberHasBits(field, format); } else { - format( - "inline int $classname$::_internal_$name$_size() const {\n" - " return $field$$1$.size();\n" - "}\n" - "inline int $classname$::$name$_size() const {\n" - "$annotate_size$" - " return _internal_$name$_size();\n" - "}\n", - IsImplicitWeakField(field, options_, scc_analyzer_) && - field->message_type() - ? ".weak" - : ""); + // Singular field. + GenerateSingularFieldHasBits(field, format); } - } else if (field->real_containing_oneof()) { - format.Set("field_name", UnderscoresToCamelCase(field->name(), true)); - format.Set("oneof_name", field->containing_oneof()->name()); - format.Set("oneof_index", - StrCat(field->containing_oneof()->index())); - GenerateOneofMemberHasBits(field, format); - } else { - // Singular field. - GenerateSingularFieldHasBits(field, format); - } if (!IsCrossFileMaybeMap(field)) { GenerateFieldClear(field, true, format); diff --git a/src/google/protobuf/compiler/plugin.pb.h b/src/google/protobuf/compiler/plugin.pb.h index a9a485f046..ad0da1d7f6 100644 --- a/src/google/protobuf/compiler/plugin.pb.h +++ b/src/google/protobuf/compiler/plugin.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021001 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021002 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/descriptor.pb.h b/src/google/protobuf/descriptor.pb.h index 8a23a88f9e..9c5d5e1756 100644 --- a/src/google/protobuf/descriptor.pb.h +++ b/src/google/protobuf/descriptor.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021001 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021002 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/duration.pb.h b/src/google/protobuf/duration.pb.h index 73193eb115..87729c4893 100644 --- a/src/google/protobuf/duration.pb.h +++ b/src/google/protobuf/duration.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021001 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021002 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/empty.pb.h b/src/google/protobuf/empty.pb.h index f5c44b8313..fdc398c3d9 100644 --- a/src/google/protobuf/empty.pb.h +++ b/src/google/protobuf/empty.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021001 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021002 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/field_mask.pb.h b/src/google/protobuf/field_mask.pb.h index f4f77070d0..fd75b88ace 100644 --- a/src/google/protobuf/field_mask.pb.h +++ b/src/google/protobuf/field_mask.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021001 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021002 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/port_def.inc b/src/google/protobuf/port_def.inc index e8791c2227..84620b0b91 100644 --- a/src/google/protobuf/port_def.inc +++ b/src/google/protobuf/port_def.inc @@ -189,6 +189,10 @@ // Used to remove the manipulation of cleared elements in RepeatedPtrField. // Owner: mkruskal@ #define PROTOBUF_FUTURE_REMOVE_CLEARED_API 1 + +// Used to escape C++20 keywords. +// Owner: mkruskal@ +#define PROTOBUF_FUTURE_CPP20_KEYWORDS 1 #else #define PROTOBUF_FUTURE_FINAL #endif @@ -196,7 +200,7 @@ #ifdef PROTOBUF_VERSION #error PROTOBUF_VERSION was previously defined #endif -#define PROTOBUF_VERSION 3021001 +#define PROTOBUF_VERSION 3021002 #ifdef PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC #error PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC was previously defined diff --git a/src/google/protobuf/source_context.pb.h b/src/google/protobuf/source_context.pb.h index 63204f789a..fb2e29f2ea 100644 --- a/src/google/protobuf/source_context.pb.h +++ b/src/google/protobuf/source_context.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021001 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021002 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/struct.pb.h b/src/google/protobuf/struct.pb.h index 1372271768..b026be358d 100644 --- a/src/google/protobuf/struct.pb.h +++ b/src/google/protobuf/struct.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021001 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021002 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/stubs/common.h b/src/google/protobuf/stubs/common.h index 81fb427183..9d90305126 100644 --- a/src/google/protobuf/stubs/common.h +++ b/src/google/protobuf/stubs/common.h @@ -82,7 +82,7 @@ namespace internal { // The current version, represented as a single integer to make comparison // easier: major * 10^6 + minor * 10^3 + micro -#define GOOGLE_PROTOBUF_VERSION 3021001 +#define GOOGLE_PROTOBUF_VERSION 3021002 // A suffix string for alpha, beta or rc releases. Empty for stable releases. #define GOOGLE_PROTOBUF_VERSION_SUFFIX "" diff --git a/src/google/protobuf/test_messages_proto2.proto b/src/google/protobuf/test_messages_proto2.proto index c7b9c487a7..b04d8bb475 100644 --- a/src/google/protobuf/test_messages_proto2.proto +++ b/src/google/protobuf/test_messages_proto2.proto @@ -295,3 +295,9 @@ message EnumOnlyProto2 { message OneStringProto2 { optional string data = 1; } + +message ProtoWithKeywords { + optional int32 inline = 1; + optional string concept = 2; + repeated string requires = 3; +} diff --git a/src/google/protobuf/timestamp.pb.h b/src/google/protobuf/timestamp.pb.h index 7c074c4f05..3b5a469b2e 100644 --- a/src/google/protobuf/timestamp.pb.h +++ b/src/google/protobuf/timestamp.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021001 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021002 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/type.pb.h b/src/google/protobuf/type.pb.h index 83439e9994..bbc1265f8c 100644 --- a/src/google/protobuf/type.pb.h +++ b/src/google/protobuf/type.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021001 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021002 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/wrappers.pb.h b/src/google/protobuf/wrappers.pb.h index 6f549dd97c..72304a56d1 100644 --- a/src/google/protobuf/wrappers.pb.h +++ b/src/google/protobuf/wrappers.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021001 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021002 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc.