diff --git a/benchmarks/util/result_parser.py b/benchmarks/util/result_parser.py index a843923aae..32f35a974c 100755 --- a/benchmarks/util/result_parser.py +++ b/benchmarks/util/result_parser.py @@ -45,9 +45,10 @@ __results = [] # "benchmarks": [ # { # "bytes_per_second": int, -# "cpu_time": int, +# "cpu_time_ns": double, +# "iterations": int, # "name: string, -# "time_unit: string, +# "real_time_ns: double, # ... # }, # ... @@ -75,6 +76,36 @@ def __parse_cpp_result(filename): }) +# Synthetic benchmark results example: +# [ +# "benchmarks": [ +# { +# "cpu_time_ns": double, +# "iterations": int, +# "name: string, +# "real_time_ns: double, +# ... +# }, +# ... +# ], +# ... +# ] +def __parse_synthetic_result(filename): + if filename == "": + return + if filename[0] != "/": + filename = os.path.dirname(os.path.abspath(__file__)) + "/" + filename + with open(filename) as f: + results = json.loads(f.read()) + for benchmark in results["benchmarks"]: + __results.append({ + "language": "cpp", + "dataFilename": "", + "behavior": "synthetic", + "throughput": 10.0**9 / benchmark["cpu_time_ns"] + }) + + # Python results example: # [ # [ @@ -204,7 +235,12 @@ def __parse_go_result(filename): "language": "go" }) -def get_result_from_file(cpp_file="", java_file="", python_file="", go_file=""): + +def get_result_from_file(cpp_file="", + java_file="", + python_file="", + go_file="", + synthetic_file=""): results = {} if cpp_file != "": __parse_cpp_result(cpp_file) @@ -214,5 +250,7 @@ def get_result_from_file(cpp_file="", java_file="", python_file="", go_file=""): __parse_python_result(python_file) if go_file != "": __parse_go_result(go_file) + if synthetic_file != "": + __parse_synthetic_result(synthetic_file) - return __results \ No newline at end of file + return __results diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs index 378b61d4ba..dd9911067e 100644 --- a/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs +++ b/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs @@ -159,7 +159,8 @@ namespace Google.Protobuf.WellKnownTypes { private string typeUrl_ = ""; /// /// A URL/resource name that uniquely identifies the type of the serialized - /// protocol buffer message. The last segment of the URL's path must represent + /// protocol buffer message. This string must contain at least + /// one "/" character. The last segment of the URL's path must represent /// the fully qualified name of the type (as in /// `path/google.protobuf.Duration`). The name should be in a canonical form /// (e.g., leading "." is not accepted). diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs index ef752be7cb..d1ab0f8965 100644 --- a/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs +++ b/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs @@ -116,7 +116,7 @@ namespace Google.Protobuf.WellKnownTypes { /// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) /// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one /// can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( - /// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime-- + /// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D /// ) to obtain a formatter capable of generating timestamps in this format. /// public sealed partial class Timestamp : pb::IMessage { diff --git a/generate_descriptor_proto.sh b/generate_descriptor_proto.sh index 8a5ed48a2b..e533d05b43 100755 --- a/generate_descriptor_proto.sh +++ b/generate_descriptor_proto.sh @@ -18,14 +18,6 @@ __EOF__ exit 1 fi -if test ! -e src/Makefile; then - cat >&2 << __EOF__ -Could not find src/Makefile. You must run ./configure (and perhaps -./autogen.sh) first. -__EOF__ - exit 1 -fi - cd src declare -a RUNTIME_PROTO_FILES=(\ @@ -51,7 +43,7 @@ while [ $# -gt 0 ]; do case $1 in --bootstrap_protoc) BOOTSTRAP_PROTOC=$2 - shift + shift 2 ;; *) break @@ -78,8 +70,8 @@ do PROTOC="./protoc" fi - $PROTOC --cpp_out=dllexport_decl=LIBPROTOBUF_EXPORT:$TMP ${RUNTIME_PROTO_FILES[@]} && \ - $PROTOC --cpp_out=dllexport_decl=LIBPROTOC_EXPORT:$TMP ${COMPILER_PROTO_FILES[@]} + $PROTOC --cpp_out=dllexport_decl=PROTOBUF_EXPORT:$TMP ${RUNTIME_PROTO_FILES[@]} && \ + $PROTOC --cpp_out=dllexport_decl=PROTOC_EXPORT:$TMP ${COMPILER_PROTO_FILES[@]} for PROTO_FILE in ${RUNTIME_PROTO_FILES[@]} ${COMPILER_PROTO_FILES[@]}; do BASE_NAME=${PROTO_FILE%.*} diff --git a/java/core/src/main/java/com/google/protobuf/AbstractMessage.java b/java/core/src/main/java/com/google/protobuf/AbstractMessage.java index 09aaed18a4..fe1bebc77b 100644 --- a/java/core/src/main/java/com/google/protobuf/AbstractMessage.java +++ b/java/core/src/main/java/com/google/protobuf/AbstractMessage.java @@ -44,15 +44,14 @@ import java.util.List; import java.util.Map; /** - * A partial implementation of the {@link Message} interface which implements - * as many methods of that interface as possible in terms of other methods. + * A partial implementation of the {@link Message} interface which implements as many methods of + * that interface as possible in terms of other methods. * * @author kenton@google.com Kenton Varda */ public abstract class AbstractMessage // TODO(dweis): Update GeneratedMessage to parameterize with MessageType and BuilderType. - extends AbstractMessageLite - implements Message { + extends AbstractMessageLite implements Message { @Override public boolean isInitialized() { @@ -60,24 +59,21 @@ public abstract class AbstractMessage } /** - * Interface for the parent of a Builder that allows the builder to - * communicate invalidations back to the parent for use when using nested - * builders. + * Interface for the parent of a Builder that allows the builder to communicate invalidations back + * to the parent for use when using nested builders. */ protected interface BuilderParent { /** - * A builder becomes dirty whenever a field is modified -- including fields - * in nested builders -- and becomes clean when build() is called. Thus, - * when a builder becomes dirty, all its parents become dirty as well, and - * when it becomes clean, all its children become clean. The dirtiness - * state is used to invalidate certain cached values. - *
- * To this end, a builder calls markDirty() on its parent whenever it - * transitions from clean to dirty. The parent must propagate this call to - * its own parent, unless it was already dirty, in which case the - * grandparent must necessarily already be dirty as well. The parent can - * only transition back to "clean" after calling build() on all children. + * A builder becomes dirty whenever a field is modified -- including fields in nested builders + * -- and becomes clean when build() is called. Thus, when a builder becomes dirty, all its + * parents become dirty as well, and when it becomes clean, all its children become clean. The + * dirtiness state is used to invalidate certain cached values. + * + *

To this end, a builder calls markDirty() on its parent whenever it transitions from clean + * to dirty. The parent must propagate this call to its own parent, unless it was already dirty, + * in which case the grandparent must necessarily already be dirty as well. The parent can only + * transition back to "clean" after calling build() on all children. */ void markDirty(); } @@ -107,8 +103,7 @@ public abstract class AbstractMessage /** TODO(jieluo): Clear it when all subclasses have implemented this method. */ @Override public FieldDescriptor getOneofFieldDescriptor(OneofDescriptor oneof) { - throw new UnsupportedOperationException( - "getOneofFieldDescriptor() is not implemented."); + throw new UnsupportedOperationException("getOneofFieldDescriptor() is not implemented."); } @Override @@ -156,8 +151,8 @@ public abstract class AbstractMessage if (getDescriptorForType() != otherMessage.getDescriptorForType()) { return false; } - return compareFields(getAllFields(), otherMessage.getAllFields()) && - getUnknownFields().equals(otherMessage.getUnknownFields()); + return compareFields(getAllFields(), otherMessage.getAllFields()) + && getUnknownFields().equals(otherMessage.getUnknownFields()); } @Override @@ -182,20 +177,17 @@ public abstract class AbstractMessage } /** - * Compares two bytes fields. The parameters must be either a byte array or a - * ByteString object. They can be of different type though. + * Compares two bytes fields. The parameters must be either a byte array or a ByteString object. + * They can be of different type though. */ private static boolean compareBytes(Object a, Object b) { if (a instanceof byte[] && b instanceof byte[]) { - return Arrays.equals((byte[])a, (byte[])b); + return Arrays.equals((byte[]) a, (byte[]) b); } return toByteString(a).equals(toByteString(b)); } - /** - * Converts a list of MapEntry messages into a Map used for equals() and - * hashCode(). - */ + /** Converts a list of MapEntry messages into a Map used for equals() and hashCode(). */ @SuppressWarnings({"rawtypes", "unchecked"}) private static Map convertMapEntryListToMap(List list) { if (list.isEmpty()) { @@ -223,10 +215,7 @@ public abstract class AbstractMessage return result; } - /** - * Compares two map fields. The parameters must be a list of MapEntry - * messages. - */ + /** Compares two map fields. The parameters must be a list of MapEntry messages. */ @SuppressWarnings({"rawtypes", "unchecked"}) private static boolean compareMapField(Object a, Object b) { Map ma = convertMapEntryListToMap((List) a); @@ -235,16 +224,13 @@ public abstract class AbstractMessage } /** - * Compares two set of fields. - * This method is used to implement {@link AbstractMessage#equals(Object)} - * and {@link AbstractMutableMessage#equals(Object)}. It takes special care - * of bytes fields because immutable messages and mutable messages use - * different Java type to represent a bytes field and this method should be - * able to compare immutable messages, mutable messages and also an immutable - * message to a mutable message. + * Compares two set of fields. This method is used to implement {@link + * AbstractMessage#equals(Object)} and {@link AbstractMutableMessage#equals(Object)}. It takes + * special care of bytes fields because immutable messages and mutable messages use different Java + * type to represent a bytes field and this method should be able to compare immutable messages, + * mutable messages and also an immutable message to a mutable message. */ - static boolean compareFields(Map a, - Map b) { + static boolean compareFields(Map a, Map b) { if (a.size() != b.size()) { return false; } @@ -286,10 +272,7 @@ public abstract class AbstractMessage return true; } - /** - * Calculates the hash code of a map field. {@code value} must be a list of - * MapEntry messages. - */ + /** Calculates the hash code of a map field. {@code value} must be a list of MapEntry messages. */ @SuppressWarnings("unchecked") private static int hashMapField(Object value) { return MapFieldLite.calculateHashCodeForMap(convertMapEntryListToMap((List) value)); @@ -304,7 +287,7 @@ public abstract class AbstractMessage hash = (37 * hash) + field.getNumber(); if (field.isMapField()) { hash = (53 * hash) + hashMapField(value); - } else if (field.getType() != FieldDescriptor.Type.ENUM){ + } else if (field.getType() != FieldDescriptor.Type.ENUM) { hash = (53 * hash) + value.hashCode(); } else if (field.isRepeated()) { List list = (List) value; @@ -317,8 +300,8 @@ public abstract class AbstractMessage } /** - * Package private helper method for AbstractParser to create - * UninitializedMessageException with missing field information. + * Package private helper method for AbstractParser to create UninitializedMessageException with + * missing field information. */ @Override UninitializedMessageException newUninitializedMessageException() { @@ -328,14 +311,12 @@ public abstract class AbstractMessage // ================================================================= /** - * A partial implementation of the {@link Message.Builder} interface which - * implements as many methods of that interface as possible in terms of - * other methods. + * A partial implementation of the {@link Message.Builder} interface which implements as many + * methods of that interface as possible in terms of other methods. */ @SuppressWarnings("unchecked") - public static abstract class Builder> - extends AbstractMessageLite.Builder - implements Message.Builder { + public abstract static class Builder> + extends AbstractMessageLite.Builder implements Message.Builder { // The compiler produces an error if this is not declared explicitly. // Method isn't abstract to bypass Java 1.6 compiler issue: // http://bugs.java.com/view_bug.do?bug_id=6908259 @@ -353,8 +334,7 @@ public abstract class AbstractMessage /** TODO(jieluo): Clear it when all subclasses have implemented this method. */ @Override public FieldDescriptor getOneofFieldDescriptor(OneofDescriptor oneof) { - throw new UnsupportedOperationException( - "getOneofFieldDescriptor() is not implemented."); + throw new UnsupportedOperationException("getOneofFieldDescriptor() is not implemented."); } /** TODO(jieluo): Clear it when all subclasses have implemented this method. */ @@ -365,8 +345,7 @@ public abstract class AbstractMessage @Override public BuilderType clear() { - for (final Map.Entry entry : - getAllFields().entrySet()) { + for (final Map.Entry entry : getAllFields().entrySet()) { clearField(entry.getKey()); } return (BuilderType) this; @@ -391,11 +370,11 @@ public abstract class AbstractMessage public BuilderType mergeFrom(final Message other) { return mergeFrom(other, other.getAllFields()); } - + BuilderType mergeFrom(final Message other, Map allFields) { if (other.getDescriptorForType() != getDescriptorForType()) { throw new IllegalArgumentException( - "mergeFrom(Message) can only merge messages of the same type."); + "mergeFrom(Message) can only merge messages of the same type."); } // Note: We don't attempt to verify that other's fields have valid @@ -410,19 +389,21 @@ public abstract class AbstractMessage for (final Map.Entry entry : allFields.entrySet()) { final FieldDescriptor field = entry.getKey(); if (field.isRepeated()) { - for (final Object element : (List)entry.getValue()) { + for (final Object element : (List) entry.getValue()) { addRepeatedField(field, element); } } else if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { - final Message existingValue = (Message)getField(field); + final Message existingValue = (Message) getField(field); if (existingValue == existingValue.getDefaultInstanceForType()) { setField(field, entry.getValue()); } else { - setField(field, - existingValue.newBuilderForType() - .mergeFrom(existingValue) - .mergeFrom((Message)entry.getValue()) - .build()); + setField( + field, + existingValue + .newBuilderForType() + .mergeFrom(existingValue) + .mergeFrom((Message) entry.getValue()) + .build()); } } else { setField(field, entry.getValue()); @@ -435,15 +416,13 @@ public abstract class AbstractMessage } @Override - public BuilderType mergeFrom(final CodedInputStream input) - throws IOException { + public BuilderType mergeFrom(final CodedInputStream input) throws IOException { return mergeFrom(input, ExtensionRegistry.getEmptyRegistry()); } @Override public BuilderType mergeFrom( - final CodedInputStream input, - final ExtensionRegistryLite extensionRegistry) + final CodedInputStream input, final ExtensionRegistryLite extensionRegistry) throws IOException { boolean discardUnknown = input.shouldDiscardUnknownFields(); final UnknownFieldSet.Builder unknownFields = @@ -456,11 +435,8 @@ public abstract class AbstractMessage MessageReflection.BuilderAdapter builderAdapter = new MessageReflection.BuilderAdapter(this); - if (!MessageReflection.mergeFieldFrom(input, unknownFields, - extensionRegistry, - getDescriptorForType(), - builderAdapter, - tag)) { + if (!MessageReflection.mergeFieldFrom( + input, unknownFields, extensionRegistry, getDescriptorForType(), builderAdapter, tag)) { // end group tag break; } @@ -474,9 +450,7 @@ public abstract class AbstractMessage @Override public BuilderType mergeUnknownFields(final UnknownFieldSet unknownFields) { setUnknownFields( - UnknownFieldSet.newBuilder(getUnknownFields()) - .mergeFrom(unknownFields) - .build()); + UnknownFieldSet.newBuilder(getUnknownFields()).mergeFrom(unknownFields).build()); return (BuilderType) this; } @@ -497,36 +471,30 @@ public abstract class AbstractMessage return TextFormat.printToString(this); } - /** - * Construct an UninitializedMessageException reporting missing fields in - * the given message. - */ - protected static UninitializedMessageException - newUninitializedMessageException(Message message) { - return new UninitializedMessageException( - MessageReflection.findMissingFields(message)); + /** Construct an UninitializedMessageException reporting missing fields in the given message. */ + protected static UninitializedMessageException newUninitializedMessageException( + Message message) { + return new UninitializedMessageException(MessageReflection.findMissingFields(message)); } /** - * Used to support nested builders and called to mark this builder as clean. - * Clean builders will propagate the {@link BuilderParent#markDirty()} event - * to their parent builders, while dirty builders will not, as their parents - * should be dirty already. + * Used to support nested builders and called to mark this builder as clean. Clean builders will + * propagate the {@link BuilderParent#markDirty()} event to their parent builders, while dirty + * builders will not, as their parents should be dirty already. * - * NOTE: Implementations that don't support nested builders don't need to - * override this method. + *

NOTE: Implementations that don't support nested builders don't need to override this + * method. */ void markClean() { throw new IllegalStateException("Should be overridden by subclasses."); } /** - * Used to support nested builders and called when this nested builder is - * no longer used by its parent builder and should release the reference - * to its parent builder. + * Used to support nested builders and called when this nested builder is no longer used by its + * parent builder and should release the reference to its parent builder. * - * NOTE: Implementations that don't support nested builders don't need to - * override this method. + *

NOTE: Implementations that don't support nested builders don't need to override this + * method. */ void dispose() { throw new IllegalStateException("Should be overridden by subclasses."); @@ -552,73 +520,63 @@ public abstract class AbstractMessage // bug. @Override - public BuilderType mergeFrom(final ByteString data) - throws InvalidProtocolBufferException { + public BuilderType mergeFrom(final ByteString data) throws InvalidProtocolBufferException { return (BuilderType) super.mergeFrom(data); } @Override public BuilderType mergeFrom( - final ByteString data, - final ExtensionRegistryLite extensionRegistry) + final ByteString data, final ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { return (BuilderType) super.mergeFrom(data, extensionRegistry); } @Override - public BuilderType mergeFrom(final byte[] data) - throws InvalidProtocolBufferException { + public BuilderType mergeFrom(final byte[] data) throws InvalidProtocolBufferException { return (BuilderType) super.mergeFrom(data); } @Override - public BuilderType mergeFrom( - final byte[] data, final int off, final int len) + public BuilderType mergeFrom(final byte[] data, final int off, final int len) throws InvalidProtocolBufferException { return (BuilderType) super.mergeFrom(data, off, len); } @Override - public BuilderType mergeFrom( - final byte[] data, - final ExtensionRegistryLite extensionRegistry) + public BuilderType mergeFrom(final byte[] data, final ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { return (BuilderType) super.mergeFrom(data, extensionRegistry); } @Override public BuilderType mergeFrom( - final byte[] data, final int off, final int len, + final byte[] data, + final int off, + final int len, final ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { return (BuilderType) super.mergeFrom(data, off, len, extensionRegistry); } @Override - public BuilderType mergeFrom(final InputStream input) - throws IOException { + public BuilderType mergeFrom(final InputStream input) throws IOException { return (BuilderType) super.mergeFrom(input); } @Override public BuilderType mergeFrom( - final InputStream input, - final ExtensionRegistryLite extensionRegistry) - throws IOException { + final InputStream input, final ExtensionRegistryLite extensionRegistry) throws IOException { return (BuilderType) super.mergeFrom(input, extensionRegistry); } @Override - public boolean mergeDelimitedFrom(final InputStream input) - throws IOException { + public boolean mergeDelimitedFrom(final InputStream input) throws IOException { return super.mergeDelimitedFrom(input); } @Override public boolean mergeDelimitedFrom( - final InputStream input, - final ExtensionRegistryLite extensionRegistry) - throws IOException { + final InputStream input, final ExtensionRegistryLite extensionRegistry) throws IOException { return super.mergeDelimitedFrom(input, extensionRegistry); } } diff --git a/java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java b/java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java index b22bbaab62..1720575099 100644 --- a/java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java +++ b/java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java @@ -41,22 +41,20 @@ import java.util.Collection; import java.util.List; /** - * A partial implementation of the {@link MessageLite} interface which - * implements as many methods of that interface as possible in terms of other - * methods. + * A partial implementation of the {@link MessageLite} interface which implements as many methods of + * that interface as possible in terms of other methods. * * @author kenton@google.com Kenton Varda */ public abstract class AbstractMessageLite< - MessageType extends AbstractMessageLite, - BuilderType extends AbstractMessageLite.Builder> - implements MessageLite { + MessageType extends AbstractMessageLite, + BuilderType extends AbstractMessageLite.Builder> + implements MessageLite { protected int memoizedHashCode = 0; @Override public ByteString toByteString() { try { - final ByteString.CodedBuilder out = - ByteString.newCodedBuilder(getSerializedSize()); + final ByteString.CodedBuilder out = ByteString.newCodedBuilder(getSerializedSize()); writeTo(out.getCodedOutput()); return out.build(); } catch (IOException e) { @@ -79,10 +77,8 @@ public abstract class AbstractMessageLite< @Override public void writeTo(final OutputStream output) throws IOException { - final int bufferSize = - CodedOutputStream.computePreferredBufferSize(getSerializedSize()); - final CodedOutputStream codedOutput = - CodedOutputStream.newInstance(output, bufferSize); + final int bufferSize = CodedOutputStream.computePreferredBufferSize(getSerializedSize()); + final CodedOutputStream codedOutput = CodedOutputStream.newInstance(output, bufferSize); writeTo(codedOutput); codedOutput.flush(); } @@ -90,10 +86,10 @@ public abstract class AbstractMessageLite< @Override public void writeDelimitedTo(final OutputStream output) throws IOException { final int serialized = getSerializedSize(); - final int bufferSize = CodedOutputStream.computePreferredBufferSize( - CodedOutputStream.computeRawVarint32Size(serialized) + serialized); - final CodedOutputStream codedOutput = - CodedOutputStream.newInstance(output, bufferSize); + final int bufferSize = + CodedOutputStream.computePreferredBufferSize( + CodedOutputStream.computeRawVarint32Size(serialized) + serialized); + final CodedOutputStream codedOutput = CodedOutputStream.newInstance(output, bufferSize); codedOutput.writeRawVarint32(serialized); writeTo(codedOutput); codedOutput.flush(); @@ -110,16 +106,16 @@ public abstract class AbstractMessageLite< } - /** - * Package private helper method for AbstractParser to create - * UninitializedMessageException. - */ + /** Package private helper method for AbstractParser to create UninitializedMessageException. */ UninitializedMessageException newUninitializedMessageException() { return new UninitializedMessageException(this); } private String getSerializingExceptionMessage(String target) { - return "Serializing " + getClass().getName() + " to a " + target + return "Serializing " + + getClass().getName() + + " to a " + + target + " threw an IOException (should never happen)."; } @@ -141,14 +137,13 @@ public abstract class AbstractMessageLite< } /** - * A partial implementation of the {@link Message.Builder} interface which - * implements as many methods of that interface as possible in terms of - * other methods. + * A partial implementation of the {@link Message.Builder} interface which implements as many + * methods of that interface as possible in terms of other methods. */ @SuppressWarnings("unchecked") public abstract static class Builder< - MessageType extends AbstractMessageLite, - BuilderType extends Builder> + MessageType extends AbstractMessageLite, + BuilderType extends Builder> implements MessageLite.Builder { // The compiler produces an error if this is not declared explicitly. @Override @@ -204,8 +199,7 @@ public abstract class AbstractMessageLite< public BuilderType mergeFrom(final byte[] data, final int off, final int len) throws InvalidProtocolBufferException { try { - final CodedInputStream input = - CodedInputStream.newInstance(data, off, len); + final CodedInputStream input = CodedInputStream.newInstance(data, off, len); mergeFrom(input); input.checkLastTagWas(0); return (BuilderType) this; @@ -230,8 +224,7 @@ public abstract class AbstractMessageLite< final ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { try { - final CodedInputStream input = - CodedInputStream.newInstance(data, off, len); + final CodedInputStream input = CodedInputStream.newInstance(data, off, len); mergeFrom(input, extensionRegistry); input.checkLastTagWas(0); return (BuilderType) this; @@ -260,10 +253,9 @@ public abstract class AbstractMessageLite< } /** - * An InputStream implementations which reads from some other InputStream - * but is limited to a particular number of bytes. Used by - * mergeDelimitedFrom(). This is intentionally package-private so that - * UnknownFieldSet can share it. + * An InputStream implementations which reads from some other InputStream but is limited to a + * particular number of bytes. Used by mergeDelimitedFrom(). This is intentionally + * package-private so that UnknownFieldSet can share it. */ static final class LimitedInputStream extends FilterInputStream { private int limit; @@ -291,8 +283,7 @@ public abstract class AbstractMessageLite< } @Override - public int read(final byte[] b, final int off, int len) - throws IOException { + public int read(final byte[] b, final int off, int len) throws IOException { if (limit <= 0) { return -1; } @@ -329,8 +320,7 @@ public abstract class AbstractMessageLite< @Override public boolean mergeDelimitedFrom(final InputStream input) throws IOException { - return mergeDelimitedFrom(input, - ExtensionRegistryLite.getEmptyRegistry()); + return mergeDelimitedFrom(input, ExtensionRegistryLite.getEmptyRegistry()); } @Override @@ -347,7 +337,10 @@ public abstract class AbstractMessageLite< protected abstract BuilderType internalMergeFrom(MessageType message); private String getReadingExceptionMessage(String target) { - return "Reading " + getClass().getName() + " from a " + target + return "Reading " + + getClass().getName() + + " from a " + + target + " threw an IOException (should never happen)."; } @@ -370,12 +363,9 @@ public abstract class AbstractMessageLite< } } - /** - * Construct an UninitializedMessageException reporting missing fields in - * the given message. - */ - protected static UninitializedMessageException - newUninitializedMessageException(MessageLite message) { + /** Construct an UninitializedMessageException reporting missing fields in the given message. */ + protected static UninitializedMessageException newUninitializedMessageException( + MessageLite message) { return new UninitializedMessageException(message); } diff --git a/java/core/src/main/java/com/google/protobuf/AbstractParser.java b/java/core/src/main/java/com/google/protobuf/AbstractParser.java index ba570e3df1..abfaca8cd8 100644 --- a/java/core/src/main/java/com/google/protobuf/AbstractParser.java +++ b/java/core/src/main/java/com/google/protobuf/AbstractParser.java @@ -36,23 +36,19 @@ import java.io.InputStream; import java.nio.ByteBuffer; /** - * A partial implementation of the {@link Parser} interface which implements - * as many methods of that interface as possible in terms of other methods. + * A partial implementation of the {@link Parser} interface which implements as many methods of that + * interface as possible in terms of other methods. * - * Note: This class implements all the convenience methods in the - * {@link Parser} interface. See {@link Parser} for related javadocs. - * Subclasses need to implement - * {@link Parser#parsePartialFrom(CodedInputStream, ExtensionRegistryLite)} + *

Note: This class implements all the convenience methods in the {@link Parser} interface. See + * {@link Parser} for related javadocs. Subclasses need to implement {@link + * Parser#parsePartialFrom(CodedInputStream, ExtensionRegistryLite)} * * @author liujisi@google.com (Pherl Liu) */ public abstract class AbstractParser implements Parser { - /** - * Creates an UninitializedMessageException for MessageType. - */ - private UninitializedMessageException - newUninitializedMessageException(MessageType message) { + /** Creates an UninitializedMessageException for MessageType. */ + private UninitializedMessageException newUninitializedMessageException(MessageType message) { if (message instanceof AbstractMessageLite) { return ((AbstractMessageLite) message).newUninitializedMessageException(); } @@ -75,8 +71,8 @@ public abstract class AbstractParser return message; } - private static final ExtensionRegistryLite EMPTY_REGISTRY - = ExtensionRegistryLite.getEmptyRegistry(); + private static final ExtensionRegistryLite EMPTY_REGISTRY = + ExtensionRegistryLite.getEmptyRegistry(); @Override public MessageType parsePartialFrom(CodedInputStream input) @@ -87,8 +83,7 @@ public abstract class AbstractParser @Override public MessageType parseFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { - return checkMessageInitialized( - parsePartialFrom(input, extensionRegistry)); + return checkMessageInitialized(parsePartialFrom(input, extensionRegistry)); } @Override @@ -193,8 +188,7 @@ public abstract class AbstractParser public MessageType parseFrom( byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { - return checkMessageInitialized( - parsePartialFrom(data, off, len, extensionRegistry)); + return checkMessageInitialized(parsePartialFrom(data, off, len, extensionRegistry)); } @Override @@ -235,8 +229,7 @@ public abstract class AbstractParser @Override public MessageType parseFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { - return checkMessageInitialized( - parsePartialFrom(input, extensionRegistry)); + return checkMessageInitialized(parsePartialFrom(input, extensionRegistry)); } @Override @@ -271,8 +264,7 @@ public abstract class AbstractParser @Override public MessageType parseDelimitedFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { - return checkMessageInitialized( - parsePartialDelimitedFrom(input, extensionRegistry)); + return checkMessageInitialized(parsePartialDelimitedFrom(input, extensionRegistry)); } @Override diff --git a/java/core/src/main/java/com/google/protobuf/AbstractProtobufList.java b/java/core/src/main/java/com/google/protobuf/AbstractProtobufList.java index b17db6e0b3..3220f64072 100644 --- a/java/core/src/main/java/com/google/protobuf/AbstractProtobufList.java +++ b/java/core/src/main/java/com/google/protobuf/AbstractProtobufList.java @@ -31,7 +31,6 @@ package com.google.protobuf; import com.google.protobuf.Internal.ProtobufList; - import java.util.AbstractList; import java.util.Collection; import java.util.List; @@ -39,23 +38,19 @@ import java.util.RandomAccess; /** * An abstract implementation of {@link ProtobufList} which manages mutability semantics. All mutate - * methods must check if the list is mutable before proceeding. Subclasses must invoke - * {@link #ensureIsMutable()} manually when overriding those methods. - *

- * This implementation assumes all subclasses are array based, supporting random access. + * methods must check if the list is mutable before proceeding. Subclasses must invoke {@link + * #ensureIsMutable()} manually when overriding those methods. + * + *

This implementation assumes all subclasses are array based, supporting random access. */ abstract class AbstractProtobufList extends AbstractList implements ProtobufList { protected static final int DEFAULT_CAPACITY = 10; - /** - * Whether or not this list is modifiable. - */ + /** Whether or not this list is modifiable. */ private boolean isMutable; - /** - * Constructs a mutable list by default. - */ + /** Constructs a mutable list by default. */ AbstractProtobufList() { isMutable = true; } @@ -115,7 +110,7 @@ abstract class AbstractProtobufList extends AbstractList implements Protob ensureIsMutable(); return super.addAll(c); } - + @Override public boolean addAll(int index, Collection c) { ensureIsMutable(); @@ -127,47 +122,47 @@ abstract class AbstractProtobufList extends AbstractList implements Protob ensureIsMutable(); super.clear(); } - + @Override public boolean isModifiable() { return isMutable; } - + @Override public final void makeImmutable() { isMutable = false; } - + @Override public E remove(int index) { ensureIsMutable(); return super.remove(index); } - + @Override public boolean remove(Object o) { ensureIsMutable(); return super.remove(o); } - + @Override public boolean removeAll(Collection c) { ensureIsMutable(); return super.removeAll(c); } - + @Override public boolean retainAll(Collection c) { ensureIsMutable(); return super.retainAll(c); } - + @Override public E set(int index, E element) { ensureIsMutable(); return super.set(index, element); } - + /** * Throws an {@link UnsupportedOperationException} if the list is immutable. Subclasses are * responsible for invoking this method on mutate operations. diff --git a/java/core/src/main/java/com/google/protobuf/BlockingRpcChannel.java b/java/core/src/main/java/com/google/protobuf/BlockingRpcChannel.java index d535efb9b6..8af80057f3 100644 --- a/java/core/src/main/java/com/google/protobuf/BlockingRpcChannel.java +++ b/java/core/src/main/java/com/google/protobuf/BlockingRpcChannel.java @@ -31,21 +31,21 @@ package com.google.protobuf; /** - *

Abstract interface for a blocking RPC channel. {@code BlockingRpcChannel} - * is the blocking equivalent to {@link RpcChannel}. + * Abstract interface for a blocking RPC channel. {@code BlockingRpcChannel} is the blocking + * equivalent to {@link RpcChannel}. * * @author kenton@google.com Kenton Varda * @author cpovirk@google.com Chris Povirk */ public interface BlockingRpcChannel { /** - * Call the given method of the remote service and blocks until it returns. - * {@code callBlockingMethod()} is the blocking equivalent to - * {@link RpcChannel#callMethod}. + * Call the given method of the remote service and blocks until it returns. {@code + * callBlockingMethod()} is the blocking equivalent to {@link RpcChannel#callMethod}. */ Message callBlockingMethod( Descriptors.MethodDescriptor method, RpcController controller, Message request, - Message responsePrototype) throws ServiceException; + Message responsePrototype) + throws ServiceException; } diff --git a/java/core/src/main/java/com/google/protobuf/BlockingService.java b/java/core/src/main/java/com/google/protobuf/BlockingService.java index d01f0b8ff0..e2b99c96c3 100644 --- a/java/core/src/main/java/com/google/protobuf/BlockingService.java +++ b/java/core/src/main/java/com/google/protobuf/BlockingService.java @@ -37,28 +37,21 @@ package com.google.protobuf; * @author cpovirk@google.com Chris Povirk */ public interface BlockingService { - /** - * Equivalent to {@link Service#getDescriptorForType}. - */ + /** Equivalent to {@link Service#getDescriptorForType}. */ Descriptors.ServiceDescriptor getDescriptorForType(); /** - * Equivalent to {@link Service#callMethod}, except that - * {@code callBlockingMethod()} returns the result of the RPC or throws a - * {@link ServiceException} if there is a failure, rather than passing the - * information to a callback. + * Equivalent to {@link Service#callMethod}, except that {@code callBlockingMethod()} returns the + * result of the RPC or throws a {@link ServiceException} if there is a failure, rather than + * passing the information to a callback. */ - Message callBlockingMethod(Descriptors.MethodDescriptor method, - RpcController controller, - Message request) throws ServiceException; + Message callBlockingMethod( + Descriptors.MethodDescriptor method, RpcController controller, Message request) + throws ServiceException; - /** - * Equivalent to {@link Service#getRequestPrototype}. - */ + /** Equivalent to {@link Service#getRequestPrototype}. */ Message getRequestPrototype(Descriptors.MethodDescriptor method); - /** - * Equivalent to {@link Service#getResponsePrototype}. - */ + /** Equivalent to {@link Service#getResponsePrototype}. */ Message getResponsePrototype(Descriptors.MethodDescriptor method); } diff --git a/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java b/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java index 0dedb173c9..2c8929e5e4 100644 --- a/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java +++ b/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java @@ -42,11 +42,11 @@ import java.util.RandomAccess; * * @author dweis@google.com (Daniel Weis) */ -final class BooleanArrayList - extends AbstractProtobufList +final class BooleanArrayList extends AbstractProtobufList implements BooleanList, RandomAccess, PrimitiveNonBoxingCollection { private static final BooleanArrayList EMPTY_LIST = new BooleanArrayList(); + static { EMPTY_LIST.makeImmutable(); } @@ -55,9 +55,7 @@ final class BooleanArrayList return EMPTY_LIST; } - /** - * The backing store for the list. - */ + /** The backing store for the list. */ private boolean[] array; /** @@ -66,16 +64,14 @@ final class BooleanArrayList */ private int size; - /** - * Constructs a new mutable {@code BooleanArrayList} with default capacity. - */ + /** Constructs a new mutable {@code BooleanArrayList} with default capacity. */ BooleanArrayList() { this(new boolean[DEFAULT_CAPACITY], 0); } /** - * Constructs a new mutable {@code BooleanArrayList} - * containing the same elements as {@code other}. + * Constructs a new mutable {@code BooleanArrayList} containing the same elements as {@code + * other}. */ private BooleanArrayList(boolean[] other, int size) { array = other; @@ -169,17 +165,13 @@ final class BooleanArrayList addBoolean(index, element); } - /** - * Like {@link #add(Boolean)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #add(Boolean)} but more efficient in that it doesn't box the element. */ @Override public void addBoolean(boolean element) { addBoolean(size, element); } - /** - * Like {@link #add(int, Boolean)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #add(int, Boolean)} but more efficient in that it doesn't box the element. */ private void addBoolean(int index, boolean element) { ensureIsMutable(); if (index < 0 || index > size) { diff --git a/java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java b/java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java index 6157a52f50..2cb3ada67f 100644 --- a/java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java +++ b/java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java @@ -40,45 +40,40 @@ import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; -/** - * Utility class to provide efficient writing of {@link ByteBuffer}s to {@link OutputStream}s. - */ +/** Utility class to provide efficient writing of {@link ByteBuffer}s to {@link OutputStream}s. */ final class ByteBufferWriter { private ByteBufferWriter() {} /** - * Minimum size for a cached buffer. This prevents us from allocating buffers that are too - * small to be easily reused. + * Minimum size for a cached buffer. This prevents us from allocating buffers that are too small + * to be easily reused. */ // TODO(nathanmittler): tune this property or allow configuration? private static final int MIN_CACHED_BUFFER_SIZE = 1024; /** - * Maximum size for a cached buffer. If a larger buffer is required, it will be allocated - * but not cached. + * Maximum size for a cached buffer. If a larger buffer is required, it will be allocated but not + * cached. */ // TODO(nathanmittler): tune this property or allow configuration? private static final int MAX_CACHED_BUFFER_SIZE = 16 * 1024; - /** - * The fraction of the requested buffer size under which the buffer will be reallocated. - */ + /** The fraction of the requested buffer size under which the buffer will be reallocated. */ // TODO(nathanmittler): tune this property or allow configuration? private static final float BUFFER_REALLOCATION_THRESHOLD = 0.5f; /** - * Keeping a soft reference to a thread-local buffer. This buffer is used for writing a - * {@link ByteBuffer} to an {@link OutputStream} when no zero-copy alternative was available. - * Using a "soft" reference since VMs may keep this reference around longer than "weak" - * (e.g. HotSpot will maintain soft references until memory pressure warrants collection). + * Keeping a soft reference to a thread-local buffer. This buffer is used for writing a {@link + * ByteBuffer} to an {@link OutputStream} when no zero-copy alternative was available. Using a + * "soft" reference since VMs may keep this reference around longer than "weak" (e.g. HotSpot will + * maintain soft references until memory pressure warrants collection). */ private static final ThreadLocal> BUFFER = new ThreadLocal>(); - /** - * This is a hack for GAE, where {@code FileOutputStream} is unavailable. - */ + /** This is a hack for GAE, where {@code FileOutputStream} is unavailable. */ private static final Class FILE_OUTPUT_STREAM_CLASS = safeGetClass("java.io.FileOutputStream"); + private static final long CHANNEL_FIELD_OFFSET = getChannelFieldOffset(FILE_OUTPUT_STREAM_CLASS); /** @@ -100,7 +95,7 @@ final class ByteBufferWriter { // Optimized write for array-backed buffers. // Note that we're taking the risk that a malicious OutputStream could modify the array. output.write(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); - } else if (!writeToChannel(buffer, output)){ + } else if (!writeToChannel(buffer, output)) { // Read all of the data from the buffer to an array. // TODO(nathanmittler): Consider performance improvements for other "known" stream types. final byte[] array = getOrCreateBuffer(buffer.remaining()); @@ -171,6 +166,7 @@ final class ByteBufferWriter { return null; } } + private static long getChannelFieldOffset(Class clazz) { try { if (clazz != null && UnsafeUtil.hasUnsafeArrayOperations()) { diff --git a/java/core/src/main/java/com/google/protobuf/ByteOutput.java b/java/core/src/main/java/com/google/protobuf/ByteOutput.java index ee5887538f..dba7a379f8 100644 --- a/java/core/src/main/java/com/google/protobuf/ByteOutput.java +++ b/java/core/src/main/java/com/google/protobuf/ByteOutput.java @@ -37,9 +37,9 @@ import java.nio.ByteBuffer; * An output target for raw bytes. This interface provides semantics that support two types of * writing: * - *

Traditional write operations: - * (as defined by {@link java.io.OutputStream}) where the target method is responsible for either - * copying the data or completing the write before returning from the method call. + *

Traditional write operations: (as defined by {@link java.io.OutputStream}) where the + * target method is responsible for either copying the data or completing the write before returning + * from the method call. * *

Lazy write operations: where the caller guarantees that it will never modify the * provided buffer and it can therefore be considered immutable. The target method is free to @@ -57,9 +57,9 @@ public abstract class ByteOutput { public abstract void write(byte value) throws IOException; /** - * Writes a sequence of bytes. The {@link ByteOutput} must copy {@code value} if it will - * not be processed prior to the return of this method call, since {@code value} may be - * reused/altered by the caller. + * Writes a sequence of bytes. The {@link ByteOutput} must copy {@code value} if it will not be + * processed prior to the return of this method call, since {@code value} may be reused/altered by + * the caller. * *

NOTE: This method MUST NOT modify the {@code value}. Doing so is a * programming error and will lead to data corruption which will be difficult to debug. @@ -87,15 +87,15 @@ public abstract class ByteOutput { public abstract void writeLazy(byte[] value, int offset, int length) throws IOException; /** - * Writes a sequence of bytes. The {@link ByteOutput} must copy {@code value} if it will - * not be processed prior to the return of this method call, since {@code value} may be - * reused/altered by the caller. + * Writes a sequence of bytes. The {@link ByteOutput} must copy {@code value} if it will not be + * processed prior to the return of this method call, since {@code value} may be reused/altered by + * the caller. * *

NOTE: This method MUST NOT modify the {@code value}. Doing so is a * programming error and will lead to data corruption which will be difficult to debug. * * @param value the bytes to be written. Upon returning from this call, the {@code position} of - * this buffer will be set to the {@code limit} + * this buffer will be set to the {@code limit} * @throws IOException thrown if an error occurred while writing */ public abstract void write(ByteBuffer value) throws IOException; @@ -109,7 +109,7 @@ public abstract class ByteOutput { * programming error and will lead to data corruption which will be difficult to debug. * * @param value the bytes to be written. Upon returning from this call, the {@code position} of - * this buffer will be set to the {@code limit} + * this buffer will be set to the {@code limit} * @throws IOException thrown if an error occurred while writing */ public abstract void writeLazy(ByteBuffer value) throws IOException; diff --git a/java/core/src/main/java/com/google/protobuf/ByteString.java b/java/core/src/main/java/com/google/protobuf/ByteString.java index ddda0f263d..844d8a5317 100644 --- a/java/core/src/main/java/com/google/protobuf/ByteString.java +++ b/java/core/src/main/java/com/google/protobuf/ByteString.java @@ -67,41 +67,36 @@ import java.util.NoSuchElementException; public abstract class ByteString implements Iterable, Serializable { /** - * When two strings to be concatenated have a combined length shorter than - * this, we just copy their bytes on {@link #concat(ByteString)}. - * The trade-off is copy size versus the overhead of creating tree nodes - * in {@link RopeByteString}. + * When two strings to be concatenated have a combined length shorter than this, we just copy + * their bytes on {@link #concat(ByteString)}. The trade-off is copy size versus the overhead of + * creating tree nodes in {@link RopeByteString}. */ static final int CONCATENATE_BY_COPY_SIZE = 128; /** - * When copying an InputStream into a ByteString with .readFrom(), - * the chunks in the underlying rope start at 256 bytes, but double - * each iteration up to 8192 bytes. + * When copying an InputStream into a ByteString with .readFrom(), the chunks in the underlying + * rope start at 256 bytes, but double each iteration up to 8192 bytes. */ - static final int MIN_READ_FROM_CHUNK_SIZE = 0x100; // 256b - static final int MAX_READ_FROM_CHUNK_SIZE = 0x2000; // 8k + static final int MIN_READ_FROM_CHUNK_SIZE = 0x100; // 256b - /** - * Empty {@code ByteString}. - */ + static final int MAX_READ_FROM_CHUNK_SIZE = 0x2000; // 8k + + /** Empty {@code ByteString}. */ public static final ByteString EMPTY = new LiteralByteString(Internal.EMPTY_BYTE_ARRAY); /** * An interface to efficiently copy {@code byte[]}. * - *

One of the noticeable costs of copying a byte[] into a new array using - * {@code System.arraycopy} is nullification of a new buffer before the copy. It has been shown - * the Hotspot VM is capable to intrisicfy {@code Arrays.copyOfRange} operation to avoid this + *

One of the noticeable costs of copying a byte[] into a new array using {@code + * System.arraycopy} is nullification of a new buffer before the copy. It has been shown the + * Hotspot VM is capable to intrisicfy {@code Arrays.copyOfRange} operation to avoid this * expensive nullification and provide substantial performance gain. Unfortunately this does not - * hold on Android runtimes and could make the copy slightly slower due to additional code in - * the {@code Arrays.copyOfRange}. Thus we provide two different implementation for array copier - * for Hotspot and Android runtimes. + * hold on Android runtimes and could make the copy slightly slower due to additional code in the + * {@code Arrays.copyOfRange}. Thus we provide two different implementation for array copier for + * Hotspot and Android runtimes. */ private interface ByteArrayCopier { - /** - * Copies the specified range of the specified array into a new array - */ + /** Copies the specified range of the specified array into a new array */ byte[] copyFrom(byte[] bytes, int offset, int size); } @@ -124,15 +119,16 @@ public abstract class ByteString implements Iterable, Serializable { } private static final ByteArrayCopier byteArrayCopier; + static { byteArrayCopier = Android.isOnAndroidDevice() ? new SystemByteArrayCopier() : new ArraysByteArrayCopier(); } /** - * Cached hash value. Intentionally accessed via a data race, which - * is safe because of the Java Memory Model's "no out-of-thin-air values" - * guarantees for ints. A value of 0 implies that the hash has not been set. + * Cached hash value. Intentionally accessed via a data race, which is safe because of the Java + * Memory Model's "no out-of-thin-air values" guarantees for ints. A value of 0 implies that the + * hash has not been set. */ private int hash = 0; @@ -140,10 +136,9 @@ public abstract class ByteString implements Iterable, Serializable { ByteString() {} /** - * Gets the byte at the given index. This method should be used only for - * random access to individual bytes. To access bytes sequentially, use the - * {@link ByteIterator} returned by {@link #iterator()}, and call {@link - * #substring(int, int)} first if necessary. + * Gets the byte at the given index. This method should be used only for random access to + * individual bytes. To access bytes sequentially, use the {@link ByteIterator} returned by {@link + * #iterator()}, and call {@link #substring(int, int)} first if necessary. * * @param index index of byte * @return the value @@ -152,9 +147,8 @@ public abstract class ByteString implements Iterable, Serializable { public abstract byte byteAt(int index); /** - * Return a {@link ByteString.ByteIterator} over the bytes in the ByteString. - * To avoid auto-boxing, you may get the iterator manually and call - * {@link ByteIterator#nextByte()}. + * Return a {@link ByteString.ByteIterator} over the bytes in the ByteString. To avoid + * auto-boxing, you may get the iterator manually and call {@link ByteIterator#nextByte()}. * * @return the iterator */ @@ -192,13 +186,11 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * This interface extends {@code Iterator}, so that we can return an - * unboxed {@code byte}. + * This interface extends {@code Iterator}, so that we can return an unboxed {@code byte}. */ public interface ByteIterator extends Iterator { /** - * An alternative to {@link Iterator#next()} that returns an - * unboxed primitive {@code byte}. + * An alternative to {@link Iterator#next()} that returns an unboxed primitive {@code byte}. * * @return the next {@code byte} in the iteration * @throws NoSuchElementException if the iteration has no more elements @@ -243,8 +235,8 @@ public abstract class ByteString implements Iterable, Serializable { * Compares two {@link ByteString}s lexicographically, treating their contents as unsigned byte * values between 0 and 255 (inclusive). * - *

For example, {@code (byte) -1} is considered to be greater than {@code (byte) 1} because - * it is interpreted as an unsigned value, {@code 255}. + *

For example, {@code (byte) -1} is considered to be greater than {@code (byte) 1} because it + * is interpreted as an unsigned value, {@code 255}. */ private static final Comparator UNSIGNED_LEXICOGRAPHICAL_COMPARATOR = new Comparator() { @@ -271,12 +263,12 @@ public abstract class ByteString implements Iterable, Serializable { * Returns a {@link Comparator} which compares {@link ByteString}-s lexicographically * as sequences of unsigned bytes (i.e. values between 0 and 255, inclusive). * - *

For example, {@code (byte) -1} is considered to be greater than {@code (byte) 1} because - * it is interpreted as an unsigned value, {@code 255}: + *

For example, {@code (byte) -1} is considered to be greater than {@code (byte) 1} because it + * is interpreted as an unsigned value, {@code 255}: * *

*/ public static Comparator unsignedLexicographicalComparator() { @@ -287,56 +279,49 @@ public abstract class ByteString implements Iterable, Serializable { // ByteString -> substring /** - * Return the substring from {@code beginIndex}, inclusive, to the end of the - * string. + * Return the substring from {@code beginIndex}, inclusive, to the end of the string. * * @param beginIndex start at this index * @return substring sharing underlying data - * @throws IndexOutOfBoundsException if {@code beginIndex < 0} or - * {@code beginIndex > size()}. + * @throws IndexOutOfBoundsException if {@code beginIndex < 0} or {@code beginIndex > size()}. */ public final ByteString substring(int beginIndex) { return substring(beginIndex, size()); } /** - * Return the substring from {@code beginIndex}, inclusive, to {@code - * endIndex}, exclusive. + * Return the substring from {@code beginIndex}, inclusive, to {@code endIndex}, exclusive. * * @param beginIndex start at this index - * @param endIndex the last character is the one before this index + * @param endIndex the last character is the one before this index * @return substring sharing underlying data - * @throws IndexOutOfBoundsException if {@code beginIndex < 0}, - * {@code endIndex > size()}, or {@code beginIndex > endIndex}. + * @throws IndexOutOfBoundsException if {@code beginIndex < 0}, {@code endIndex > size()}, or + * {@code beginIndex > endIndex}. */ public abstract ByteString substring(int beginIndex, int endIndex); /** - * Tests if this bytestring starts with the specified prefix. - * Similar to {@link String#startsWith(String)} + * Tests if this bytestring starts with the specified prefix. Similar to {@link + * String#startsWith(String)} * * @param prefix the prefix. - * @return true if the byte sequence represented by the - * argument is a prefix of the byte sequence represented by - * this string; false otherwise. + * @return true if the byte sequence represented by the argument is a prefix of the + * byte sequence represented by this string; false otherwise. */ public final boolean startsWith(ByteString prefix) { - return size() >= prefix.size() && - substring(0, prefix.size()).equals(prefix); + return size() >= prefix.size() && substring(0, prefix.size()).equals(prefix); } /** - * Tests if this bytestring ends with the specified suffix. - * Similar to {@link String#endsWith(String)} + * Tests if this bytestring ends with the specified suffix. Similar to {@link + * String#endsWith(String)} * * @param suffix the suffix. - * @return true if the byte sequence represented by the - * argument is a suffix of the byte sequence represented by - * this string; false otherwise. + * @return true if the byte sequence represented by the argument is a suffix of the + * byte sequence represented by this string; false otherwise. */ public final boolean endsWith(ByteString suffix) { - return size() >= suffix.size() && - substring(size() - suffix.size()).equals(suffix); + return size() >= suffix.size() && substring(size() - suffix.size()).equals(suffix); } // ================================================================= @@ -366,9 +351,7 @@ public abstract class ByteString implements Iterable, Serializable { return copyFrom(bytes, 0, bytes.length); } - /** - * Wraps the given bytes into a {@code ByteString}. Intended for internal only usage. - */ + /** Wraps the given bytes into a {@code ByteString}. Intended for internal only usage. */ static ByteString wrap(ByteBuffer buffer) { if (buffer.hasArray()) { final int offset = buffer.arrayOffset(); @@ -379,8 +362,8 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Wraps the given bytes into a {@code ByteString}. Intended for internal only - * usage to force a classload of ByteString before LiteralByteString. + * Wraps the given bytes into a {@code ByteString}. Intended for internal only usage to force a + * classload of ByteString before LiteralByteString. */ static ByteString wrap(byte[] bytes) { // TODO(dweis): Return EMPTY when bytes are empty to reduce allocations? @@ -388,17 +371,16 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Wraps the given bytes into a {@code ByteString}. Intended for internal only - * usage to force a classload of ByteString before BoundedByteString and - * LiteralByteString. + * Wraps the given bytes into a {@code ByteString}. Intended for internal only usage to force a + * classload of ByteString before BoundedByteString and LiteralByteString. */ static ByteString wrap(byte[] bytes, int offset, int length) { return new BoundedByteString(bytes, offset, length); } /** - * Copies the next {@code size} bytes from a {@code java.nio.ByteBuffer} into - * a {@code ByteString}. + * Copies the next {@code size} bytes from a {@code java.nio.ByteBuffer} into a {@code + * ByteString}. * * @param bytes source buffer * @param size number of bytes to copy @@ -413,8 +395,7 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Copies the remaining bytes from a {@code java.nio.ByteBuffer} into - * a {@code ByteString}. + * Copies the remaining bytes from a {@code java.nio.ByteBuffer} into a {@code ByteString}. * * @param bytes sourceBuffer * @return new {@code ByteString} @@ -424,8 +405,8 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Encodes {@code text} into a sequence of bytes using the named charset - * and returns the result as a {@code ByteString}. + * Encodes {@code text} into a sequence of bytes using the named charset and returns the result as + * a {@code ByteString}. * * @param text source string * @param charsetName encoding to use @@ -438,8 +419,8 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Encodes {@code text} into a sequence of bytes using the named charset - * and returns the result as a {@code ByteString}. + * Encodes {@code text} into a sequence of bytes using the named charset and returns the result as + * a {@code ByteString}. * * @param text source string * @param charset encode using this charset @@ -450,8 +431,8 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Encodes {@code text} into a sequence of UTF-8 bytes and returns the - * result as a {@code ByteString}. + * Encodes {@code text} into a sequence of UTF-8 bytes and returns the result as a {@code + * ByteString}. * * @param text source string * @return new {@code ByteString} @@ -464,60 +445,48 @@ public abstract class ByteString implements Iterable, Serializable { // InputStream -> ByteString /** - * Completely reads the given stream's bytes into a - * {@code ByteString}, blocking if necessary until all bytes are - * read through to the end of the stream. - * - * Performance notes: The returned {@code ByteString} is an - * immutable tree of byte arrays ("chunks") of the stream data. The - * first chunk is small, with subsequent chunks each being double - * the size, up to 8K. - * - *

Each byte read from the input stream will be copied twice to ensure - * that the resulting ByteString is truly immutable. - * - * @param streamToDrain The source stream, which is read completely - * but not closed. - * @return A new {@code ByteString} which is made up of chunks of - * various sizes, depending on the behavior of the underlying - * stream. - * @throws IOException IOException is thrown if there is a problem - * reading the underlying stream. + * Completely reads the given stream's bytes into a {@code ByteString}, blocking if necessary + * until all bytes are read through to the end of the stream. + * + *

Performance notes: The returned {@code ByteString} is an immutable tree of byte + * arrays ("chunks") of the stream data. The first chunk is small, with subsequent chunks each + * being double the size, up to 8K. + * + *

Each byte read from the input stream will be copied twice to ensure that the resulting + * ByteString is truly immutable. + * + * @param streamToDrain The source stream, which is read completely but not closed. + * @return A new {@code ByteString} which is made up of chunks of various sizes, depending on the + * behavior of the underlying stream. + * @throws IOException IOException is thrown if there is a problem reading the underlying stream. */ - public static ByteString readFrom(InputStream streamToDrain) - throws IOException { + public static ByteString readFrom(InputStream streamToDrain) throws IOException { return readFrom(streamToDrain, MIN_READ_FROM_CHUNK_SIZE, MAX_READ_FROM_CHUNK_SIZE); } /** - * Completely reads the given stream's bytes into a - * {@code ByteString}, blocking if necessary until all bytes are - * read through to the end of the stream. - * - * Performance notes: The returned {@code ByteString} is an - * immutable tree of byte arrays ("chunks") of the stream data. The - * chunkSize parameter sets the size of these byte arrays. - * - *

Each byte read from the input stream will be copied twice to ensure - * that the resulting ByteString is truly immutable. - * - * @param streamToDrain The source stream, which is read completely - * but not closed. - * @param chunkSize The size of the chunks in which to read the - * stream. - * @return A new {@code ByteString} which is made up of chunks of - * the given size. - * @throws IOException IOException is thrown if there is a problem - * reading the underlying stream. + * Completely reads the given stream's bytes into a {@code ByteString}, blocking if necessary + * until all bytes are read through to the end of the stream. + * + *

Performance notes: The returned {@code ByteString} is an immutable tree of byte + * arrays ("chunks") of the stream data. The chunkSize parameter sets the size of these byte + * arrays. + * + *

Each byte read from the input stream will be copied twice to ensure that the resulting + * ByteString is truly immutable. + * + * @param streamToDrain The source stream, which is read completely but not closed. + * @param chunkSize The size of the chunks in which to read the stream. + * @return A new {@code ByteString} which is made up of chunks of the given size. + * @throws IOException IOException is thrown if there is a problem reading the underlying stream. */ - public static ByteString readFrom(InputStream streamToDrain, int chunkSize) - throws IOException { + public static ByteString readFrom(InputStream streamToDrain, int chunkSize) throws IOException { return readFrom(streamToDrain, chunkSize, chunkSize); } // Helper method that takes the chunk size range as a parameter. - public static ByteString readFrom(InputStream streamToDrain, int minChunkSize, - int maxChunkSize) throws IOException { + public static ByteString readFrom(InputStream streamToDrain, int minChunkSize, int maxChunkSize) + throws IOException { Collection results = new ArrayList(); // copy the inbound bytes into a list of chunks; the chunk size @@ -536,42 +505,39 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Blocks until a chunk of the given size can be made from the - * stream, or EOF is reached. Calls read() repeatedly in case the - * given stream implementation doesn't completely fill the given + * Blocks until a chunk of the given size can be made from the stream, or EOF is reached. Calls + * read() repeatedly in case the given stream implementation doesn't completely fill the given * buffer in one read() call. * - * @return A chunk of the desired size, or else a chunk as large as - * was available when end of stream was reached. Returns null if the - * given stream had no more data in it. + * @return A chunk of the desired size, or else a chunk as large as was available when end of + * stream was reached. Returns null if the given stream had no more data in it. */ - private static ByteString readChunk(InputStream in, final int chunkSize) - throws IOException { - final byte[] buf = new byte[chunkSize]; - int bytesRead = 0; - while (bytesRead < chunkSize) { - final int count = in.read(buf, bytesRead, chunkSize - bytesRead); - if (count == -1) { - break; - } - bytesRead += count; + private static ByteString readChunk(InputStream in, final int chunkSize) throws IOException { + final byte[] buf = new byte[chunkSize]; + int bytesRead = 0; + while (bytesRead < chunkSize) { + final int count = in.read(buf, bytesRead, chunkSize - bytesRead); + if (count == -1) { + break; } + bytesRead += count; + } - if (bytesRead == 0) { - return null; - } + if (bytesRead == 0) { + return null; + } - // Always make a copy since InputStream could steal a reference to buf. - return ByteString.copyFrom(buf, 0, bytesRead); + // Always make a copy since InputStream could steal a reference to buf. + return ByteString.copyFrom(buf, 0, bytesRead); } // ================================================================= // Multiple ByteStrings -> One ByteString /** - * Concatenate the given {@code ByteString} to this one. Short concatenations, - * of total size smaller than {@link ByteString#CONCATENATE_BY_COPY_SIZE}, are - * produced by copying the underlying bytes (as per Rope.java, * BAP95 . In general, the concatenate involves no copying. * @@ -580,21 +546,20 @@ public abstract class ByteString implements Iterable, Serializable { */ public final ByteString concat(ByteString other) { if (Integer.MAX_VALUE - size() < other.size()) { - throw new IllegalArgumentException("ByteString would be too long: " + - size() + "+" + other.size()); + throw new IllegalArgumentException( + "ByteString would be too long: " + size() + "+" + other.size()); } return RopeByteString.concatenate(this, other); } /** - * Concatenates all byte strings in the iterable and returns the result. - * This is designed to run in O(list size), not O(total bytes). + * Concatenates all byte strings in the iterable and returns the result. This is designed to run + * in O(list size), not O(total bytes). * - *

The returned {@code ByteString} is not necessarily a unique object. - * If the list is empty, the returned object is the singleton empty - * {@code ByteString}. If the list has only one element, that - * {@code ByteString} will be returned without copying. + *

The returned {@code ByteString} is not necessarily a unique object. If the list is empty, + * the returned object is the singleton empty {@code ByteString}. If the list has only one + * element, that {@code ByteString} will be returned without copying. * * @param byteStrings strings to be concatenated * @return new {@code ByteString} @@ -604,9 +569,9 @@ public abstract class ByteString implements Iterable, Serializable { final int size; if (!(byteStrings instanceof Collection)) { int tempSize = 0; - for (Iterator iter = byteStrings.iterator(); iter.hasNext(); - iter.next(), ++tempSize) { - } + for (Iterator iter = byteStrings.iterator(); + iter.hasNext(); + iter.next(), ++tempSize) {} size = tempSize; } else { size = ((Collection) byteStrings).size(); @@ -676,13 +641,11 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Internal (package private) implementation of - * {@link #copyTo(byte[],int,int,int)}. - * It assumes that all error checking has already been performed and that - * {@code numberToCopy > 0}. + * Internal (package private) implementation of {@link #copyTo(byte[],int,int,int)}. It assumes + * that all error checking has already been performed and that {@code numberToCopy > 0}. */ - protected abstract void copyToInternal(byte[] target, int sourceOffset, - int targetOffset, int numberToCopy); + protected abstract void copyToInternal( + byte[] target, int sourceOffset, int targetOffset, int numberToCopy); /** * Copies bytes into a ByteBuffer. @@ -715,22 +678,21 @@ public abstract class ByteString implements Iterable, Serializable { /** * Writes a copy of the contents of this byte string to the specified output stream argument. * - * @param out the output stream to which to write the data. - * @throws IOException if an I/O error occurs. + * @param out the output stream to which to write the data. + * @throws IOException if an I/O error occurs. */ public abstract void writeTo(OutputStream out) throws IOException; /** * Writes a specified part of this byte string to an output stream. * - * @param out the output stream to which to write the data. - * @param sourceOffset offset within these bytes - * @param numberToWrite number of bytes to write - * @throws IOException if an I/O error occurs. + * @param out the output stream to which to write the data. + * @param sourceOffset offset within these bytes + * @param numberToWrite number of bytes to write + * @throws IOException if an I/O error occurs. * @throws IndexOutOfBoundsException if an offset or size is negative or too large */ - final void writeTo(OutputStream out, int sourceOffset, int numberToWrite) - throws IOException { + final void writeTo(OutputStream out, int sourceOffset, int numberToWrite) throws IOException { checkRange(sourceOffset, sourceOffset + numberToWrite, size()); if (numberToWrite > 0) { writeToInternal(out, sourceOffset, numberToWrite); @@ -738,59 +700,55 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Internal version of {@link #writeTo(OutputStream,int,int)} that assumes - * all error checking has already been done. + * Internal version of {@link #writeTo(OutputStream,int,int)} that assumes all error checking has + * already been done. */ abstract void writeToInternal(OutputStream out, int sourceOffset, int numberToWrite) throws IOException; /** - * Writes this {@link ByteString} to the provided {@link ByteOutput}. Calling - * this method may result in multiple operations on the target {@link ByteOutput}. + * Writes this {@link ByteString} to the provided {@link ByteOutput}. Calling this method may + * result in multiple operations on the target {@link ByteOutput}. * *

This method may expose internal backing buffers of the {@link ByteString} to the {@link * ByteOutput} in order to avoid additional copying overhead. It would be possible for a malicious * {@link ByteOutput} to corrupt the {@link ByteString}. Use with caution! * - * @param byteOutput the output target to receive the bytes - * @throws IOException if an I/O error occurs + * @param byteOutput the output target to receive the bytes + * @throws IOException if an I/O error occurs * @see UnsafeByteOperations#unsafeWriteTo(ByteString, ByteOutput) */ abstract void writeTo(ByteOutput byteOutput) throws IOException; /** - * Constructs a read-only {@code java.nio.ByteBuffer} whose content - * is equal to the contents of this byte string. - * The result uses the same backing array as the byte string, if possible. + * Constructs a read-only {@code java.nio.ByteBuffer} whose content is equal to the contents of + * this byte string. The result uses the same backing array as the byte string, if possible. * * @return wrapped bytes */ public abstract ByteBuffer asReadOnlyByteBuffer(); /** - * Constructs a list of read-only {@code java.nio.ByteBuffer} objects - * such that the concatenation of their contents is equal to the contents - * of this byte string. The result uses the same backing arrays as the - * byte string. - *

- * By returning a list, implementations of this method may be able to avoid - * copying even when there are multiple backing arrays. + * Constructs a list of read-only {@code java.nio.ByteBuffer} objects such that the concatenation + * of their contents is equal to the contents of this byte string. The result uses the same + * backing arrays as the byte string. + * + *

By returning a list, implementations of this method may be able to avoid copying even when + * there are multiple backing arrays. * * @return a list of wrapped bytes */ public abstract List asReadOnlyByteBufferList(); /** - * Constructs a new {@code String} by decoding the bytes using the - * specified charset. + * Constructs a new {@code String} by decoding the bytes using the specified charset. * * @param charsetName encode using this charset * @return new string * @throws UnsupportedEncodingException if charset isn't recognized */ - public final String toString(String charsetName) - throws UnsupportedEncodingException { + public final String toString(String charsetName) throws UnsupportedEncodingException { try { return toString(Charset.forName(charsetName)); } catch (UnsupportedCharsetException e) { @@ -801,8 +759,8 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Constructs a new {@code String} by decoding the bytes using the - * specified charset. Returns the same empty String if empty. + * Constructs a new {@code String} by decoding the bytes using the specified charset. Returns the + * same empty String if empty. * * @param charset encode using this charset * @return new string @@ -812,8 +770,7 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Constructs a new {@code String} by decoding the bytes using the - * specified charset. + * Constructs a new {@code String} by decoding the bytes using the specified charset. * * @param charset encode using this charset * @return new string @@ -833,50 +790,45 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Tells whether this {@code ByteString} represents a well-formed UTF-8 - * byte sequence, such that the original bytes can be converted to a - * String object and then round tripped back to bytes without loss. + * Tells whether this {@code ByteString} represents a well-formed UTF-8 byte sequence, such that + * the original bytes can be converted to a String object and then round tripped back to bytes + * without loss. * - *

More precisely, returns {@code true} whenever:

 {@code
+   * 

More precisely, returns {@code true} whenever: + * + *

{@code
    * Arrays.equals(byteString.toByteArray(),
    *     new String(byteString.toByteArray(), "UTF-8").getBytes("UTF-8"))
    * }
* - *

This method returns {@code false} for "overlong" byte sequences, - * as well as for 3-byte sequences that would map to a surrogate - * character, in accordance with the restricted definition of UTF-8 - * introduced in Unicode 3.1. Note that the UTF-8 decoder included in - * Oracle's JDK has been modified to also reject "overlong" byte - * sequences, but (as of 2011) still accepts 3-byte surrogate - * character byte sequences. + *

This method returns {@code false} for "overlong" byte sequences, as well as for 3-byte + * sequences that would map to a surrogate character, in accordance with the restricted definition + * of UTF-8 introduced in Unicode 3.1. Note that the UTF-8 decoder included in Oracle's JDK has + * been modified to also reject "overlong" byte sequences, but (as of 2011) still accepts 3-byte + * surrogate character byte sequences. * *

See the Unicode Standard,
* Table 3-6. UTF-8 Bit Distribution,
* Table 3-7. Well Formed UTF-8 Byte Sequences. * - * @return whether the bytes in this {@code ByteString} are a - * well-formed UTF-8 byte sequence + * @return whether the bytes in this {@code ByteString} are a well-formed UTF-8 byte sequence */ public abstract boolean isValidUtf8(); /** - * Tells whether the given byte sequence is a well-formed, malformed, or - * incomplete UTF-8 byte sequence. This method accepts and returns a partial - * state result, allowing the bytes for a complete UTF-8 byte sequence to be - * composed from multiple {@code ByteString} segments. - * - * @param state either {@code 0} (if this is the initial decoding operation) - * or the value returned from a call to a partial decoding method for the - * previous bytes + * Tells whether the given byte sequence is a well-formed, malformed, or incomplete UTF-8 byte + * sequence. This method accepts and returns a partial state result, allowing the bytes for a + * complete UTF-8 byte sequence to be composed from multiple {@code ByteString} segments. + * + * @param state either {@code 0} (if this is the initial decoding operation) or the value returned + * from a call to a partial decoding method for the previous bytes * @param offset offset of the first byte to check * @param length number of bytes to check - * - * @return {@code -1} if the partial byte sequence is definitely malformed, - * {@code 0} if it is well-formed (no additional input needed), or, if the - * byte sequence is "incomplete", i.e. apparently terminated in the middle of - * a character, an opaque integer "state" value containing enough information - * to decode the character when passed to a subsequent invocation of a - * partial decoding method. + * @return {@code -1} if the partial byte sequence is definitely malformed, {@code 0} if it is + * well-formed (no additional input needed), or, if the byte sequence is "incomplete", i.e. + * apparently terminated in the middle of a character, an opaque integer "state" value + * containing enough information to decode the character when passed to a subsequent + * invocation of a partial decoding method. */ protected abstract int partialIsValidUtf8(int state, int offset, int length); @@ -886,9 +838,7 @@ public abstract class ByteString implements Iterable, Serializable { @Override public abstract boolean equals(Object o); - /** - * Base class for leaf {@link ByteString}s (i.e. non-ropes). - */ + /** Base class for leaf {@link ByteString}s (i.e. non-ropes). */ abstract static class LeafByteString extends ByteString { @Override protected final int getTreeDepth() { @@ -902,10 +852,10 @@ public abstract class ByteString implements Iterable, Serializable { /** - * Check equality of the substring of given length of this object starting at - * zero with another {@code ByteString} substring starting at offset. + * Check equality of the substring of given length of this object starting at zero with another + * {@code ByteString} substring starting at offset. * - * @param other what to compare a substring in + * @param other what to compare a substring in * @param offset offset into other * @param length number of bytes to compare * @return true for equality of substrings, else false. @@ -914,8 +864,7 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Compute the hashCode using the traditional algorithm from {@link - * ByteString}. + * Compute the hashCode using the traditional algorithm from {@link ByteString}. * * @return hashCode value */ @@ -939,26 +888,23 @@ public abstract class ByteString implements Iterable, Serializable { /** * Creates an {@code InputStream} which can be used to read the bytes. - *

- * The {@link InputStream} returned by this method is guaranteed to be - * completely non-blocking. The method {@link InputStream#available()} - * returns the number of bytes remaining in the stream. The methods - * {@link InputStream#read(byte[])}, {@link InputStream#read(byte[],int,int)} - * and {@link InputStream#skip(long)} will read/skip as many bytes as are - * available. The method {@link InputStream#markSupported()} returns - * {@code true}. - *

- * The methods in the returned {@link InputStream} might not be - * thread safe. + * + *

The {@link InputStream} returned by this method is guaranteed to be completely non-blocking. + * The method {@link InputStream#available()} returns the number of bytes remaining in the stream. + * The methods {@link InputStream#read(byte[])}, {@link InputStream#read(byte[],int,int)} and + * {@link InputStream#skip(long)} will read/skip as many bytes as are available. The method {@link + * InputStream#markSupported()} returns {@code true}. + * + *

The methods in the returned {@link InputStream} might not be thread safe. * * @return an input stream that returns the bytes of this byte string. */ public abstract InputStream newInput(); /** - * Creates a {@link CodedInputStream} which can be used to read the bytes. - * Using this is often more efficient than creating a {@link CodedInputStream} - * that wraps the result of {@link #newInput()}. + * Creates a {@link CodedInputStream} which can be used to read the bytes. Using this is often + * more efficient than creating a {@link CodedInputStream} that wraps the result of {@link + * #newInput()}. * * @return stream based on wrapped data */ @@ -970,10 +916,10 @@ public abstract class ByteString implements Iterable, Serializable { /** * Creates a new {@link Output} with the given initial capacity. Call {@link * Output#toByteString()} to create the {@code ByteString} instance. - *

- * A {@link ByteString.Output} offers the same functionality as a - * {@link ByteArrayOutputStream}, except that it returns a {@link ByteString} - * rather than a {@code byte} array. + * + *

A {@link ByteString.Output} offers the same functionality as a {@link + * ByteArrayOutputStream}, except that it returns a {@link ByteString} rather than a {@code byte} + * array. * * @param initialCapacity estimate of number of bytes to be written * @return {@code OutputStream} for building a {@code ByteString} @@ -983,12 +929,12 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Creates a new {@link Output}. Call {@link Output#toByteString()} to create - * the {@code ByteString} instance. - *

- * A {@link ByteString.Output} offers the same functionality as a - * {@link ByteArrayOutputStream}, except that it returns a {@link ByteString} - * rather than a {@code byte array}. + * Creates a new {@link Output}. Call {@link Output#toByteString()} to create the {@code + * ByteString} instance. + * + *

A {@link ByteString.Output} offers the same functionality as a {@link + * ByteArrayOutputStream}, except that it returns a {@link ByteString} rather than a {@code byte + * array}. * * @return {@code OutputStream} for building a {@code ByteString} */ @@ -997,8 +943,8 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Outputs to a {@code ByteString} instance. Call {@link #toByteString()} to - * create the {@code ByteString} instance. + * Outputs to a {@code ByteString} instance. Call {@link #toByteString()} to create the {@code + * ByteString} instance. */ public static final class Output extends OutputStream { // Implementation note. @@ -1020,10 +966,9 @@ public abstract class ByteString implements Iterable, Serializable { private int bufferPos; /** - * Creates a new ByteString output stream with the specified - * initial capacity. + * Creates a new ByteString output stream with the specified initial capacity. * - * @param initialCapacity the initial capacity of the output stream. + * @param initialCapacity the initial capacity of the output stream. */ Output(int initialCapacity) { if (initialCapacity < 0) { @@ -1039,43 +984,41 @@ public abstract class ByteString implements Iterable, Serializable { if (bufferPos == buffer.length) { flushFullBuffer(1); } - buffer[bufferPos++] = (byte)b; + buffer[bufferPos++] = (byte) b; } @Override - public synchronized void write(byte[] b, int offset, int length) { + public synchronized void write(byte[] b, int offset, int length) { if (length <= buffer.length - bufferPos) { // The bytes can fit into the current buffer. System.arraycopy(b, offset, buffer, bufferPos, length); bufferPos += length; } else { // Use up the current buffer - int copySize = buffer.length - bufferPos; + int copySize = buffer.length - bufferPos; System.arraycopy(b, offset, buffer, bufferPos, copySize); offset += copySize; length -= copySize; // Flush the buffer, and get a new buffer at least big enough to cover // what we still need to output flushFullBuffer(length); - System.arraycopy(b, offset, buffer, 0 /* count */, length); + System.arraycopy(b, offset, buffer, /* count= */ 0, length); bufferPos = length; } } /** - * Creates a byte string. Its size is the current size of this output - * stream and its output has been copied to it. + * Creates a byte string. Its size is the current size of this output stream and its output has + * been copied to it. * - * @return the current contents of this output stream, as a byte string. + * @return the current contents of this output stream, as a byte string. */ public synchronized ByteString toByteString() { flushLastBuffer(); return ByteString.copyFrom(flushedBuffers); } - /** - * Implement java.util.Arrays.copyOf() for jdk 1.5. - */ + /** Implement java.util.Arrays.copyOf() for jdk 1.5. */ private byte[] copyArray(byte[] buffer, int length) { byte[] result = new byte[length]; System.arraycopy(buffer, 0, result, 0, Math.min(buffer.length, length)); @@ -1083,11 +1026,11 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Writes the complete contents of this byte array output stream to - * the specified output stream argument. + * Writes the complete contents of this byte array output stream to the specified output stream + * argument. * * @param out the output stream to which to write the data. - * @throws IOException if an I/O error occurs. + * @throws IOException if an I/O error occurs. */ public void writeTo(OutputStream out) throws IOException { ByteString[] cachedFlushBuffers; @@ -1096,8 +1039,7 @@ public abstract class ByteString implements Iterable, Serializable { synchronized (this) { // Copy the information we need into local variables so as to hold // the lock for as short a time as possible. - cachedFlushBuffers = - flushedBuffers.toArray(new ByteString[flushedBuffers.size()]); + cachedFlushBuffers = flushedBuffers.toArray(new ByteString[flushedBuffers.size()]); cachedBuffer = buffer; cachedBufferPos = bufferPos; } @@ -1111,16 +1053,15 @@ public abstract class ByteString implements Iterable, Serializable { /** * Returns the current size of the output stream. * - * @return the current size of the output stream + * @return the current size of the output stream */ public synchronized int size() { return flushedBuffersTotalBytes + bufferPos; } /** - * Resets this stream, so that all currently accumulated output in the - * output stream is discarded. The output stream can be used again, - * reusing the already allocated buffer space. + * Resets this stream, so that all currently accumulated output in the output stream is + * discarded. The output stream can be used again, reusing the already allocated buffer space. */ public synchronized void reset() { flushedBuffers.clear(); @@ -1130,32 +1071,31 @@ public abstract class ByteString implements Iterable, Serializable { @Override public String toString() { - return String.format("", + return String.format( + "", Integer.toHexString(System.identityHashCode(this)), size()); } /** - * Internal function used by writers. The current buffer is full, and the - * writer needs a new buffer whose size is at least the specified minimum - * size. + * Internal function used by writers. The current buffer is full, and the writer needs a new + * buffer whose size is at least the specified minimum size. */ - private void flushFullBuffer(int minSize) { + private void flushFullBuffer(int minSize) { flushedBuffers.add(new LiteralByteString(buffer)); flushedBuffersTotalBytes += buffer.length; // We want to increase our total capacity by 50%, but as a minimum, // the new buffer should also at least be >= minSize and // >= initial Capacity. - int newSize = Math.max(initialCapacity, - Math.max(minSize, flushedBuffersTotalBytes >>> 1)); + int newSize = Math.max(initialCapacity, Math.max(minSize, flushedBuffersTotalBytes >>> 1)); buffer = new byte[newSize]; bufferPos = 0; } /** - * Internal function used by {@link #toByteString()}. The current buffer may - * or may not be full, but it needs to be flushed. + * Internal function used by {@link #toByteString()}. The current buffer may or may not be full, + * but it needs to be flushed. */ - private void flushLastBuffer() { + private void flushLastBuffer() { if (bufferPos < buffer.length) { if (bufferPos > 0) { byte[] bufferCopy = copyArray(buffer, bufferPos); @@ -1178,17 +1118,15 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Constructs a new {@code ByteString} builder, which allows you to - * efficiently construct a {@code ByteString} by writing to a {@link - * CodedOutputStream}. Using this is much more efficient than calling {@code - * newOutput()} and wrapping that in a {@code CodedOutputStream}. + * Constructs a new {@code ByteString} builder, which allows you to efficiently construct a {@code + * ByteString} by writing to a {@link CodedOutputStream}. Using this is much more efficient than + * calling {@code newOutput()} and wrapping that in a {@code CodedOutputStream}. * - *

This is package-private because it's a somewhat confusing interface. - * Users can call {@link Message#toByteString()} instead of calling this - * directly. + *

This is package-private because it's a somewhat confusing interface. Users can call {@link + * Message#toByteString()} instead of calling this directly. * - * @param size The target byte size of the {@code ByteString}. You must write - * exactly this many bytes before building the result. + * @param size The target byte size of the {@code ByteString}. You must write exactly this many + * bytes before building the result. * @return the builder */ static CodedBuilder newCodedBuilder(int size) { @@ -1224,16 +1162,16 @@ public abstract class ByteString implements Iterable, Serializable { // public API. /** - * Return the depth of the tree representing this {@code ByteString}, if any, - * whose root is this node. If this is a leaf node, return 0. + * Return the depth of the tree representing this {@code ByteString}, if any, whose root is this + * node. If this is a leaf node, return 0. * * @return tree depth or zero */ protected abstract int getTreeDepth(); /** - * Return {@code true} if this ByteString is literal (a leaf node) or a - * flat-enough tree in the sense of {@link RopeByteString}. + * Return {@code true} if this ByteString is literal (a leaf node) or a flat-enough tree in the + * sense of {@link RopeByteString}. * * @return true if the tree is flat enough */ @@ -1249,10 +1187,9 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Compute the hash across the value bytes starting with the given hash, and - * return the result. This is used to compute the hash across strings - * represented as a set of pieces by allowing the hash computation to be - * continued from piece to piece. + * Compute the hash across the value bytes starting with the given hash, and return the result. + * This is used to compute the hash across strings represented as a set of pieces by allowing the + * hash computation to be continued from piece to piece. * * @param h starting hash value * @param offset offset into this value to start looking at data values @@ -1304,16 +1241,15 @@ public abstract class ByteString implements Iterable, Serializable { @Override public final String toString() { - return String.format("", - Integer.toHexString(System.identityHashCode(this)), size()); + return String.format( + "", Integer.toHexString(System.identityHashCode(this)), size()); } /** - * This class implements a {@link com.google.protobuf.ByteString} backed by a - * single array of bytes, contiguous in memory. It supports substring by - * pointing to only a sub-range of the underlying byte array, meaning that a - * substring will reference the full byte-array of the string it's made from, - * exactly as with {@link String}. + * This class implements a {@link com.google.protobuf.ByteString} backed by a single array of + * bytes, contiguous in memory. It supports substring by pointing to only a sub-range of the + * underlying byte array, meaning that a substring will reference the full byte-array of the + * string it's made from, exactly as with {@link String}. * * @author carlanton@google.com (Carl Haverl) */ @@ -1325,8 +1261,7 @@ public abstract class ByteString implements Iterable, Serializable { protected final byte[] bytes; /** - * Creates a {@code LiteralByteString} backed by the given array, without - * copying. + * Creates a {@code LiteralByteString} backed by the given array, without copying. * * @param bytes array to wrap */ @@ -1464,10 +1399,10 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Check equality of the substring of given length of this object starting at - * zero with another {@code LiteralByteString} substring starting at offset. + * Check equality of the substring of given length of this object starting at zero with another + * {@code LiteralByteString} substring starting at offset. * - * @param other what to compare a substring in + * @param other what to compare a substring in * @param offset offset into other * @param length number of bytes to compare * @return true for equality of substrings, else false. @@ -1487,10 +1422,10 @@ public abstract class ByteString implements Iterable, Serializable { byte[] thisBytes = bytes; byte[] otherBytes = lbsOther.bytes; int thisLimit = getOffsetIntoBytes() + length; - for ( - int thisIndex = getOffsetIntoBytes(), + for (int thisIndex = getOffsetIntoBytes(), otherIndex = lbsOther.getOffsetIntoBytes() + offset; - (thisIndex < thisLimit); ++thisIndex, ++otherIndex) { + (thisIndex < thisLimit); + ++thisIndex, ++otherIndex) { if (thisBytes[thisIndex] != otherBytes[otherIndex]) { return false; } @@ -1519,7 +1454,7 @@ public abstract class ByteString implements Iterable, Serializable { // We trust CodedInputStream not to modify the bytes, or to give anyone // else access to them. return CodedInputStream.newInstance( - bytes, getOffsetIntoBytes(), size(), true /* bufferIsImmutable */); + bytes, getOffsetIntoBytes(), size(), /* bufferIsImmutable= */ true); } // ================================================================= @@ -1536,14 +1471,12 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * This class is used to represent the substring of a {@link ByteString} over a - * single byte array. In terms of the public API of {@link ByteString}, you end - * up here by calling {@link ByteString#copyFrom(byte[])} followed by {@link - * ByteString#substring(int, int)}. + * This class is used to represent the substring of a {@link ByteString} over a single byte array. + * In terms of the public API of {@link ByteString}, you end up here by calling {@link + * ByteString#copyFrom(byte[])} followed by {@link ByteString#substring(int, int)}. * - *

This class contains most of the overhead involved in creating a substring - * from a {@link LiteralByteString}. The overhead involves some range-checking - * and two extra fields. + *

This class contains most of the overhead involved in creating a substring from a {@link + * LiteralByteString}. The overhead involves some range-checking and two extra fields. * * @author carlanton@google.com (Carl Haverl) */ @@ -1555,15 +1488,13 @@ public abstract class ByteString implements Iterable, Serializable { private final int bytesLength; /** - * Creates a {@code BoundedByteString} backed by the sub-range of given array, - * without copying. + * Creates a {@code BoundedByteString} backed by the sub-range of given array, without copying. * - * @param bytes array to wrap + * @param bytes array to wrap * @param offset index to first byte to use in bytes * @param length number of bytes to use from bytes - * @throws IllegalArgumentException if {@code offset < 0}, {@code length < 0}, - * or if {@code offset + length > - * bytes.length}. + * @throws IllegalArgumentException if {@code offset < 0}, {@code length < 0}, or if {@code + * offset + length > bytes.length}. */ BoundedByteString(byte[] bytes, int offset, int length) { super(bytes); @@ -1574,10 +1505,9 @@ public abstract class ByteString implements Iterable, Serializable { } /** - * Gets the byte at the given index. - * Throws {@link ArrayIndexOutOfBoundsException} - * for backwards-compatibility reasons although it would more properly be - * {@link IndexOutOfBoundsException}. + * Gets the byte at the given index. Throws {@link ArrayIndexOutOfBoundsException} for + * backwards-compatibility reasons although it would more properly be {@link + * IndexOutOfBoundsException}. * * @param index index of byte * @return the value @@ -1605,10 +1535,10 @@ public abstract class ByteString implements Iterable, Serializable { // ByteString -> byte[] @Override - protected void copyToInternal(byte[] target, int sourceOffset, int targetOffset, - int numberToCopy) { - System.arraycopy(bytes, getOffsetIntoBytes() + sourceOffset, target, - targetOffset, numberToCopy); + protected void copyToInternal( + byte[] target, int sourceOffset, int targetOffset, int numberToCopy) { + System.arraycopy( + bytes, getOffsetIntoBytes() + sourceOffset, target, targetOffset, numberToCopy); } // ================================================================= diff --git a/java/core/src/main/java/com/google/protobuf/CodedInputStream.java b/java/core/src/main/java/com/google/protobuf/CodedInputStream.java index 4545d0aed9..df4cc6649e 100644 --- a/java/core/src/main/java/com/google/protobuf/CodedInputStream.java +++ b/java/core/src/main/java/com/google/protobuf/CodedInputStream.java @@ -77,8 +77,11 @@ public abstract class CodedInputStream { return newInstance(input, DEFAULT_BUFFER_SIZE); } - /** Create a new CodedInputStream wrapping the given InputStream. */ - static CodedInputStream newInstance(final InputStream input, int bufferSize) { + /** Create a new CodedInputStream wrapping the given InputStream, with a specified buffer size. */ + public static CodedInputStream newInstance(final InputStream input, int bufferSize) { + if (bufferSize <= 0) { + throw new IllegalArgumentException("bufferSize must be > 0"); + } if (input == null) { // TODO(nathanmittler): Ideally we should throw here. This is done for backward compatibility. return newInstance(EMPTY_BYTE_ARRAY); @@ -130,7 +133,7 @@ public abstract class CodedInputStream { /** Create a new CodedInputStream wrapping the given byte array slice. */ public static CodedInputStream newInstance(final byte[] buf, final int off, final int len) { - return newInstance(buf, off, len, false /* bufferIsImmutable */); + return newInstance(buf, off, len, /* bufferIsImmutable= */ false); } /** Create a new CodedInputStream wrapping the given byte array slice. */ @@ -166,7 +169,7 @@ public abstract class CodedInputStream { * trying to alter the ByteBuffer's status. */ public static CodedInputStream newInstance(ByteBuffer buf) { - return newInstance(buf, false /* bufferIsImmutable */); + return newInstance(buf, /* bufferIsImmutable= */ false); } /** Create a new CodedInputStream wrapping the given buffer. */ @@ -410,7 +413,6 @@ public abstract class CodedInputStream { return oldLimit; } - private boolean shouldDiscardUnknownFields = false; /** diff --git a/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java b/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java index 7b1ac65120..975cb90e00 100644 --- a/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java +++ b/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java @@ -47,12 +47,11 @@ import java.util.logging.Logger; /** * Encodes and writes protocol message fields. * - *

This class contains two kinds of methods: methods that write specific - * protocol message constructs and field types (e.g. {@link #writeTag} and - * {@link #writeInt32}) and methods that write low-level values (e.g. - * {@link #writeRawVarint32} and {@link #writeRawBytes}). If you are - * writing encoded protocol messages, you should use the former methods, but if - * you are writing some other format of your own design, use the latter. + *

This class contains two kinds of methods: methods that write specific protocol message + * constructs and field types (e.g. {@link #writeTag} and {@link #writeInt32}) and methods that + * write low-level values (e.g. {@link #writeRawVarint32} and {@link #writeRawBytes}). If you are + * writing encoded protocol messages, you should use the former methods, but if you are writing some + * other format of your own design, use the latter. * *

This class is totally unsynchronized. */ @@ -60,23 +59,17 @@ public abstract class CodedOutputStream extends ByteOutput { private static final Logger logger = Logger.getLogger(CodedOutputStream.class.getName()); private static final boolean HAS_UNSAFE_ARRAY_OPERATIONS = UnsafeUtil.hasUnsafeArrayOperations(); - /** - * @deprecated Use {@link #computeFixed32SizeNoTag(int)} instead. - */ - @Deprecated - public static final int LITTLE_ENDIAN_32_SIZE = FIXED32_SIZE; + /** @deprecated Use {@link #computeFixed32SizeNoTag(int)} instead. */ + @Deprecated public static final int LITTLE_ENDIAN_32_SIZE = FIXED32_SIZE; - /** - * The buffer size used in {@link #newInstance(OutputStream)}. - */ + /** The buffer size used in {@link #newInstance(OutputStream)}. */ public static final int DEFAULT_BUFFER_SIZE = 4096; /** - * Returns the buffer size to efficiently write dataLength bytes to this - * CodedOutputStream. Used by AbstractMessageLite. + * Returns the buffer size to efficiently write dataLength bytes to this CodedOutputStream. Used + * by AbstractMessageLite. * - * @return the buffer size to efficiently write dataLength bytes to this - * CodedOutputStream. + * @return the buffer size to efficiently write dataLength bytes to this CodedOutputStream. */ static int computePreferredBufferSize(int dataLength) { if (dataLength > DEFAULT_BUFFER_SIZE) { @@ -88,9 +81,9 @@ public abstract class CodedOutputStream extends ByteOutput { /** * Create a new {@code CodedOutputStream} wrapping the given {@code OutputStream}. * - *

NOTE: The provided {@link OutputStream} MUST NOT retain access or - * modify the provided byte arrays. Doing so may result in corrupted data, which would be - * difficult to debug. + *

NOTE: The provided {@link OutputStream} MUST NOT retain access or modify + * the provided byte arrays. Doing so may result in corrupted data, which would be difficult to + * debug. */ public static CodedOutputStream newInstance(final OutputStream output) { return newInstance(output, DEFAULT_BUFFER_SIZE); @@ -100,30 +93,28 @@ public abstract class CodedOutputStream extends ByteOutput { * Create a new {@code CodedOutputStream} wrapping the given {@code OutputStream} with a given * buffer size. * - *

NOTE: The provided {@link OutputStream} MUST NOT retain access or - * modify the provided byte arrays. Doing so may result in corrupted data, which would be - * difficult to debug. + *

NOTE: The provided {@link OutputStream} MUST NOT retain access or modify + * the provided byte arrays. Doing so may result in corrupted data, which would be difficult to + * debug. */ public static CodedOutputStream newInstance(final OutputStream output, final int bufferSize) { return new OutputStreamEncoder(output, bufferSize); } /** - * Create a new {@code CodedOutputStream} that writes directly to the given - * byte array. If more bytes are written than fit in the array, - * {@link OutOfSpaceException} will be thrown. Writing directly to a flat - * array is faster than writing to an {@code OutputStream}. See also - * {@link ByteString#newCodedBuilder}. + * Create a new {@code CodedOutputStream} that writes directly to the given byte array. If more + * bytes are written than fit in the array, {@link OutOfSpaceException} will be thrown. Writing + * directly to a flat array is faster than writing to an {@code OutputStream}. See also {@link + * ByteString#newCodedBuilder}. */ public static CodedOutputStream newInstance(final byte[] flatArray) { return newInstance(flatArray, 0, flatArray.length); } /** - * Create a new {@code CodedOutputStream} that writes directly to the given - * byte array slice. If more bytes are written than fit in the slice, - * {@link OutOfSpaceException} will be thrown. Writing directly to a flat - * array is faster than writing to an {@code OutputStream}. See also + * Create a new {@code CodedOutputStream} that writes directly to the given byte array slice. If + * more bytes are written than fit in the slice, {@link OutOfSpaceException} will be thrown. + * Writing directly to a flat array is faster than writing to an {@code OutputStream}. See also * {@link ByteString#newCodedBuilder}. */ public static CodedOutputStream newInstance( @@ -162,9 +153,9 @@ public abstract class CodedOutputStream extends ByteOutput { * implies: * *

    - *
  • repeated serialization of a message will return the same bytes - *
  • different processes of the same binary (which may be executing on different machines) will - * serialize equal messages to the same bytes. + *
  • repeated serialization of a message will return the same bytes + *
  • different processes of the same binary (which may be executing on different machines) + * will serialize equal messages to the same bytes. *
* *

Note the deterministic serialization is NOT canonical across languages; it is also unstable @@ -173,14 +164,14 @@ public abstract class CodedOutputStream extends ByteOutput { * their own canonicalization specification and implement the serializer using reflection APIs * rather than relying on this API. * - *

Once set, the serializer will: (Note this is an implementation detail and may subject to + *

Once set, the serializer will: (Note this is an implementation detail and may subject to * change in the future) * *

    - *
  • sort map entries by keys in lexicographical order or numerical order. Note: For string - * keys, the order is based on comparing the Unicode value of each character in the strings. - * The order may be different from the deterministic serialization in other languages where - * maps are sorted on the lexicographical order of the UTF8 encoded keys. + *
  • sort map entries by keys in lexicographical order or numerical order. Note: For string + * keys, the order is based on comparing the Unicode value of each character in the strings. + * The order may be different from the deterministic serialization in other languages where + * maps are sorted on the lexicographical order of the UTF8 encoded keys. *
*/ public void useDeterministicSerialization() { @@ -190,31 +181,32 @@ public abstract class CodedOutputStream extends ByteOutput { boolean isSerializationDeterministic() { return serializationDeterministic; } + private boolean serializationDeterministic; /** * Create a new {@code CodedOutputStream} that writes to the given {@link ByteBuffer}. * * @deprecated the size parameter is no longer used since use of an internal buffer is useless - * (and wasteful) when writing to a {@link ByteBuffer}. Use {@link #newInstance(ByteBuffer)} - * instead. + * (and wasteful) when writing to a {@link ByteBuffer}. Use {@link #newInstance(ByteBuffer)} + * instead. */ @Deprecated - public static CodedOutputStream newInstance(ByteBuffer byteBuffer, - @SuppressWarnings("unused") int unused) { + public static CodedOutputStream newInstance( + ByteBuffer byteBuffer, @SuppressWarnings("unused") int unused) { return newInstance(byteBuffer); } /** * Create a new {@code CodedOutputStream} that writes to the provided {@link ByteOutput}. * - *

NOTE: The {@link ByteOutput} MUST NOT modify the provided buffers. Doing - * so may result in corrupted data, which would be difficult to debug. + *

NOTE: The {@link ByteOutput} MUST NOT modify the provided buffers. Doing so + * may result in corrupted data, which would be difficult to debug. * * @param byteOutput the output target for encoded bytes. * @param bufferSize the size of the internal scratch buffer to be used for string encoding. - * Setting this to {@code 0} will disable buffering, requiring an allocation for each encoded - * string. + * Setting this to {@code 0} will disable buffering, requiring an allocation for each encoded + * string. */ static CodedOutputStream newInstance(ByteOutput byteOutput, int bufferSize) { if (bufferSize < 0) { @@ -225,8 +217,7 @@ public abstract class CodedOutputStream extends ByteOutput { } // Disallow construction outside of this class. - private CodedOutputStream() { - } + private CodedOutputStream() {} // ----------------------------------------------------------------- @@ -294,8 +285,8 @@ public abstract class CodedOutputStream extends ByteOutput { public abstract void writeBool(int fieldNumber, boolean value) throws IOException; /** - * Write an enum field, including tag, to the stream. The provided value is the numeric - * value used to represent the enum value on the wire (not the enum ordinal value). + * Write an enum field, including tag, to the stream. The provided value is the numeric value used + * to represent the enum value on the wire (not the enum ordinal value). */ public final void writeEnum(final int fieldNumber, final int value) throws IOException { writeInt32(fieldNumber, value); @@ -319,21 +310,17 @@ public abstract class CodedOutputStream extends ByteOutput { throws IOException; /** - * Write a {@code bytes} field, including tag, to the stream. - * This method will write all content of the ByteBuffer regardless of the - * current position and limit (i.e., the number of bytes to be written is - * value.capacity(), not value.remaining()). Furthermore, this method doesn't - * alter the state of the passed-in ByteBuffer. Its position, limit, mark, - * etc. will remain unchanged. If you only want to write the remaining bytes - * of a ByteBuffer, you can call - * {@code writeByteBuffer(fieldNumber, byteBuffer.slice())}. + * Write a {@code bytes} field, including tag, to the stream. This method will write all content + * of the ByteBuffer regardless of the current position and limit (i.e., the number of bytes to be + * written is value.capacity(), not value.remaining()). Furthermore, this method doesn't alter the + * state of the passed-in ByteBuffer. Its position, limit, mark, etc. will remain unchanged. If + * you only want to write the remaining bytes of a ByteBuffer, you can call {@code + * writeByteBuffer(fieldNumber, byteBuffer.slice())}. */ // Abstract to avoid overhead of additional virtual method calls. public abstract void writeByteBuffer(int fieldNumber, ByteBuffer value) throws IOException; - /** - * Write a single byte. - */ + /** Write a single byte. */ public final void writeRawByte(final byte value) throws IOException { write(value); } @@ -348,9 +335,7 @@ public abstract class CodedOutputStream extends ByteOutput { write(value, 0, value.length); } - /** - * Write part of an array of bytes. - */ + /** Write part of an array of bytes. */ public final void writeRawBytes(final byte[] value, int offset, int length) throws IOException { write(value, offset, length); } @@ -361,13 +346,11 @@ public abstract class CodedOutputStream extends ByteOutput { } /** - * Write a ByteBuffer. This method will write all content of the ByteBuffer - * regardless of the current position and limit (i.e., the number of bytes - * to be written is value.capacity(), not value.remaining()). Furthermore, - * this method doesn't alter the state of the passed-in ByteBuffer. Its - * position, limit, mark, etc. will remain unchanged. If you only want to - * write the remaining bytes of a ByteBuffer, you can call - * {@code writeRawBytes(byteBuffer.slice())}. + * Write a ByteBuffer. This method will write all content of the ByteBuffer regardless of the + * current position and limit (i.e., the number of bytes to be written is value.capacity(), not + * value.remaining()). Furthermore, this method doesn't alter the state of the passed-in + * ByteBuffer. Its position, limit, mark, etc. will remain unchanged. If you only want to write + * the remaining bytes of a ByteBuffer, you can call {@code writeRawBytes(byteBuffer.slice())}. */ // Abstract to avoid overhead of additional virtual method calls. public abstract void writeRawBytes(final ByteBuffer value) throws IOException; @@ -379,16 +362,16 @@ public abstract class CodedOutputStream extends ByteOutput { /** - * Write a MessageSet extension field to the stream. For historical reasons, - * the wire format differs from normal fields. + * Write a MessageSet extension field to the stream. For historical reasons, the wire format + * differs from normal fields. */ // Abstract to avoid overhead of additional virtual method calls. public abstract void writeMessageSetExtension(final int fieldNumber, final MessageLite value) throws IOException; /** - * Write an unparsed MessageSet extension field to the stream. For - * historical reasons, the wire format differs from normal fields. + * Write an unparsed MessageSet extension field to the stream. For historical reasons, the wire + * format differs from normal fields. */ // Abstract to avoid overhead of additional virtual method calls. public abstract void writeRawMessageSetExtension(final int fieldNumber, final ByteString value) @@ -457,8 +440,8 @@ public abstract class CodedOutputStream extends ByteOutput { } /** - * Write an enum field to the stream. The provided value is the numeric - * value used to represent the enum value on the wire (not the enum ordinal value). + * Write an enum field to the stream. The provided value is the numeric value used to represent + * the enum value on the wire (not the enum ordinal value). */ public final void writeEnumNoTag(final int value) throws IOException { writeInt32NoTag(value); @@ -483,7 +466,7 @@ public abstract class CodedOutputStream extends ByteOutput { public abstract void writeMessageNoTag(final MessageLite value) throws IOException; - //================================================================= + // ================================================================= @ExperimentalApi @Override @@ -508,161 +491,160 @@ public abstract class CodedOutputStream extends ByteOutput { // ================================================================= /** - * Compute the number of bytes that would be needed to encode an - * {@code int32} field, including tag. + * Compute the number of bytes that would be needed to encode an {@code int32} field, including + * tag. */ public static int computeInt32Size(final int fieldNumber, final int value) { return computeTagSize(fieldNumber) + computeInt32SizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode a - * {@code uint32} field, including tag. + * Compute the number of bytes that would be needed to encode a {@code uint32} field, including + * tag. */ public static int computeUInt32Size(final int fieldNumber, final int value) { return computeTagSize(fieldNumber) + computeUInt32SizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode an - * {@code sint32} field, including tag. + * Compute the number of bytes that would be needed to encode an {@code sint32} field, including + * tag. */ public static int computeSInt32Size(final int fieldNumber, final int value) { return computeTagSize(fieldNumber) + computeSInt32SizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode a - * {@code fixed32} field, including tag. + * Compute the number of bytes that would be needed to encode a {@code fixed32} field, including + * tag. */ public static int computeFixed32Size(final int fieldNumber, final int value) { return computeTagSize(fieldNumber) + computeFixed32SizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode an - * {@code sfixed32} field, including tag. + * Compute the number of bytes that would be needed to encode an {@code sfixed32} field, including + * tag. */ public static int computeSFixed32Size(final int fieldNumber, final int value) { return computeTagSize(fieldNumber) + computeSFixed32SizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode an - * {@code int64} field, including tag. + * Compute the number of bytes that would be needed to encode an {@code int64} field, including + * tag. */ public static int computeInt64Size(final int fieldNumber, final long value) { return computeTagSize(fieldNumber) + computeInt64SizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode a - * {@code uint64} field, including tag. + * Compute the number of bytes that would be needed to encode a {@code uint64} field, including + * tag. */ public static int computeUInt64Size(final int fieldNumber, final long value) { return computeTagSize(fieldNumber) + computeUInt64SizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode an - * {@code sint64} field, including tag. + * Compute the number of bytes that would be needed to encode an {@code sint64} field, including + * tag. */ public static int computeSInt64Size(final int fieldNumber, final long value) { return computeTagSize(fieldNumber) + computeSInt64SizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode a - * {@code fixed64} field, including tag. + * Compute the number of bytes that would be needed to encode a {@code fixed64} field, including + * tag. */ public static int computeFixed64Size(final int fieldNumber, final long value) { return computeTagSize(fieldNumber) + computeFixed64SizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode an - * {@code sfixed64} field, including tag. + * Compute the number of bytes that would be needed to encode an {@code sfixed64} field, including + * tag. */ public static int computeSFixed64Size(final int fieldNumber, final long value) { return computeTagSize(fieldNumber) + computeSFixed64SizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode a - * {@code float} field, including tag. + * Compute the number of bytes that would be needed to encode a {@code float} field, including + * tag. */ public static int computeFloatSize(final int fieldNumber, final float value) { return computeTagSize(fieldNumber) + computeFloatSizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode a - * {@code double} field, including tag. + * Compute the number of bytes that would be needed to encode a {@code double} field, including + * tag. */ public static int computeDoubleSize(final int fieldNumber, final double value) { return computeTagSize(fieldNumber) + computeDoubleSizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode a - * {@code bool} field, including tag. + * Compute the number of bytes that would be needed to encode a {@code bool} field, including tag. */ public static int computeBoolSize(final int fieldNumber, final boolean value) { return computeTagSize(fieldNumber) + computeBoolSizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode an - * enum field, including tag. The provided value is the numeric - * value used to represent the enum value on the wire (not the enum ordinal value). + * Compute the number of bytes that would be needed to encode an enum field, including tag. The + * provided value is the numeric value used to represent the enum value on the wire (not the enum + * ordinal value). */ public static int computeEnumSize(final int fieldNumber, final int value) { return computeTagSize(fieldNumber) + computeEnumSizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode a - * {@code string} field, including tag. + * Compute the number of bytes that would be needed to encode a {@code string} field, including + * tag. */ public static int computeStringSize(final int fieldNumber, final String value) { return computeTagSize(fieldNumber) + computeStringSizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode a - * {@code bytes} field, including tag. + * Compute the number of bytes that would be needed to encode a {@code bytes} field, including + * tag. */ public static int computeBytesSize(final int fieldNumber, final ByteString value) { return computeTagSize(fieldNumber) + computeBytesSizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode a - * {@code bytes} field, including tag. + * Compute the number of bytes that would be needed to encode a {@code bytes} field, including + * tag. */ public static int computeByteArraySize(final int fieldNumber, final byte[] value) { return computeTagSize(fieldNumber) + computeByteArraySizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode a - * {@code bytes} field, including tag. + * Compute the number of bytes that would be needed to encode a {@code bytes} field, including + * tag. */ public static int computeByteBufferSize(final int fieldNumber, final ByteBuffer value) { return computeTagSize(fieldNumber) + computeByteBufferSizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode an - * embedded message in lazy field, including tag. + * Compute the number of bytes that would be needed to encode an embedded message in lazy field, + * including tag. */ public static int computeLazyFieldSize(final int fieldNumber, final LazyFieldLite value) { return computeTagSize(fieldNumber) + computeLazyFieldSizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode an - * embedded message field, including tag. + * Compute the number of bytes that would be needed to encode an embedded message field, including + * tag. */ public static int computeMessageSize(final int fieldNumber, final MessageLite value) { return computeTagSize(fieldNumber) + computeMessageSizeNoTag(value); @@ -670,9 +652,8 @@ public abstract class CodedOutputStream extends ByteOutput { /** - * Compute the number of bytes that would be needed to encode a - * MessageSet extension to the stream. For historical reasons, - * the wire format differs from normal fields. + * Compute the number of bytes that would be needed to encode a MessageSet extension to the + * stream. For historical reasons, the wire format differs from normal fields. */ public static int computeMessageSetExtensionSize(final int fieldNumber, final MessageLite value) { return computeTagSize(WireFormat.MESSAGE_SET_ITEM) * 2 @@ -681,9 +662,8 @@ public abstract class CodedOutputStream extends ByteOutput { } /** - * Compute the number of bytes that would be needed to encode an - * unparsed MessageSet extension field to the stream. For - * historical reasons, the wire format differs from normal fields. + * Compute the number of bytes that would be needed to encode an unparsed MessageSet extension + * field to the stream. For historical reasons, the wire format differs from normal fields. */ public static int computeRawMessageSetExtensionSize( final int fieldNumber, final ByteString value) { @@ -693,9 +673,9 @@ public abstract class CodedOutputStream extends ByteOutput { } /** - * Compute the number of bytes that would be needed to encode an - * lazily parsed MessageSet extension field to the stream. For - * historical reasons, the wire format differs from normal fields. + * Compute the number of bytes that would be needed to encode an lazily parsed MessageSet + * extension field to the stream. For historical reasons, the wire format differs from normal + * fields. */ public static int computeLazyFieldMessageSetExtensionSize( final int fieldNumber, final LazyFieldLite value) { @@ -712,8 +692,8 @@ public abstract class CodedOutputStream extends ByteOutput { } /** - * Compute the number of bytes that would be needed to encode an - * {@code int32} field, including tag. + * Compute the number of bytes that would be needed to encode an {@code int32} field, including + * tag. */ public static int computeInt32SizeNoTag(final int value) { if (value >= 0) { @@ -724,12 +704,9 @@ public abstract class CodedOutputStream extends ByteOutput { } } - /** - * Compute the number of bytes that would be needed to encode a - * {@code uint32} field. - */ + /** Compute the number of bytes that would be needed to encode a {@code uint32} field. */ public static int computeUInt32SizeNoTag(final int value) { - if ((value & (~0 << 7)) == 0) { + if ((value & (~0 << 7)) == 0) { return 1; } if ((value & (~0 << 14)) == 0) { @@ -744,41 +721,32 @@ public abstract class CodedOutputStream extends ByteOutput { return 5; } - /** - * Compute the number of bytes that would be needed to encode an - * {@code sint32} field. - */ + /** Compute the number of bytes that would be needed to encode an {@code sint32} field. */ public static int computeSInt32SizeNoTag(final int value) { return computeUInt32SizeNoTag(encodeZigZag32(value)); } - /** - * Compute the number of bytes that would be needed to encode a - * {@code fixed32} field. - */ + /** Compute the number of bytes that would be needed to encode a {@code fixed32} field. */ public static int computeFixed32SizeNoTag(@SuppressWarnings("unused") final int unused) { return FIXED32_SIZE; } - /** - * Compute the number of bytes that would be needed to encode an - * {@code sfixed32} field. - */ + /** Compute the number of bytes that would be needed to encode an {@code sfixed32} field. */ public static int computeSFixed32SizeNoTag(@SuppressWarnings("unused") final int unused) { return FIXED32_SIZE; } /** - * Compute the number of bytes that would be needed to encode an - * {@code int64} field, including tag. + * Compute the number of bytes that would be needed to encode an {@code int64} field, including + * tag. */ public static int computeInt64SizeNoTag(final long value) { return computeUInt64SizeNoTag(value); } /** - * Compute the number of bytes that would be needed to encode a - * {@code uint64} field, including tag. + * Compute the number of bytes that would be needed to encode a {@code uint64} field, including + * tag. */ public static int computeUInt64SizeNoTag(long value) { // handle two popular special cases up front ... @@ -791,10 +759,12 @@ public abstract class CodedOutputStream extends ByteOutput { // ... leaving us with 8 remaining, which we can divide and conquer int n = 2; if ((value & (~0L << 35)) != 0L) { - n += 4; value >>>= 28; + n += 4; + value >>>= 28; } if ((value & (~0L << 21)) != 0L) { - n += 2; value >>>= 14; + n += 2; + value >>>= 14; } if ((value & (~0L << 14)) != 0L) { n += 1; @@ -802,67 +772,51 @@ public abstract class CodedOutputStream extends ByteOutput { return n; } - /** - * Compute the number of bytes that would be needed to encode an - * {@code sint64} field. - */ + /** Compute the number of bytes that would be needed to encode an {@code sint64} field. */ public static int computeSInt64SizeNoTag(final long value) { return computeUInt64SizeNoTag(encodeZigZag64(value)); } - /** - * Compute the number of bytes that would be needed to encode a - * {@code fixed64} field. - */ + /** Compute the number of bytes that would be needed to encode a {@code fixed64} field. */ public static int computeFixed64SizeNoTag(@SuppressWarnings("unused") final long unused) { return FIXED64_SIZE; } - /** - * Compute the number of bytes that would be needed to encode an - * {@code sfixed64} field. - */ + /** Compute the number of bytes that would be needed to encode an {@code sfixed64} field. */ public static int computeSFixed64SizeNoTag(@SuppressWarnings("unused") final long unused) { return FIXED64_SIZE; } /** - * Compute the number of bytes that would be needed to encode a - * {@code float} field, including tag. + * Compute the number of bytes that would be needed to encode a {@code float} field, including + * tag. */ public static int computeFloatSizeNoTag(@SuppressWarnings("unused") final float unused) { return FIXED32_SIZE; } /** - * Compute the number of bytes that would be needed to encode a - * {@code double} field, including tag. + * Compute the number of bytes that would be needed to encode a {@code double} field, including + * tag. */ public static int computeDoubleSizeNoTag(@SuppressWarnings("unused") final double unused) { return FIXED64_SIZE; } - /** - * Compute the number of bytes that would be needed to encode a - * {@code bool} field. - */ + /** Compute the number of bytes that would be needed to encode a {@code bool} field. */ public static int computeBoolSizeNoTag(@SuppressWarnings("unused") final boolean unused) { return 1; } /** - * Compute the number of bytes that would be needed to encode an enum field. - * The provided value is the numeric value used to represent the enum value on the wire - * (not the enum ordinal value). + * Compute the number of bytes that would be needed to encode an enum field. The provided value is + * the numeric value used to represent the enum value on the wire (not the enum ordinal value). */ public static int computeEnumSizeNoTag(final int value) { return computeInt32SizeNoTag(value); } - /** - * Compute the number of bytes that would be needed to encode a - * {@code string} field. - */ + /** Compute the number of bytes that would be needed to encode a {@code string} field. */ public static int computeStringSizeNoTag(final String value) { int length; try { @@ -877,41 +831,29 @@ public abstract class CodedOutputStream extends ByteOutput { } /** - * Compute the number of bytes that would be needed to encode an embedded - * message stored in lazy field. + * Compute the number of bytes that would be needed to encode an embedded message stored in lazy + * field. */ public static int computeLazyFieldSizeNoTag(final LazyFieldLite value) { return computeLengthDelimitedFieldSize(value.getSerializedSize()); } - /** - * Compute the number of bytes that would be needed to encode a - * {@code bytes} field. - */ + /** Compute the number of bytes that would be needed to encode a {@code bytes} field. */ public static int computeBytesSizeNoTag(final ByteString value) { return computeLengthDelimitedFieldSize(value.size()); } - /** - * Compute the number of bytes that would be needed to encode a - * {@code bytes} field. - */ + /** Compute the number of bytes that would be needed to encode a {@code bytes} field. */ public static int computeByteArraySizeNoTag(final byte[] value) { return computeLengthDelimitedFieldSize(value.length); } - /** - * Compute the number of bytes that would be needed to encode a - * {@code bytes} field. - */ + /** Compute the number of bytes that would be needed to encode a {@code bytes} field. */ public static int computeByteBufferSizeNoTag(final ByteBuffer value) { return computeLengthDelimitedFieldSize(value.capacity()); } - /** - * Compute the number of bytes that would be needed to encode an embedded - * message field. - */ + /** Compute the number of bytes that would be needed to encode an embedded message field. */ public static int computeMessageSizeNoTag(final MessageLite value) { return computeLengthDelimitedFieldSize(value.getSerializedSize()); } @@ -922,14 +864,13 @@ public abstract class CodedOutputStream extends ByteOutput { } /** - * Encode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers - * into values that can be efficiently encoded with varint. (Otherwise, - * negative values must be sign-extended to 64 bits to be varint encoded, - * thus always taking 10 bytes on the wire.) + * Encode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers into values that can be + * efficiently encoded with varint. (Otherwise, negative values must be sign-extended to 64 bits + * to be varint encoded, thus always taking 10 bytes on the wire.) * * @param n A signed 32-bit integer. - * @return An unsigned 32-bit integer, stored in a signed int because - * Java has no explicit unsigned support. + * @return An unsigned 32-bit integer, stored in a signed int because Java has no explicit + * unsigned support. */ public static int encodeZigZag32(final int n) { // Note: the right-shift must be arithmetic @@ -937,14 +878,13 @@ public abstract class CodedOutputStream extends ByteOutput { } /** - * Encode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers - * into values that can be efficiently encoded with varint. (Otherwise, - * negative values must be sign-extended to 64 bits to be varint encoded, - * thus always taking 10 bytes on the wire.) + * Encode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers into values that can be + * efficiently encoded with varint. (Otherwise, negative values must be sign-extended to 64 bits + * to be varint encoded, thus always taking 10 bytes on the wire.) * * @param n A signed 64-bit integer. - * @return An unsigned 64-bit integer, stored in a signed int because - * Java has no explicit unsigned support. + * @return An unsigned 64-bit integer, stored in a signed int because Java has no explicit + * unsigned support. */ public static long encodeZigZag64(final long n) { // Note: the right-shift must be arithmetic @@ -954,23 +894,22 @@ public abstract class CodedOutputStream extends ByteOutput { // ================================================================= /** - * Flushes the stream and forces any buffered bytes to be written. This - * does not flush the underlying OutputStream. + * Flushes the stream and forces any buffered bytes to be written. This does not flush the + * underlying OutputStream. */ public abstract void flush() throws IOException; /** - * If writing to a flat array, return the space left in the array. - * Otherwise, throws {@code UnsupportedOperationException}. + * If writing to a flat array, return the space left in the array. Otherwise, throws {@code + * UnsupportedOperationException}. */ public abstract int spaceLeft(); /** - * Verifies that {@link #spaceLeft()} returns zero. It's common to create - * a byte array that is exactly big enough to hold a message, then write to - * it with a {@code CodedOutputStream}. Calling {@code checkNoSpaceLeft()} - * after writing verifies that the message was actually as big as expected, - * which can help catch bugs. + * Verifies that {@link #spaceLeft()} returns zero. It's common to create a byte array that is + * exactly big enough to hold a message, then write to it with a {@code CodedOutputStream}. + * Calling {@code checkNoSpaceLeft()} after writing verifies that the message was actually as big + * as expected, which can help catch bugs. */ public final void checkNoSpaceLeft() { if (spaceLeft() != 0) { @@ -979,9 +918,8 @@ public abstract class CodedOutputStream extends ByteOutput { } /** - * If you create a CodedOutputStream around a simple flat array, you must - * not attempt to write more bytes than the array has space. Otherwise, - * this exception will be thrown. + * If you create a CodedOutputStream around a simple flat array, you must not attempt to write + * more bytes than the array has space. Otherwise, this exception will be thrown. */ public static class OutOfSpaceException extends IOException { private static final long serialVersionUID = -6947486886997889499L; @@ -1007,9 +945,8 @@ public abstract class CodedOutputStream extends ByteOutput { } /** - * Get the total number of bytes successfully written to this stream. The - * returned value is not guaranteed to be accurate if exceptions have been - * found in the middle of writing. + * Get the total number of bytes successfully written to this stream. The returned value is not + * guaranteed to be accurate if exceptions have been found in the middle of writing. */ public abstract int getTotalBytesWritten(); @@ -1021,8 +958,10 @@ public abstract class CodedOutputStream extends ByteOutput { final void inefficientWriteStringNoTag(String value, UnpairedSurrogateException cause) throws IOException { - logger.log(Level.WARNING, - "Converting ill-formed UTF-16. Your Protocol Buffer will not round trip correctly!", cause); + logger.log( + Level.WARNING, + "Converting ill-formed UTF-16. Your Protocol Buffer will not round trip correctly!", + cause); // Unfortunately there does not appear to be any way to tell Java to encode // UTF-8 directly into our buffer, so we have to let it create its own byte @@ -1066,8 +1005,8 @@ public abstract class CodedOutputStream extends ByteOutput { /** - * Compute the number of bytes that would be needed to encode a - * {@code group} field, including tag. + * Compute the number of bytes that would be needed to encode a {@code group} field, including + * tag. * * @deprecated groups are deprecated. */ @@ -1077,10 +1016,7 @@ public abstract class CodedOutputStream extends ByteOutput { } - /** - * Compute the number of bytes that would be needed to encode a - * {@code group} field. - */ + /** Compute the number of bytes that would be needed to encode a {@code group} field. */ @Deprecated public static int computeGroupSizeNoTag(final MessageLite value) { return value.getSerializedSize(); @@ -1088,8 +1024,8 @@ public abstract class CodedOutputStream extends ByteOutput { /** - * Encode and write a varint. {@code value} is treated as - * unsigned, so it won't be sign-extended if negative. + * Encode and write a varint. {@code value} is treated as unsigned, so it won't be sign-extended + * if negative. * * @deprecated use {@link #writeUInt32NoTag} instead. */ @@ -1109,9 +1045,8 @@ public abstract class CodedOutputStream extends ByteOutput { } /** - * Compute the number of bytes that would be needed to encode a varint. - * {@code value} is treated as unsigned, so it won't be sign-extended if - * negative. + * Compute the number of bytes that would be needed to encode a varint. {@code value} is treated + * as unsigned, so it won't be sign-extended if negative. * * @deprecated use {@link #computeUInt32SizeNoTag(int)} instead. */ @@ -1152,9 +1087,7 @@ public abstract class CodedOutputStream extends ByteOutput { // ================================================================= - /** - * A {@link CodedOutputStream} that writes directly to a byte array. - */ + /** A {@link CodedOutputStream} that writes directly to a byte array. */ private static class ArrayEncoder extends CodedOutputStream { private final byte[] buffer; private final int offset; @@ -1166,9 +1099,10 @@ public abstract class CodedOutputStream extends ByteOutput { throw new NullPointerException("buffer"); } if ((offset | length | (buffer.length - (offset + length))) < 0) { - throw new IllegalArgumentException(String.format( - "Array range is invalid. Buffer.length=%d, offset=%d, length=%d", - buffer.length, offset, length)); + throw new IllegalArgumentException( + String.format( + "Array range is invalid. Buffer.length=%d, offset=%d, length=%d", + buffer.length, offset, length)); } this.buffer = buffer; this.offset = offset; @@ -1501,15 +1435,17 @@ public abstract class CodedOutputStream extends ByteOutput { } /** - * A {@link CodedOutputStream} that writes directly to a heap {@link ByteBuffer}. Writes are - * done directly to the underlying array. The buffer position is only updated after a flush. + * A {@link CodedOutputStream} that writes directly to a heap {@link ByteBuffer}. Writes are done + * directly to the underlying array. The buffer position is only updated after a flush. */ private static final class HeapNioEncoder extends ArrayEncoder { private final ByteBuffer byteBuffer; private int initialPosition; HeapNioEncoder(ByteBuffer byteBuffer) { - super(byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(), + super( + byteBuffer.array(), + byteBuffer.arrayOffset() + byteBuffer.position(), byteBuffer.remaining()); this.byteBuffer = byteBuffer; this.initialPosition = byteBuffer.position(); @@ -1604,16 +1540,14 @@ public abstract class CodedOutputStream extends ByteOutput { } @Override - public void writeByteBuffer(final int fieldNumber, final ByteBuffer value) - throws IOException { + public void writeByteBuffer(final int fieldNumber, final ByteBuffer value) throws IOException { writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED); writeUInt32NoTag(value.capacity()); writeRawBytes(value); } @Override - public void writeMessage(final int fieldNumber, final MessageLite value) - throws IOException { + public void writeMessage(final int fieldNumber, final MessageLite value) throws IOException { writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED); writeMessageNoTag(value); } @@ -2186,9 +2120,7 @@ public abstract class CodedOutputStream extends ByteOutput { } } - /** - * Abstract base class for buffered encoders. - */ + /** Abstract base class for buffered encoders. */ private abstract static class AbstractBufferedEncoder extends CodedOutputStream { final byte[] buffer; final int limit; @@ -2346,8 +2278,8 @@ public abstract class CodedOutputStream extends ByteOutput { /** * A {@link CodedOutputStream} that decorates a {@link ByteOutput}. It internal buffer only to - * support string encoding operations. All other writes are just passed through to the - * {@link ByteOutput}. + * support string encoding operations. All other writes are just passed through to the {@link + * ByteOutput}. */ private static final class ByteOutputEncoder extends AbstractBufferedEncoder { private final ByteOutput out; @@ -2433,8 +2365,7 @@ public abstract class CodedOutputStream extends ByteOutput { } @Override - public void writeByteBuffer(final int fieldNumber, final ByteBuffer value) - throws IOException { + public void writeByteBuffer(final int fieldNumber, final ByteBuffer value) throws IOException { writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED); writeUInt32NoTag(value.capacity()); writeRawBytes(value); @@ -2464,8 +2395,7 @@ public abstract class CodedOutputStream extends ByteOutput { } @Override - public void writeMessage(final int fieldNumber, final MessageLite value) - throws IOException { + public void writeMessage(final int fieldNumber, final MessageLite value) throws IOException { writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED); writeMessageNoTag(value); } @@ -2738,8 +2668,7 @@ public abstract class CodedOutputStream extends ByteOutput { } @Override - public void writeByteBuffer(final int fieldNumber, final ByteBuffer value) - throws IOException { + public void writeByteBuffer(final int fieldNumber, final ByteBuffer value) throws IOException { writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED); writeUInt32NoTag(value.capacity()); writeRawBytes(value); @@ -2769,8 +2698,7 @@ public abstract class CodedOutputStream extends ByteOutput { } @Override - public void writeMessage(final int fieldNumber, final MessageLite value) - throws IOException { + public void writeMessage(final int fieldNumber, final MessageLite value) throws IOException { writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED); writeMessageNoTag(value); } @@ -2916,8 +2844,7 @@ public abstract class CodedOutputStream extends ByteOutput { } @Override - public void write(byte[] value, int offset, int length) - throws IOException { + public void write(byte[] value, int offset, int length) throws IOException { if (limit - position >= length) { // We have room in the current buffer. System.arraycopy(value, offset, buffer, position, length); diff --git a/java/core/src/main/java/com/google/protobuf/Descriptors.java b/java/core/src/main/java/com/google/protobuf/Descriptors.java index 75b16fe30e..8f751925c4 100644 --- a/java/core/src/main/java/com/google/protobuf/Descriptors.java +++ b/java/core/src/main/java/com/google/protobuf/Descriptors.java @@ -49,29 +49,25 @@ import java.util.logging.Logger; /** * Contains a collection of classes which describe protocol message types. * - * Every message type has a {@link Descriptor}, which lists all - * its fields and other information about a type. You can get a message - * type's descriptor by calling {@code MessageType.getDescriptor()}, or - * (given a message object of the type) {@code message.getDescriptorForType()}. - * Furthermore, each message is associated with a {@link FileDescriptor} for - * a relevant {@code .proto} file. You can obtain it by calling - * {@code Descriptor.getFile()}. A {@link FileDescriptor} contains descriptors - * for all the messages defined in that file, and file descriptors for all the - * imported {@code .proto} files. + *

Every message type has a {@link Descriptor}, which lists all its fields and other information + * about a type. You can get a message type's descriptor by calling {@code + * MessageType.getDescriptor()}, or (given a message object of the type) {@code + * message.getDescriptorForType()}. Furthermore, each message is associated with a {@link + * FileDescriptor} for a relevant {@code .proto} file. You can obtain it by calling {@code + * Descriptor.getFile()}. A {@link FileDescriptor} contains descriptors for all the messages defined + * in that file, and file descriptors for all the imported {@code .proto} files. * - * Descriptors are built from DescriptorProtos, as defined in - * {@code google/protobuf/descriptor.proto}. + *

Descriptors are built from DescriptorProtos, as defined in {@code + * google/protobuf/descriptor.proto}. * * @author kenton@google.com Kenton Varda */ public final class Descriptors { - private static final Logger logger = - Logger.getLogger(Descriptors.class.getName()); + private static final Logger logger = Logger.getLogger(Descriptors.class.getName()); /** - * Describes a {@code .proto} file, including everything defined within. - * That includes, in particular, descriptors for all the messages and - * file descriptors for all other imported {@code .proto} files - * (dependencies). + * Describes a {@code .proto} file, including everything defined within. That includes, in + * particular, descriptors for all the messages and file descriptors for all other imported {@code + * .proto} files (dependencies). */ public static final class FileDescriptor extends GenericDescriptor { /** Convert the descriptor to its protocol message representation. */ @@ -99,14 +95,17 @@ public final class Descriptors { } /** - * Get the proto package name. This is the package name given by the - * {@code package} statement in the {@code .proto} file, which differs - * from the Java package. + * Get the proto package name. This is the package name given by the {@code package} statement + * in the {@code .proto} file, which differs from the Java package. */ - public String getPackage() { return proto.getPackage(); } + public String getPackage() { + return proto.getPackage(); + } /** Get the {@code FileOptions}, defined in {@code descriptor.proto}. */ - public FileOptions getOptions() { return proto.getOptions(); } + public FileOptions getOptions() { + return proto.getOptions(); + } /** Get a list of top-level message types declared in this file. */ public List getMessageTypes() { @@ -147,6 +146,7 @@ public final class Descriptors { Syntax(String name) { this.name = name; } + private final String name; } @@ -159,7 +159,7 @@ public final class Descriptors { } /** - * Find a message type in the file by name. Does not find nested types. + * Find a message type in the file by name. Does not find nested types. * * @param name The unqualified type name to look for. * @return The message type's descriptor, or {@code null} if not found. @@ -174,16 +174,15 @@ public final class Descriptors { name = getPackage() + '.' + name; } final GenericDescriptor result = pool.findSymbol(name); - if (result != null && result instanceof Descriptor && - result.getFile() == this) { - return (Descriptor)result; + if (result != null && result instanceof Descriptor && result.getFile() == this) { + return (Descriptor) result; } else { return null; } } /** - * Find an enum type in the file by name. Does not find nested types. + * Find an enum type in the file by name. Does not find nested types. * * @param name The unqualified type name to look for. * @return The enum type's descriptor, or {@code null} if not found. @@ -198,9 +197,8 @@ public final class Descriptors { name = getPackage() + '.' + name; } final GenericDescriptor result = pool.findSymbol(name); - if (result != null && result instanceof EnumDescriptor && - result.getFile() == this) { - return (EnumDescriptor)result; + if (result != null && result instanceof EnumDescriptor && result.getFile() == this) { + return (EnumDescriptor) result; } else { return null; } @@ -222,17 +220,15 @@ public final class Descriptors { name = getPackage() + '.' + name; } final GenericDescriptor result = pool.findSymbol(name); - if (result != null && result instanceof ServiceDescriptor && - result.getFile() == this) { - return (ServiceDescriptor)result; + if (result != null && result instanceof ServiceDescriptor && result.getFile() == this) { + return (ServiceDescriptor) result; } else { return null; } } /** - * Find an extension in the file by name. Does not find extensions nested - * inside message types. + * Find an extension in the file by name. Does not find extensions nested inside message types. * * @param name The unqualified extension name to look for. * @return The extension's descriptor, or {@code null} if not found. @@ -245,9 +241,8 @@ public final class Descriptors { name = getPackage() + '.' + name; } final GenericDescriptor result = pool.findSymbol(name); - if (result != null && result instanceof FieldDescriptor && - result.getFile() == this) { - return (FieldDescriptor)result; + if (result != null && result instanceof FieldDescriptor && result.getFile() == this) { + return (FieldDescriptor) result; } else { return null; } @@ -257,36 +252,31 @@ public final class Descriptors { * Construct a {@code FileDescriptor}. * * @param proto The protocol message form of the FileDescriptor. - * @param dependencies {@code FileDescriptor}s corresponding to all of - * the file's dependencies. - * @throws DescriptorValidationException {@code proto} is not a valid - * descriptor. This can occur for a number of reasons, e.g. - * because a field has an undefined type or because two messages - * were defined with the same name. + * @param dependencies {@code FileDescriptor}s corresponding to all of the file's dependencies. + * @throws DescriptorValidationException {@code proto} is not a valid descriptor. This can occur + * for a number of reasons, e.g. because a field has an undefined type or because two + * messages were defined with the same name. */ - public static FileDescriptor buildFrom(final FileDescriptorProto proto, - final FileDescriptor[] dependencies) - throws DescriptorValidationException { + public static FileDescriptor buildFrom( + final FileDescriptorProto proto, final FileDescriptor[] dependencies) + throws DescriptorValidationException { return buildFrom(proto, dependencies, false); } - /** * Construct a {@code FileDescriptor}. * * @param proto The protocol message form of the FileDescriptor. - * @param dependencies {@code FileDescriptor}s corresponding to all of - * the file's dependencies. - * @param allowUnknownDependencies If true, non-exist dependenncies will be - * ignored and undefined message types will be replaced with a - * placeholder type. - * @throws DescriptorValidationException {@code proto} is not a valid - * descriptor. This can occur for a number of reasons, e.g. - * because a field has an undefined type or because two messages - * were defined with the same name. + * @param dependencies {@code FileDescriptor}s corresponding to all of the file's dependencies. + * @param allowUnknownDependencies If true, non-exist dependenncies will be ignored and + * undefined message types will be replaced with a placeholder type. + * @throws DescriptorValidationException {@code proto} is not a valid descriptor. This can occur + * for a number of reasons, e.g. because a field has an undefined type or because two + * messages were defined with the same name. */ public static FileDescriptor buildFrom( - final FileDescriptorProto proto, final FileDescriptor[] dependencies, + final FileDescriptorProto proto, + final FileDescriptor[] dependencies, final boolean allowUnknownDependencies) throws DescriptorValidationException { // Building descriptors involves two steps: translating and linking. @@ -298,18 +288,16 @@ public final class Descriptors { // FieldDescriptor for an embedded message contains a pointer directly // to the Descriptor for that message's type. We also detect undefined // types in the linking step. - final DescriptorPool pool = new DescriptorPool( - dependencies, allowUnknownDependencies); - final FileDescriptor result = new FileDescriptor( - proto, dependencies, pool, allowUnknownDependencies); + final DescriptorPool pool = new DescriptorPool(dependencies, allowUnknownDependencies); + final FileDescriptor result = + new FileDescriptor(proto, dependencies, pool, allowUnknownDependencies); result.crossLink(); return result; } /** - * This method is to be called by generated code only. It is equivalent - * to {@code buildFrom} except that the {@code FileDescriptorProto} is - * encoded in protocol buffer wire format. + * This method is to be called by generated code only. It is equivalent to {@code buildFrom} + * except that the {@code FileDescriptorProto} is encoded in protocol buffer wire format. */ public static void internalBuildGeneratedFileFrom( final String[] descriptorDataParts, @@ -339,7 +327,7 @@ public final class Descriptors { proto = FileDescriptorProto.parseFrom(descriptorBytes); } catch (InvalidProtocolBufferException e) { throw new IllegalArgumentException( - "Failed to parse protocol buffer descriptor for generated code.", e); + "Failed to parse protocol buffer descriptor for generated code.", e); } final FileDescriptor result; @@ -349,11 +337,10 @@ public final class Descriptors { result = buildFrom(proto, dependencies, true); } catch (DescriptorValidationException e) { throw new IllegalArgumentException( - "Invalid embedded descriptor for \"" + proto.getName() + "\".", e); + "Invalid embedded descriptor for \"" + proto.getName() + "\".", e); } - final ExtensionRegistry registry = - descriptorAssigner.assignDescriptors(result); + final ExtensionRegistry registry = descriptorAssigner.assignDescriptors(result); if (registry != null) { // We must re-parse the proto using the registry. @@ -361,8 +348,7 @@ public final class Descriptors { proto = FileDescriptorProto.parseFrom(descriptorBytes, registry); } catch (InvalidProtocolBufferException e) { throw new IllegalArgumentException( - "Failed to parse protocol buffer descriptor for generated code.", - e); + "Failed to parse protocol buffer descriptor for generated code.", e); } result.setProto(proto); @@ -370,8 +356,8 @@ public final class Descriptors { } /** - * This method is to be called by generated code only. It uses Java - * reflection to load the dependencies' descriptors. + * This method is to be called by generated code only. It uses Java reflection to load the + * dependencies' descriptors. */ public static void internalBuildGeneratedFileFrom( final String[] descriptorDataParts, @@ -382,54 +368,46 @@ public final class Descriptors { List descriptors = new ArrayList(); for (int i = 0; i < dependencies.length; i++) { try { - Class clazz = - descriptorOuterClass.getClassLoader().loadClass(dependencies[i]); - descriptors.add( - (FileDescriptor) clazz.getField("descriptor").get(null)); + Class clazz = descriptorOuterClass.getClassLoader().loadClass(dependencies[i]); + descriptors.add((FileDescriptor) clazz.getField("descriptor").get(null)); } catch (Exception e) { // We allow unknown dependencies by default. If a dependency cannot // be found we only generate a warning. - logger.warning("Descriptors for \"" + dependencyFileNames[i] + - "\" can not be found."); + logger.warning("Descriptors for \"" + dependencyFileNames[i] + "\" can not be found."); } } FileDescriptor[] descriptorArray = new FileDescriptor[descriptors.size()]; descriptors.toArray(descriptorArray); - internalBuildGeneratedFileFrom( - descriptorDataParts, descriptorArray, descriptorAssigner); + internalBuildGeneratedFileFrom(descriptorDataParts, descriptorArray, descriptorAssigner); } /** - * This method is to be called by generated code only. It is used to - * update the FileDescriptorProto associated with the descriptor by - * parsing it again with the given ExtensionRegistry. This is needed to - * recognize custom options. + * This method is to be called by generated code only. It is used to update the + * FileDescriptorProto associated with the descriptor by parsing it again with the given + * ExtensionRegistry. This is needed to recognize custom options. */ public static void internalUpdateFileDescriptor( - final FileDescriptor descriptor, - final ExtensionRegistry registry) { + final FileDescriptor descriptor, final ExtensionRegistry registry) { ByteString bytes = descriptor.proto.toByteString(); FileDescriptorProto proto; try { proto = FileDescriptorProto.parseFrom(bytes, registry); } catch (InvalidProtocolBufferException e) { throw new IllegalArgumentException( - "Failed to parse protocol buffer descriptor for generated code.", e); + "Failed to parse protocol buffer descriptor for generated code.", e); } descriptor.setProto(proto); } /** - * This class should be used by generated code only. When calling - * {@link FileDescriptor#internalBuildGeneratedFileFrom}, the caller - * provides a callback implementing this interface. The callback is called - * after the FileDescriptor has been constructed, in order to assign all - * the global variables defined in the generated code which point at parts - * of the FileDescriptor. The callback returns an ExtensionRegistry which - * contains any extensions which might be used in the descriptor -- that - * is, extensions of the various "Options" messages defined in - * descriptor.proto. The callback may also return null to indicate that - * no extensions are used in the descriptor. + * This class should be used by generated code only. When calling {@link + * FileDescriptor#internalBuildGeneratedFileFrom}, the caller provides a callback implementing + * this interface. The callback is called after the FileDescriptor has been constructed, in + * order to assign all the global variables defined in the generated code which point at parts + * of the FileDescriptor. The callback returns an ExtensionRegistry which contains any + * extensions which might be used in the descriptor -- that is, extensions of the various + * "Options" messages defined in descriptor.proto. The callback may also return null to indicate + * that no extensions are used in the descriptor. */ public interface InternalDescriptorAssigner { ExtensionRegistry assignDescriptors(FileDescriptor root); @@ -444,16 +422,16 @@ public final class Descriptors { private final FileDescriptor[] publicDependencies; private final DescriptorPool pool; - private FileDescriptor(final FileDescriptorProto proto, - final FileDescriptor[] dependencies, - final DescriptorPool pool, - boolean allowUnknownDependencies) - throws DescriptorValidationException { + private FileDescriptor( + final FileDescriptorProto proto, + final FileDescriptor[] dependencies, + final DescriptorPool pool, + boolean allowUnknownDependencies) + throws DescriptorValidationException { this.pool = pool; this.proto = proto; this.dependencies = dependencies.clone(); - HashMap nameToFileMap = - new HashMap(); + HashMap nameToFileMap = new HashMap(); for (FileDescriptor file : dependencies) { nameToFileMap.put(file.getName(), file); } @@ -461,15 +439,13 @@ public final class Descriptors { for (int i = 0; i < proto.getPublicDependencyCount(); i++) { int index = proto.getPublicDependency(i); if (index < 0 || index >= proto.getDependencyCount()) { - throw new DescriptorValidationException(this, - "Invalid public dependency index."); + throw new DescriptorValidationException(this, "Invalid public dependency index."); } String name = proto.getDependency(index); FileDescriptor file = nameToFileMap.get(name); if (file == null) { if (!allowUnknownDependencies) { - throw new DescriptorValidationException(this, - "Invalid public dependency: " + name); + throw new DescriptorValidationException(this, "Invalid public dependency: " + name); } // Ignore unknown dependencies. } else { @@ -483,8 +459,7 @@ public final class Descriptors { messageTypes = new Descriptor[proto.getMessageTypeCount()]; for (int i = 0; i < proto.getMessageTypeCount(); i++) { - messageTypes[i] = - new Descriptor(proto.getMessageType(i), this, null, i); + messageTypes[i] = new Descriptor(proto.getMessageType(i), this, null, i); } enumTypes = new EnumDescriptor[proto.getEnumTypeCount()]; @@ -499,20 +474,19 @@ public final class Descriptors { extensions = new FieldDescriptor[proto.getExtensionCount()]; for (int i = 0; i < proto.getExtensionCount(); i++) { - extensions[i] = new FieldDescriptor( - proto.getExtension(i), this, null, i, true); + extensions[i] = new FieldDescriptor(proto.getExtension(i), this, null, i, true); } } - /** - * Create a placeholder FileDescriptor for a message Descriptor. - */ - FileDescriptor(String packageName, Descriptor message) - throws DescriptorValidationException { + /** Create a placeholder FileDescriptor for a message Descriptor. */ + FileDescriptor(String packageName, Descriptor message) throws DescriptorValidationException { this.pool = new DescriptorPool(new FileDescriptor[0], true); - this.proto = FileDescriptorProto.newBuilder() - .setName(message.getFullName() + ".placeholder.proto") - .setPackage(packageName).addMessageType(message.toProto()).build(); + this.proto = + FileDescriptorProto.newBuilder() + .setName(message.getFullName() + ".placeholder.proto") + .setPackage(packageName) + .addMessageType(message.toProto()) + .build(); this.dependencies = new FileDescriptor[0]; this.publicDependencies = new FileDescriptor[0]; @@ -541,14 +515,12 @@ public final class Descriptors { } /** - * Replace our {@link FileDescriptorProto} with the given one, which is - * identical except that it might contain extensions that weren't present - * in the original. This method is needed for bootstrapping when a file - * defines custom options. The options may be defined in the file itself, - * so we can't actually parse them until we've constructed the descriptors, - * but to construct the descriptors we have to have parsed the descriptor - * protos. So, we have to parse the descriptor protos a second time after - * constructing the descriptors. + * Replace our {@link FileDescriptorProto} with the given one, which is identical except that it + * might contain extensions that weren't present in the original. This method is needed for + * bootstrapping when a file defines custom options. The options may be defined in the file + * itself, so we can't actually parse them until we've constructed the descriptors, but to + * construct the descriptors we have to have parsed the descriptor protos. So, we have to parse + * the descriptor protos a second time after constructing the descriptors. */ private void setProto(final FileDescriptorProto proto) { this.proto = proto; @@ -580,19 +552,24 @@ public final class Descriptors { /** Describes a message type. */ public static final class Descriptor extends GenericDescriptor { /** - * Get the index of this descriptor within its parent. In other words, - * given a {@link FileDescriptor} {@code file}, the following is true: + * Get the index of this descriptor within its parent. In other words, given a {@link + * FileDescriptor} {@code file}, the following is true: + * *

      *   for all i in [0, file.getMessageTypeCount()):
      *     file.getMessageType(i).getIndex() == i
      * 
+ * * Similarly, for a {@link Descriptor} {@code messageType}: + * *
      *   for all i in [0, messageType.getNestedTypeCount()):
      *     messageType.getNestedType(i).getIndex() == i
      * 
*/ - public int getIndex() { return index; } + public int getIndex() { + return index; + } /** Convert the descriptor to its protocol message representation. */ @Override @@ -607,14 +584,15 @@ public final class Descriptors { } /** - * Get the type's fully-qualified name, within the proto language's - * namespace. This differs from the Java name. For example, given this - * {@code .proto}: + * Get the type's fully-qualified name, within the proto language's namespace. This differs from + * the Java name. For example, given this {@code .proto}: + * *
      *   package foo.bar;
      *   option java_package = "com.example.protos"
      *   message Baz {}
      * 
+ * * {@code Baz}'s full name is "foo.bar.Baz". */ @Override @@ -629,10 +607,14 @@ public final class Descriptors { } /** If this is a nested type, get the outer descriptor, otherwise null. */ - public Descriptor getContainingType() { return containingType; } + public Descriptor getContainingType() { + return containingType; + } /** Get the {@code MessageOptions}, defined in {@code descriptor.proto}. */ - public MessageOptions getOptions() { return proto.getOptions(); } + public MessageOptions getOptions() { + return proto.getOptions(); + } /** Get a list of this message type's fields. */ public List getFields() { @@ -661,8 +643,7 @@ public final class Descriptors { /** Determines if the given field number is an extension. */ public boolean isExtensionNumber(final int number) { - for (final DescriptorProto.ExtensionRange range : - proto.getExtensionRangeList()) { + for (final DescriptorProto.ExtensionRange range : proto.getExtensionRangeList()) { if (range.getStart() <= number && number < range.getEnd()) { return true; } @@ -672,8 +653,7 @@ public final class Descriptors { /** Determines if the given field number is reserved. */ public boolean isReservedNumber(final int number) { - for (final DescriptorProto.ReservedRange range : - proto.getReservedRangeList()) { + for (final DescriptorProto.ReservedRange range : proto.getReservedRangeList()) { if (range.getStart() <= number && number < range.getEnd()) { return true; } @@ -693,8 +673,8 @@ public final class Descriptors { } /** - * Indicates whether the message can be extended. That is, whether it has - * any "extensions x to y" ranges declared on it. + * Indicates whether the message can be extended. That is, whether it has any "extensions x to + * y" ranges declared on it. */ public boolean isExtendable() { return proto.getExtensionRangeList().size() != 0; @@ -702,14 +682,14 @@ public final class Descriptors { /** * Finds a field by name. + * * @param name The unqualified name of the field (e.g. "foo"). * @return The field's descriptor, or {@code null} if not found. */ public FieldDescriptor findFieldByName(final String name) { - final GenericDescriptor result = - file.pool.findSymbol(fullName + '.' + name); + final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name); if (result != null && result instanceof FieldDescriptor) { - return (FieldDescriptor)result; + return (FieldDescriptor) result; } else { return null; } @@ -717,24 +697,24 @@ public final class Descriptors { /** * Finds a field by field number. + * * @param number The field number within this message type. * @return The field's descriptor, or {@code null} if not found. */ public FieldDescriptor findFieldByNumber(final int number) { - return file.pool.fieldsByNumber.get( - new DescriptorPool.DescriptorIntPair(this, number)); + return file.pool.fieldsByNumber.get(new DescriptorPool.DescriptorIntPair(this, number)); } /** * Finds a nested message type by name. + * * @param name The unqualified name of the nested type (e.g. "Foo"). * @return The types's descriptor, or {@code null} if not found. */ public Descriptor findNestedTypeByName(final String name) { - final GenericDescriptor result = - file.pool.findSymbol(fullName + '.' + name); + final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name); if (result != null && result instanceof Descriptor) { - return (Descriptor)result; + return (Descriptor) result; } else { return null; } @@ -742,14 +722,14 @@ public final class Descriptors { /** * Finds a nested enum type by name. + * * @param name The unqualified name of the nested type (e.g. "Foo"). * @return The types's descriptor, or {@code null} if not found. */ public EnumDescriptor findEnumTypeByName(final String name) { - final GenericDescriptor result = - file.pool.findSymbol(fullName + '.' + name); + final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name); if (result != null && result instanceof EnumDescriptor) { - return (EnumDescriptor)result; + return (EnumDescriptor) result; } else { return null; } @@ -776,9 +756,12 @@ public final class Descriptors { packageName = fullname.substring(0, pos); } this.index = 0; - this.proto = DescriptorProto.newBuilder().setName(name).addExtensionRange( - DescriptorProto.ExtensionRange.newBuilder().setStart(1) - .setEnd(536870912).build()).build(); + this.proto = + DescriptorProto.newBuilder() + .setName(name) + .addExtensionRange( + DescriptorProto.ExtensionRange.newBuilder().setStart(1).setEnd(536870912).build()) + .build(); this.fullName = fullname; this.containingType = null; @@ -792,11 +775,12 @@ public final class Descriptors { this.file = new FileDescriptor(packageName, this); } - private Descriptor(final DescriptorProto proto, - final FileDescriptor file, - final Descriptor parent, - final int index) - throws DescriptorValidationException { + private Descriptor( + final DescriptorProto proto, + final FileDescriptor file, + final Descriptor parent, + final int index) + throws DescriptorValidationException { this.index = index; this.proto = proto; fullName = computeFullName(file, parent, proto.getName()); @@ -805,32 +789,27 @@ public final class Descriptors { oneofs = new OneofDescriptor[proto.getOneofDeclCount()]; for (int i = 0; i < proto.getOneofDeclCount(); i++) { - oneofs[i] = new OneofDescriptor( - proto.getOneofDecl(i), file, this, i); + oneofs[i] = new OneofDescriptor(proto.getOneofDecl(i), file, this, i); } nestedTypes = new Descriptor[proto.getNestedTypeCount()]; for (int i = 0; i < proto.getNestedTypeCount(); i++) { - nestedTypes[i] = new Descriptor( - proto.getNestedType(i), file, this, i); + nestedTypes[i] = new Descriptor(proto.getNestedType(i), file, this, i); } enumTypes = new EnumDescriptor[proto.getEnumTypeCount()]; for (int i = 0; i < proto.getEnumTypeCount(); i++) { - enumTypes[i] = new EnumDescriptor( - proto.getEnumType(i), file, this, i); + enumTypes[i] = new EnumDescriptor(proto.getEnumType(i), file, this, i); } fields = new FieldDescriptor[proto.getFieldCount()]; for (int i = 0; i < proto.getFieldCount(); i++) { - fields[i] = new FieldDescriptor( - proto.getField(i), file, this, i, false); + fields[i] = new FieldDescriptor(proto.getField(i), file, this, i, false); } extensions = new FieldDescriptor[proto.getExtensionCount()]; for (int i = 0; i < proto.getExtensionCount(); i++) { - extensions[i] = new FieldDescriptor( - proto.getExtension(i), file, this, i, true); + extensions[i] = new FieldDescriptor(proto.getExtension(i), file, this, i, true); } for (int i = 0; i < proto.getOneofDeclCount(); i++) { @@ -891,15 +870,16 @@ public final class Descriptors { // ================================================================= /** Describes a field of a message type. */ - public static final class FieldDescriptor - extends GenericDescriptor - implements Comparable, - FieldSet.FieldDescriptorLite { + public static final class FieldDescriptor extends GenericDescriptor + implements Comparable, FieldSet.FieldDescriptorLite { /** * Get the index of this descriptor within its parent. + * * @see Descriptors.Descriptor#getIndex() */ - public int getIndex() { return index; } + public int getIndex() { + return index; + } /** Convert the descriptor to its protocol message representation. */ @Override @@ -921,6 +901,7 @@ public final class Descriptors { /** * Get the field's fully-qualified name. + * * @see Descriptors.Descriptor#getFullName() */ @Override @@ -934,10 +915,12 @@ public final class Descriptors { } /** - * Get the field's java type. This is just for convenience. Every - * {@code FieldDescriptorProto.Type} maps to exactly one Java type. + * Get the field's java type. This is just for convenience. Every {@code + * FieldDescriptorProto.Type} maps to exactly one Java type. */ - public JavaType getJavaType() { return type.getJavaType(); } + public JavaType getJavaType() { + return type.getJavaType(); + } /** For internal use only. */ @Override @@ -952,7 +935,9 @@ public final class Descriptors { } /** Get the field's declared type. */ - public Type getType() { return type; } + public Type getType() { + return type; + } /** For internal use only. */ @Override @@ -976,15 +961,15 @@ public final class Descriptors { } public boolean isMapField() { - return getType() == Type.MESSAGE && isRepeated() + return getType() == Type.MESSAGE + && isRepeated() && getMessageType().getOptions().getMapEntry(); } // I'm pretty sure values() constructs a new array every time, since there // is nothing stopping the caller from mutating the array. Therefore we // make a static copy here. - private static final WireFormat.FieldType[] table = - WireFormat.FieldType.values(); + private static final WireFormat.FieldType[] table = WireFormat.FieldType.values(); /** Is this field declared required? */ public boolean isRequired() { @@ -1002,8 +987,9 @@ public final class Descriptors { return proto.getLabel() == FieldDescriptorProto.Label.LABEL_REPEATED; } - /** Does this field have the {@code [packed = true]} option or is this field - * packable in proto3 and not explicitly setted to unpacked? + /** + * Does this field have the {@code [packed = true]} option or is this field packable in proto3 + * and not explicitly setted to unpacked? */ @Override public boolean isPacked() { @@ -1023,42 +1009,50 @@ public final class Descriptors { } /** Returns true if the field had an explicitly-defined default value. */ - public boolean hasDefaultValue() { return proto.hasDefaultValue(); } + public boolean hasDefaultValue() { + return proto.hasDefaultValue(); + } /** - * Returns the field's default value. Valid for all types except for - * messages and groups. For all other types, the object returned is of - * the same class that would returned by Message.getField(this). + * Returns the field's default value. Valid for all types except for messages and groups. For + * all other types, the object returned is of the same class that would returned by + * Message.getField(this). */ public Object getDefaultValue() { if (getJavaType() == JavaType.MESSAGE) { throw new UnsupportedOperationException( - "FieldDescriptor.getDefaultValue() called on an embedded message " + - "field."); + "FieldDescriptor.getDefaultValue() called on an embedded message field."); } return defaultValue; } /** Get the {@code FieldOptions}, defined in {@code descriptor.proto}. */ - public FieldOptions getOptions() { return proto.getOptions(); } + public FieldOptions getOptions() { + return proto.getOptions(); + } /** Is this field an extension? */ - public boolean isExtension() { return proto.hasExtendee(); } + public boolean isExtension() { + return proto.hasExtendee(); + } /** - * Get the field's containing type. For extensions, this is the type being - * extended, not the location where the extension was defined. See - * {@link #getExtensionScope()}. + * Get the field's containing type. For extensions, this is the type being extended, not the + * location where the extension was defined. See {@link #getExtensionScope()}. */ - public Descriptor getContainingType() { return containingType; } + public Descriptor getContainingType() { + return containingType; + } /** Get the field's containing oneof. */ - public OneofDescriptor getContainingOneof() { return containingOneof; } + public OneofDescriptor getContainingOneof() { + return containingOneof; + } /** - * For extensions defined nested within message types, gets the outer - * type. Not valid for non-extension fields. For example, consider - * this {@code .proto} file: + * For extensions defined nested within message types, gets the outer type. Not valid for + * non-extension fields. For example, consider this {@code .proto} file: + * *
      *   message Foo {
      *     extensions 1000 to max;
@@ -1072,14 +1066,14 @@ public final class Descriptors {
      *     }
      *   }
      * 
- * Both {@code baz}'s and {@code qux}'s containing type is {@code Foo}. - * However, {@code baz}'s extension scope is {@code null} while - * {@code qux}'s extension scope is {@code Bar}. + * + * Both {@code baz}'s and {@code qux}'s containing type is {@code Foo}. However, {@code baz}'s + * extension scope is {@code null} while {@code qux}'s extension scope is {@code Bar}. */ public Descriptor getExtensionScope() { if (!isExtension()) { throw new UnsupportedOperationException( - "This field is not an extension."); + String.format("This field is not an extension. (%s)", fullName)); } return extensionScope; } @@ -1088,7 +1082,7 @@ public final class Descriptors { public Descriptor getMessageType() { if (getJavaType() != JavaType.MESSAGE) { throw new UnsupportedOperationException( - "This field is not of message type."); + String.format("This field is not of message type. (%s)", fullName)); } return messageType; } @@ -1098,27 +1092,25 @@ public final class Descriptors { public EnumDescriptor getEnumType() { if (getJavaType() != JavaType.ENUM) { throw new UnsupportedOperationException( - "This field is not of enum type."); + String.format("This field is not of enum type. (%s)", fullName)); } return enumType; } /** - * Compare with another {@code FieldDescriptor}. This orders fields in - * "canonical" order, which simply means ascending order by field number. - * {@code other} must be a field of the same type -- i.e. - * {@code getContainingType()} must return the same {@code Descriptor} for - * both fields. + * Compare with another {@code FieldDescriptor}. This orders fields in "canonical" order, which + * simply means ascending order by field number. {@code other} must be a field of the same type + * -- i.e. {@code getContainingType()} must return the same {@code Descriptor} for both fields. * - * @return negative, zero, or positive if {@code this} is less than, - * equal to, or greater than {@code other}, respectively. + * @return negative, zero, or positive if {@code this} is less than, equal to, or greater than + * {@code other}, respectively. */ @Override public int compareTo(final FieldDescriptor other) { if (other.containingType != containingType) { throw new IllegalArgumentException( - "FieldDescriptors can only be compared to other FieldDescriptors " + - "for fields of the same message type."); + "FieldDescriptors can only be compared to other FieldDescriptors " + + "for fields of the same message type."); } return getNumber() - other.getNumber(); } @@ -1145,24 +1137,24 @@ public final class Descriptors { private Object defaultValue; public enum Type { - DOUBLE (JavaType.DOUBLE ), - FLOAT (JavaType.FLOAT ), - INT64 (JavaType.LONG ), - UINT64 (JavaType.LONG ), - INT32 (JavaType.INT ), - FIXED64 (JavaType.LONG ), - FIXED32 (JavaType.INT ), - BOOL (JavaType.BOOLEAN ), - STRING (JavaType.STRING ), - GROUP (JavaType.MESSAGE ), - MESSAGE (JavaType.MESSAGE ), - BYTES (JavaType.BYTE_STRING), - UINT32 (JavaType.INT ), - ENUM (JavaType.ENUM ), - SFIXED32(JavaType.INT ), - SFIXED64(JavaType.LONG ), - SINT32 (JavaType.INT ), - SINT64 (JavaType.LONG ); + DOUBLE(JavaType.DOUBLE), + FLOAT(JavaType.FLOAT), + INT64(JavaType.LONG), + UINT64(JavaType.LONG), + INT32(JavaType.INT), + FIXED64(JavaType.LONG), + FIXED32(JavaType.INT), + BOOL(JavaType.BOOLEAN), + STRING(JavaType.STRING), + GROUP(JavaType.MESSAGE), + MESSAGE(JavaType.MESSAGE), + BYTES(JavaType.BYTE_STRING), + UINT32(JavaType.INT), + ENUM(JavaType.ENUM), + SFIXED32(JavaType.INT), + SFIXED64(JavaType.LONG), + SINT32(JavaType.INT), + SINT64(JavaType.LONG); Type(final JavaType javaType) { this.javaType = javaType; @@ -1173,7 +1165,10 @@ public final class Descriptors { public FieldDescriptorProto.Type toProto() { return FieldDescriptorProto.Type.forNumber(ordinal() + 1); } - public JavaType getJavaType() { return javaType; } + + public JavaType getJavaType() { + return javaType; + } public static Type valueOf(final FieldDescriptorProto.Type type) { return values()[type.getNumber() - 1]; @@ -1183,9 +1178,8 @@ public final class Descriptors { static { // Refuse to init if someone added a new declared type. if (Type.values().length != FieldDescriptorProto.Type.values().length) { - throw new RuntimeException("" - + "descriptor.proto has a new declared type but Descriptors.java " - + "wasn't updated."); + throw new RuntimeException( + "descriptor.proto has a new declared type but Descriptors.java wasn't updated."); } } @@ -1205,8 +1199,8 @@ public final class Descriptors { } /** - * The default default value for fields of this type, if it's a primitive - * type. This is meant for use inside this file only, hence is private. + * The default default value for fields of this type, if it's a primitive type. This is meant + * for use inside this file only, hence is private. */ private final Object defaultDefault; } @@ -1230,12 +1224,13 @@ public final class Descriptors { return result.toString(); } - private FieldDescriptor(final FieldDescriptorProto proto, - final FileDescriptor file, - final Descriptor parent, - final int index, - final boolean isExtension) - throws DescriptorValidationException { + private FieldDescriptor( + final FieldDescriptorProto proto, + final FileDescriptor file, + final Descriptor parent, + final int index, + final boolean isExtension) + throws DescriptorValidationException { this.index = index; this.proto = proto; fullName = computeFullName(file, parent, proto.getName()); @@ -1251,16 +1246,15 @@ public final class Descriptors { } if (getNumber() <= 0) { - throw new DescriptorValidationException(this, - "Field numbers must be positive integers."); + throw new DescriptorValidationException(this, "Field numbers must be positive integers."); } if (isExtension) { if (!proto.hasExtendee()) { - throw new DescriptorValidationException(this, - "FieldDescriptorProto.extendee not set for extension field."); + throw new DescriptorValidationException( + this, "FieldDescriptorProto.extendee not set for extension field."); } - containingType = null; // Will be filled in when cross-linking + containingType = null; // Will be filled in when cross-linking if (parent != null) { extensionScope = parent; } else { @@ -1268,23 +1262,23 @@ public final class Descriptors { } if (proto.hasOneofIndex()) { - throw new DescriptorValidationException(this, - "FieldDescriptorProto.oneof_index set for extension field."); + throw new DescriptorValidationException( + this, "FieldDescriptorProto.oneof_index set for extension field."); } containingOneof = null; } else { if (proto.hasExtendee()) { - throw new DescriptorValidationException(this, - "FieldDescriptorProto.extendee set for non-extension field."); + throw new DescriptorValidationException( + this, "FieldDescriptorProto.extendee set for non-extension field."); } containingType = parent; if (proto.hasOneofIndex()) { - if (proto.getOneofIndex() < 0 || - proto.getOneofIndex() >= parent.toProto().getOneofDeclCount()) { - throw new DescriptorValidationException(this, - "FieldDescriptorProto.oneof_index is out of range for type " - + parent.getName()); + if (proto.getOneofIndex() < 0 + || proto.getOneofIndex() >= parent.toProto().getOneofDeclCount()) { + throw new DescriptorValidationException( + this, + "FieldDescriptorProto.oneof_index is out of range for type " + parent.getName()); } containingOneof = parent.getOneofs().get(proto.getOneofIndex()); containingOneof.fieldCount++; @@ -1301,26 +1295,29 @@ public final class Descriptors { private void crossLink() throws DescriptorValidationException { if (proto.hasExtendee()) { final GenericDescriptor extendee = - file.pool.lookupSymbol(proto.getExtendee(), this, - DescriptorPool.SearchFilter.TYPES_ONLY); + file.pool.lookupSymbol( + proto.getExtendee(), this, DescriptorPool.SearchFilter.TYPES_ONLY); if (!(extendee instanceof Descriptor)) { - throw new DescriptorValidationException(this, - '\"' + proto.getExtendee() + "\" is not a message type."); + throw new DescriptorValidationException( + this, '\"' + proto.getExtendee() + "\" is not a message type."); } - containingType = (Descriptor)extendee; + containingType = (Descriptor) extendee; if (!getContainingType().isExtensionNumber(getNumber())) { - throw new DescriptorValidationException(this, - '\"' + getContainingType().getFullName() + - "\" does not declare " + getNumber() + - " as an extension number."); + throw new DescriptorValidationException( + this, + '\"' + + getContainingType().getFullName() + + "\" does not declare " + + getNumber() + + " as an extension number."); } } if (proto.hasTypeName()) { final GenericDescriptor typeDescriptor = - file.pool.lookupSymbol(proto.getTypeName(), this, - DescriptorPool.SearchFilter.TYPES_ONLY); + file.pool.lookupSymbol( + proto.getTypeName(), this, DescriptorPool.SearchFilter.TYPES_ONLY); if (!proto.hasType()) { // Choose field type based on symbol. @@ -1329,53 +1326,49 @@ public final class Descriptors { } else if (typeDescriptor instanceof EnumDescriptor) { type = Type.ENUM; } else { - throw new DescriptorValidationException(this, - '\"' + proto.getTypeName() + "\" is not a type."); + throw new DescriptorValidationException( + this, '\"' + proto.getTypeName() + "\" is not a type."); } } if (getJavaType() == JavaType.MESSAGE) { if (!(typeDescriptor instanceof Descriptor)) { - throw new DescriptorValidationException(this, - '\"' + proto.getTypeName() + "\" is not a message type."); + throw new DescriptorValidationException( + this, '\"' + proto.getTypeName() + "\" is not a message type."); } - messageType = (Descriptor)typeDescriptor; + messageType = (Descriptor) typeDescriptor; if (proto.hasDefaultValue()) { - throw new DescriptorValidationException(this, - "Messages can't have default values."); + throw new DescriptorValidationException(this, "Messages can't have default values."); } } else if (getJavaType() == JavaType.ENUM) { if (!(typeDescriptor instanceof EnumDescriptor)) { - throw new DescriptorValidationException(this, - '\"' + proto.getTypeName() + "\" is not an enum type."); + throw new DescriptorValidationException( + this, '\"' + proto.getTypeName() + "\" is not an enum type."); } - enumType = (EnumDescriptor)typeDescriptor; + enumType = (EnumDescriptor) typeDescriptor; } else { - throw new DescriptorValidationException(this, - "Field with primitive type has type_name."); + throw new DescriptorValidationException(this, "Field with primitive type has type_name."); } } else { - if (getJavaType() == JavaType.MESSAGE || - getJavaType() == JavaType.ENUM) { - throw new DescriptorValidationException(this, - "Field with message or enum type missing type_name."); + if (getJavaType() == JavaType.MESSAGE || getJavaType() == JavaType.ENUM) { + throw new DescriptorValidationException( + this, "Field with message or enum type missing type_name."); } } // Only repeated primitive fields may be packed. if (proto.getOptions().getPacked() && !isPackable()) { - throw new DescriptorValidationException(this, - "[packed = true] can only be specified for repeated primitive " + - "fields."); + throw new DescriptorValidationException( + this, "[packed = true] can only be specified for repeated primitive fields."); } // We don't attempt to parse the default value until here because for // enums we need the enum type's descriptor. if (proto.hasDefaultValue()) { if (isRepeated()) { - throw new DescriptorValidationException(this, - "Repeated fields cannot have default values."); + throw new DescriptorValidationException( + this, "Repeated fields cannot have default values."); } try { @@ -1428,30 +1421,26 @@ public final class Descriptors { break; case BYTES: try { - defaultValue = - TextFormat.unescapeBytes(proto.getDefaultValue()); + defaultValue = TextFormat.unescapeBytes(proto.getDefaultValue()); } catch (TextFormat.InvalidEscapeSequenceException e) { - throw new DescriptorValidationException(this, - "Couldn't parse default value: " + e.getMessage(), e); + throw new DescriptorValidationException( + this, "Couldn't parse default value: " + e.getMessage(), e); } break; case ENUM: defaultValue = enumType.findValueByName(proto.getDefaultValue()); if (defaultValue == null) { - throw new DescriptorValidationException(this, - "Unknown enum default value: \"" + - proto.getDefaultValue() + '\"'); + throw new DescriptorValidationException( + this, "Unknown enum default value: \"" + proto.getDefaultValue() + '\"'); } break; case MESSAGE: case GROUP: - throw new DescriptorValidationException(this, - "Message type had default value."); + throw new DescriptorValidationException(this, "Message type had default value."); } } catch (NumberFormatException e) { - throw new DescriptorValidationException(this, - "Could not parse default value: \"" + - proto.getDefaultValue() + '\"', e); + throw new DescriptorValidationException( + this, "Could not parse default value: \"" + proto.getDefaultValue() + '\"', e); } } else { // Determine the default default for this field. @@ -1478,16 +1467,15 @@ public final class Descriptors { file.pool.addFieldByNumber(this); } - if (containingType != null && - containingType.getOptions().getMessageSetWireFormat()) { + if (containingType != null && containingType.getOptions().getMessageSetWireFormat()) { if (isExtension()) { if (!isOptional() || getType() != Type.MESSAGE) { - throw new DescriptorValidationException(this, - "Extensions of MessageSets must be optional messages."); + throw new DescriptorValidationException( + this, "Extensions of MessageSets must be optional messages."); } } else { - throw new DescriptorValidationException(this, - "MessageSets cannot have fields, only extensions."); + throw new DescriptorValidationException( + this, "MessageSets cannot have fields, only extensions."); } } } @@ -1497,10 +1485,7 @@ public final class Descriptors { this.proto = proto; } - /** - * For internal use only. This is to satisfy the FieldDescriptorLite - * interface. - */ + /** For internal use only. This is to satisfy the FieldDescriptorLite interface. */ @Override public MessageLite.Builder internalMergeFrom(MessageLite.Builder to, MessageLite from) { // FieldDescriptors are only used with non-lite messages so we can just @@ -1517,9 +1502,12 @@ public final class Descriptors { implements Internal.EnumLiteMap { /** * Get the index of this descriptor within its parent. + * * @see Descriptors.Descriptor#getIndex() */ - public int getIndex() { return index; } + public int getIndex() { + return index; + } /** Convert the descriptor to its protocol message representation. */ @Override @@ -1535,6 +1523,7 @@ public final class Descriptors { /** * Get the type's fully-qualified name. + * * @see Descriptors.Descriptor#getFullName() */ @Override @@ -1549,10 +1538,14 @@ public final class Descriptors { } /** If this is a nested type, get the outer descriptor, otherwise null. */ - public Descriptor getContainingType() { return containingType; } + public Descriptor getContainingType() { + return containingType; + } /** Get the {@code EnumOptions}, defined in {@code descriptor.proto}. */ - public EnumOptions getOptions() { return proto.getOptions(); } + public EnumOptions getOptions() { + return proto.getOptions(); + } /** Get a list of defined values for this enum. */ public List getValues() { @@ -1561,34 +1554,34 @@ public final class Descriptors { /** * Find an enum value by name. + * * @param name The unqualified name of the value (e.g. "FOO"). * @return the value's descriptor, or {@code null} if not found. */ public EnumValueDescriptor findValueByName(final String name) { - final GenericDescriptor result = - file.pool.findSymbol(fullName + '.' + name); + final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name); if (result != null && result instanceof EnumValueDescriptor) { - return (EnumValueDescriptor)result; + return (EnumValueDescriptor) result; } else { return null; } } /** - * Find an enum value by number. If multiple enum values have the same - * number, this returns the first defined value with that number. + * Find an enum value by number. If multiple enum values have the same number, this returns the + * first defined value with that number. + * * @param number The value's number. * @return the value's descriptor, or {@code null} if not found. */ @Override public EnumValueDescriptor findValueByNumber(final int number) { - return file.pool.enumValuesByNumber.get( - new DescriptorPool.DescriptorIntPair(this, number)); + return file.pool.enumValuesByNumber.get(new DescriptorPool.DescriptorIntPair(this, number)); } /** - * Get the enum value for a number. If no enum value has this number, - * construct an EnumValueDescriptor for it. + * Get the enum value for a number. If no enum value has this number, construct an + * EnumValueDescriptor for it. */ public EnumValueDescriptor findValueByNumberCreatingIfUnknown(final int number) { EnumValueDescriptor result = findValueByNumber(number); @@ -1653,11 +1646,12 @@ public final class Descriptors { private final WeakHashMap> unknownValues = new WeakHashMap>(); - private EnumDescriptor(final EnumDescriptorProto proto, - final FileDescriptor file, - final Descriptor parent, - final int index) - throws DescriptorValidationException { + private EnumDescriptor( + final EnumDescriptorProto proto, + final FileDescriptor file, + final Descriptor parent, + final int index) + throws DescriptorValidationException { this.index = index; this.proto = proto; fullName = computeFullName(file, parent, proto.getName()); @@ -1667,14 +1661,12 @@ public final class Descriptors { if (proto.getValueCount() == 0) { // We cannot allow enums with no values because this would mean there // would be no valid default value for fields of this type. - throw new DescriptorValidationException(this, - "Enums must contain at least one value."); + throw new DescriptorValidationException(this, "Enums must contain at least one value."); } values = new EnumValueDescriptor[proto.getValueCount()]; for (int i = 0; i < proto.getValueCount(); i++) { - values[i] = new EnumValueDescriptor( - proto.getValue(i), file, this, i); + values[i] = new EnumValueDescriptor(proto.getValue(i), file, this, i); } file.pool.addSymbol(this); @@ -1693,18 +1685,20 @@ public final class Descriptors { // ================================================================= /** - * Describes one value within an enum type. Note that multiple defined - * values may have the same number. In generated Java code, all values - * with the same number after the first become aliases of the first. - * However, they still have independent EnumValueDescriptors. + * Describes one value within an enum type. Note that multiple defined values may have the same + * number. In generated Java code, all values with the same number after the first become aliases + * of the first. However, they still have independent EnumValueDescriptors. */ public static final class EnumValueDescriptor extends GenericDescriptor implements Internal.EnumLite { /** * Get the index of this descriptor within its parent. + * * @see Descriptors.Descriptor#getIndex() */ - public int getIndex() { return index; } + public int getIndex() { + return index; + } /** Convert the descriptor to its protocol message representation. */ @Override @@ -1725,10 +1719,13 @@ public final class Descriptors { } @Override - public String toString() { return proto.getName(); } + public String toString() { + return proto.getName(); + } /** * Get the value's fully-qualified name. + * * @see Descriptors.Descriptor#getFullName() */ @Override @@ -1743,12 +1740,14 @@ public final class Descriptors { } /** Get the value's enum type. */ - public EnumDescriptor getType() { return type; } + public EnumDescriptor getType() { + return type; + } - /** - * Get the {@code EnumValueOptions}, defined in {@code descriptor.proto}. - */ - public EnumValueOptions getOptions() { return proto.getOptions(); } + /** Get the {@code EnumValueOptions}, defined in {@code descriptor.proto}. */ + public EnumValueOptions getOptions() { + return proto.getOptions(); + } private final int index; private EnumValueDescriptorProto proto; @@ -1756,11 +1755,12 @@ public final class Descriptors { private final FileDescriptor file; private final EnumDescriptor type; - private EnumValueDescriptor(final EnumValueDescriptorProto proto, - final FileDescriptor file, - final EnumDescriptor parent, - final int index) - throws DescriptorValidationException { + private EnumValueDescriptor( + final EnumValueDescriptorProto proto, + final FileDescriptor file, + final EnumDescriptor parent, + final int index) + throws DescriptorValidationException { this.index = index; this.proto = proto; this.file = file; @@ -1775,12 +1775,10 @@ public final class Descriptors { private Integer number; // Create an unknown enum value. private EnumValueDescriptor( - final FileDescriptor file, - final EnumDescriptor parent, - final Integer number) { + final FileDescriptor file, final EnumDescriptor parent, final Integer number) { String name = "UNKNOWN_ENUM_VALUE_" + parent.getName() + "_" + number; - EnumValueDescriptorProto proto = EnumValueDescriptorProto - .newBuilder().setName(name).setNumber(number).build(); + EnumValueDescriptorProto proto = + EnumValueDescriptorProto.newBuilder().setName(name).setNumber(number).build(); this.index = -1; this.proto = proto; this.file = file; @@ -1802,10 +1800,11 @@ public final class Descriptors { /** Describes a service type. */ public static final class ServiceDescriptor extends GenericDescriptor { /** - * Get the index of this descriptor within its parent. - * * @see Descriptors.Descriptor#getIndex() + * Get the index of this descriptor within its parent. * @see Descriptors.Descriptor#getIndex() */ - public int getIndex() { return index; } + public int getIndex() { + return index; + } /** Convert the descriptor to its protocol message representation. */ @Override @@ -1821,6 +1820,7 @@ public final class Descriptors { /** * Get the type's fully-qualified name. + * * @see Descriptors.Descriptor#getFullName() */ @Override @@ -1835,7 +1835,9 @@ public final class Descriptors { } /** Get the {@code ServiceOptions}, defined in {@code descriptor.proto}. */ - public ServiceOptions getOptions() { return proto.getOptions(); } + public ServiceOptions getOptions() { + return proto.getOptions(); + } /** Get a list of methods for this service. */ public List getMethods() { @@ -1844,14 +1846,14 @@ public final class Descriptors { /** * Find a method by name. + * * @param name The unqualified name of the method (e.g. "Foo"). * @return the method's descriptor, or {@code null} if not found. */ public MethodDescriptor findMethodByName(final String name) { - final GenericDescriptor result = - file.pool.findSymbol(fullName + '.' + name); + final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name); if (result != null && result instanceof MethodDescriptor) { - return (MethodDescriptor)result; + return (MethodDescriptor) result; } else { return null; } @@ -1863,10 +1865,9 @@ public final class Descriptors { private final FileDescriptor file; private MethodDescriptor[] methods; - private ServiceDescriptor(final ServiceDescriptorProto proto, - final FileDescriptor file, - final int index) - throws DescriptorValidationException { + private ServiceDescriptor( + final ServiceDescriptorProto proto, final FileDescriptor file, final int index) + throws DescriptorValidationException { this.index = index; this.proto = proto; fullName = computeFullName(file, null, proto.getName()); @@ -1874,8 +1875,7 @@ public final class Descriptors { methods = new MethodDescriptor[proto.getMethodCount()]; for (int i = 0; i < proto.getMethodCount(); i++) { - methods[i] = new MethodDescriptor( - proto.getMethod(i), file, this, i); + methods[i] = new MethodDescriptor(proto.getMethod(i), file, this, i); } file.pool.addSymbol(this); @@ -1899,15 +1899,14 @@ public final class Descriptors { // ================================================================= - /** - * Describes one method within a service type. - */ + /** Describes one method within a service type. */ public static final class MethodDescriptor extends GenericDescriptor { /** - * Get the index of this descriptor within its parent. - * * @see Descriptors.Descriptor#getIndex() + * Get the index of this descriptor within its parent. * @see Descriptors.Descriptor#getIndex() */ - public int getIndex() { return index; } + public int getIndex() { + return index; + } /** Convert the descriptor to its protocol message representation. */ @Override @@ -1923,6 +1922,7 @@ public final class Descriptors { /** * Get the method's fully-qualified name. + * * @see Descriptors.Descriptor#getFullName() */ @Override @@ -1937,18 +1937,24 @@ public final class Descriptors { } /** Get the method's service type. */ - public ServiceDescriptor getService() { return service; } + public ServiceDescriptor getService() { + return service; + } /** Get the method's input type. */ - public Descriptor getInputType() { return inputType; } + public Descriptor getInputType() { + return inputType; + } /** Get the method's output type. */ - public Descriptor getOutputType() { return outputType; } + public Descriptor getOutputType() { + return outputType; + } - /** - * Get the {@code MethodOptions}, defined in {@code descriptor.proto}. - */ - public MethodOptions getOptions() { return proto.getOptions(); } + /** Get the {@code MethodOptions}, defined in {@code descriptor.proto}. */ + public MethodOptions getOptions() { + return proto.getOptions(); + } private final int index; private MethodDescriptorProto proto; @@ -1960,11 +1966,12 @@ public final class Descriptors { private Descriptor inputType; private Descriptor outputType; - private MethodDescriptor(final MethodDescriptorProto proto, - final FileDescriptor file, - final ServiceDescriptor parent, - final int index) - throws DescriptorValidationException { + private MethodDescriptor( + final MethodDescriptorProto proto, + final FileDescriptor file, + final ServiceDescriptor parent, + final int index) + throws DescriptorValidationException { this.index = index; this.proto = proto; this.file = file; @@ -1977,22 +1984,22 @@ public final class Descriptors { private void crossLink() throws DescriptorValidationException { final GenericDescriptor input = - file.pool.lookupSymbol(proto.getInputType(), this, - DescriptorPool.SearchFilter.TYPES_ONLY); + file.pool.lookupSymbol( + proto.getInputType(), this, DescriptorPool.SearchFilter.TYPES_ONLY); if (!(input instanceof Descriptor)) { - throw new DescriptorValidationException(this, - '\"' + proto.getInputType() + "\" is not a message type."); + throw new DescriptorValidationException( + this, '\"' + proto.getInputType() + "\" is not a message type."); } - inputType = (Descriptor)input; + inputType = (Descriptor) input; final GenericDescriptor output = - file.pool.lookupSymbol(proto.getOutputType(), this, - DescriptorPool.SearchFilter.TYPES_ONLY); + file.pool.lookupSymbol( + proto.getOutputType(), this, DescriptorPool.SearchFilter.TYPES_ONLY); if (!(output instanceof Descriptor)) { - throw new DescriptorValidationException(this, - '\"' + proto.getOutputType() + "\" is not a message type."); + throw new DescriptorValidationException( + this, '\"' + proto.getOutputType() + "\" is not a message type."); } - outputType = (Descriptor)output; + outputType = (Descriptor) output; } /** See {@link FileDescriptor#setProto}. */ @@ -2003,9 +2010,8 @@ public final class Descriptors { // ================================================================= - private static String computeFullName(final FileDescriptor file, - final Descriptor parent, - final String name) { + private static String computeFullName( + final FileDescriptor file, final Descriptor parent, final String name) { if (parent != null) { return parent.getFullName() + '.' + name; } else if (file.getPackage().length() > 0) { @@ -2018,47 +2024,47 @@ public final class Descriptors { // ================================================================= /** - * All descriptors implement this to make it easier to implement tools like - * {@code DescriptorPool}.

+ * All descriptors implement this to make it easier to implement tools like {@code + * DescriptorPool}. * - * This class is public so that the methods it exposes can be called from - * outside of this package. However, it should only be subclassed from - * nested classes of Descriptors. + *

This class is public so that the methods it exposes can be called from outside of this + * package. However, it should only be subclassed from nested classes of Descriptors. */ public abstract static class GenericDescriptor { public abstract Message toProto(); + public abstract String getName(); + public abstract String getFullName(); + public abstract FileDescriptor getFile(); } - /** - * Thrown when building descriptors fails because the source DescriptorProtos - * are not valid. - */ + /** Thrown when building descriptors fails because the source DescriptorProtos are not valid. */ public static class DescriptorValidationException extends Exception { private static final long serialVersionUID = 5750205775490483148L; /** Gets the full name of the descriptor where the error occurred. */ - public String getProblemSymbolName() { return name; } + public String getProblemSymbolName() { + return name; + } - /** - * Gets the protocol message representation of the invalid descriptor. - */ - public Message getProblemProto() { return proto; } + /** Gets the protocol message representation of the invalid descriptor. */ + public Message getProblemProto() { + return proto; + } - /** - * Gets a human-readable description of the error. - */ - public String getDescription() { return description; } + /** Gets a human-readable description of the error. */ + public String getDescription() { + return description; + } private final String name; private final Message proto; private final String description; private DescriptorValidationException( - final GenericDescriptor problemDescriptor, - final String description) { + final GenericDescriptor problemDescriptor, final String description) { super(problemDescriptor.getFullName() + ": " + description); // Note that problemDescriptor may be partially uninitialized, so we @@ -2078,8 +2084,7 @@ public final class Descriptors { } private DescriptorValidationException( - final FileDescriptor problemDescriptor, - final String description) { + final FileDescriptor problemDescriptor, final String description) { super(problemDescriptor.getName() + ": " + description); // Note that problemDescriptor may be partially uninitialized, so we @@ -2094,19 +2099,19 @@ public final class Descriptors { // ================================================================= /** - * A private helper class which contains lookup tables containing all the - * descriptors defined in a particular file. + * A private helper class which contains lookup tables containing all the descriptors defined in a + * particular file. */ private static final class DescriptorPool { - /** Defines what subclass of descriptors to search in the descriptor pool. - */ + /** Defines what subclass of descriptors to search in the descriptor pool. */ enum SearchFilter { - TYPES_ONLY, AGGREGATES_ONLY, ALL_SYMBOLS + TYPES_ONLY, + AGGREGATES_ONLY, + ALL_SYMBOLS } - DescriptorPool(final FileDescriptor[] dependencies, - boolean allowUnknownDependencies) { + DescriptorPool(final FileDescriptor[] dependencies, boolean allowUnknownDependencies) { this.dependencies = new HashSet(); this.allowUnknownDependencies = allowUnknownDependencies; @@ -2127,7 +2132,7 @@ public final class Descriptors { } } - /** Find and put public dependencies of the file into dependencies set.*/ + /** Find and put public dependencies of the file into dependencies set. */ private void importPublicDependencies(final FileDescriptor file) { for (FileDescriptor dependency : file.getPublicDependencies()) { if (dependencies.add(dependency)) { @@ -2140,27 +2145,27 @@ public final class Descriptors { private boolean allowUnknownDependencies; private final Map descriptorsByName = - new HashMap(); + new HashMap(); private final Map fieldsByNumber = - new HashMap(); - private final Map enumValuesByNumber - = new HashMap(); + new HashMap(); + private final Map enumValuesByNumber = + new HashMap(); /** Find a generic descriptor by fully-qualified name. */ GenericDescriptor findSymbol(final String fullName) { return findSymbol(fullName, SearchFilter.ALL_SYMBOLS); } - /** Find a descriptor by fully-qualified name and given option to only - * search valid field type descriptors. + /** + * Find a descriptor by fully-qualified name and given option to only search valid field type + * descriptors. */ - GenericDescriptor findSymbol(final String fullName, - final SearchFilter filter) { + GenericDescriptor findSymbol(final String fullName, final SearchFilter filter) { GenericDescriptor result = descriptorsByName.get(fullName); if (result != null) { - if ((filter==SearchFilter.ALL_SYMBOLS) || - ((filter==SearchFilter.TYPES_ONLY) && isType(result)) || - ((filter==SearchFilter.AGGREGATES_ONLY) && isAggregate(result))) { + if ((filter == SearchFilter.ALL_SYMBOLS) + || ((filter == SearchFilter.TYPES_ONLY) && isType(result)) + || ((filter == SearchFilter.AGGREGATES_ONLY) && isAggregate(result))) { return result; } } @@ -2168,9 +2173,9 @@ public final class Descriptors { for (final FileDescriptor dependency : dependencies) { result = dependency.pool.descriptorsByName.get(fullName); if (result != null) { - if ((filter==SearchFilter.ALL_SYMBOLS) || - ((filter==SearchFilter.TYPES_ONLY) && isType(result)) || - ((filter==SearchFilter.AGGREGATES_ONLY) && isAggregate(result))) { + if ((filter == SearchFilter.ALL_SYMBOLS) + || ((filter == SearchFilter.TYPES_ONLY) && isType(result)) + || ((filter == SearchFilter.AGGREGATES_ONLY) && isAggregate(result))) { return result; } } @@ -2181,28 +2186,27 @@ public final class Descriptors { /** Checks if the descriptor is a valid type for a message field. */ boolean isType(GenericDescriptor descriptor) { - return (descriptor instanceof Descriptor) || - (descriptor instanceof EnumDescriptor); + return (descriptor instanceof Descriptor) || (descriptor instanceof EnumDescriptor); } /** Checks if the descriptor is a valid namespace type. */ boolean isAggregate(GenericDescriptor descriptor) { - return (descriptor instanceof Descriptor) || - (descriptor instanceof EnumDescriptor) || - (descriptor instanceof PackageDescriptor) || - (descriptor instanceof ServiceDescriptor); + return (descriptor instanceof Descriptor) + || (descriptor instanceof EnumDescriptor) + || (descriptor instanceof PackageDescriptor) + || (descriptor instanceof ServiceDescriptor); } /** - * Look up a type descriptor by name, relative to some other descriptor. - * The name may be fully-qualified (with a leading '.'), - * partially-qualified, or unqualified. C++-like name lookup semantics - * are used to search for the matching descriptor. + * Look up a type descriptor by name, relative to some other descriptor. The name may be + * fully-qualified (with a leading '.'), partially-qualified, or unqualified. C++-like name + * lookup semantics are used to search for the matching descriptor. */ - GenericDescriptor lookupSymbol(final String name, - final GenericDescriptor relativeTo, - final DescriptorPool.SearchFilter filter) - throws DescriptorValidationException { + GenericDescriptor lookupSymbol( + final String name, + final GenericDescriptor relativeTo, + final DescriptorPool.SearchFilter filter) + throws DescriptorValidationException { // TODO(kenton): This could be optimized in a number of ways. GenericDescriptor result; @@ -2235,8 +2239,7 @@ public final class Descriptors { // We will search each parent scope of "relativeTo" looking for the // symbol. - final StringBuilder scopeToTry = - new StringBuilder(relativeTo.getFullName()); + final StringBuilder scopeToTry = new StringBuilder(relativeTo.getFullName()); while (true) { // Chop off the last component of the scope. @@ -2250,8 +2253,7 @@ public final class Descriptors { // Append firstPart and try to find scopeToTry.append(firstPart); - result = findSymbol(scopeToTry.toString(), - DescriptorPool.SearchFilter.AGGREGATES_ONLY); + result = findSymbol(scopeToTry.toString(), DescriptorPool.SearchFilter.AGGREGATES_ONLY); if (result != null) { if (firstPartLength != -1) { @@ -2274,22 +2276,23 @@ public final class Descriptors { if (result == null) { if (allowUnknownDependencies && filter == SearchFilter.TYPES_ONLY) { - logger.warning("The descriptor for message type \"" + name + - "\" can not be found and a placeholder is created for it"); + logger.warning( + "The descriptor for message type \"" + + name + + "\" can not be found and a placeholder is created for it"); // We create a dummy message descriptor here regardless of the // expected type. If the type should be message, this dummy // descriptor will work well and if the type should be enum, a // DescriptorValidationException will be thrown latter. In either // case, the code works as expected: we allow unknown message types - // but not unknwon enum types. + // but not unknown enum types. result = new Descriptor(fullname); // Add the placeholder file as a dependency so we can find the // placeholder symbol when resolving other references. this.dependencies.add(result.getFile()); return result; } else { - throw new DescriptorValidationException(relativeTo, - '\"' + name + "\" is not defined."); + throw new DescriptorValidationException(relativeTo, '\"' + name + "\" is not defined."); } } else { return result; @@ -2297,11 +2300,10 @@ public final class Descriptors { } /** - * Adds a symbol to the symbol table. If a symbol with the same name - * already exists, throws an error. + * Adds a symbol to the symbol table. If a symbol with the same name already exists, throws an + * error. */ - void addSymbol(final GenericDescriptor descriptor) - throws DescriptorValidationException { + void addSymbol(final GenericDescriptor descriptor) throws DescriptorValidationException { validateSymbolName(descriptor); final String fullName = descriptor.getFullName(); @@ -2313,47 +2315,56 @@ public final class Descriptors { if (descriptor.getFile() == old.getFile()) { if (dotpos == -1) { - throw new DescriptorValidationException(descriptor, - '\"' + fullName + "\" is already defined."); + throw new DescriptorValidationException( + descriptor, '\"' + fullName + "\" is already defined."); } else { - throw new DescriptorValidationException(descriptor, - '\"' + fullName.substring(dotpos + 1) + - "\" is already defined in \"" + - fullName.substring(0, dotpos) + "\"."); + throw new DescriptorValidationException( + descriptor, + '\"' + + fullName.substring(dotpos + 1) + + "\" is already defined in \"" + + fullName.substring(0, dotpos) + + "\"."); } } else { - throw new DescriptorValidationException(descriptor, - '\"' + fullName + "\" is already defined in file \"" + - old.getFile().getName() + "\"."); + throw new DescriptorValidationException( + descriptor, + '\"' + + fullName + + "\" is already defined in file \"" + + old.getFile().getName() + + "\"."); } } } /** - * Represents a package in the symbol table. We use PackageDescriptors - * just as placeholders so that someone cannot define, say, a message type - * that has the same name as an existing package. + * Represents a package in the symbol table. We use PackageDescriptors just as placeholders so + * that someone cannot define, say, a message type that has the same name as an existing + * package. */ private static final class PackageDescriptor extends GenericDescriptor { @Override public Message toProto() { return file.toProto(); } + @Override public String getName() { return name; } + @Override public String getFullName() { return fullName; } + @Override public FileDescriptor getFile() { return file; } - PackageDescriptor(final String name, final String fullName, - final FileDescriptor file) { + PackageDescriptor(final String name, final String fullName, final FileDescriptor file) { this.file = file; this.fullName = fullName; this.name = name; @@ -2365,13 +2376,12 @@ public final class Descriptors { } /** - * Adds a package to the symbol tables. If a package by the same name - * already exists, that is fine, but if some other kind of symbol exists - * under the same name, an exception is thrown. If the package has - * multiple components, this also adds the parent package(s). + * Adds a package to the symbol tables. If a package by the same name already exists, that is + * fine, but if some other kind of symbol exists under the same name, an exception is thrown. If + * the package has multiple components, this also adds the parent package(s). */ void addPackage(final String fullName, final FileDescriptor file) - throws DescriptorValidationException { + throws DescriptorValidationException { final int dotpos = fullName.lastIndexOf('.'); final String name; if (dotpos == -1) { @@ -2382,14 +2392,18 @@ public final class Descriptors { } final GenericDescriptor old = - descriptorsByName.put(fullName, - new PackageDescriptor(name, fullName, file)); + descriptorsByName.put(fullName, new PackageDescriptor(name, fullName, file)); if (old != null) { descriptorsByName.put(fullName, old); if (!(old instanceof PackageDescriptor)) { - throw new DescriptorValidationException(file, - '\"' + name + "\" is already defined (as something other than a " - + "package) in file \"" + old.getFile().getName() + "\"."); + throw new DescriptorValidationException( + file, + '\"' + + name + + "\" is already defined (as something other than a " + + "package) in file \"" + + old.getFile().getName() + + "\"."); } } } @@ -2408,43 +2422,46 @@ public final class Descriptors { public int hashCode() { return descriptor.hashCode() * ((1 << 16) - 1) + number; } + @Override public boolean equals(final Object obj) { if (!(obj instanceof DescriptorIntPair)) { return false; } - final DescriptorIntPair other = (DescriptorIntPair)obj; + final DescriptorIntPair other = (DescriptorIntPair) obj; return descriptor == other.descriptor && number == other.number; } } /** - * Adds a field to the fieldsByNumber table. Throws an exception if a - * field with the same containing type and number already exists. + * Adds a field to the fieldsByNumber table. Throws an exception if a field with the same + * containing type and number already exists. */ - void addFieldByNumber(final FieldDescriptor field) - throws DescriptorValidationException { + void addFieldByNumber(final FieldDescriptor field) throws DescriptorValidationException { final DescriptorIntPair key = - new DescriptorIntPair(field.getContainingType(), field.getNumber()); + new DescriptorIntPair(field.getContainingType(), field.getNumber()); final FieldDescriptor old = fieldsByNumber.put(key, field); if (old != null) { fieldsByNumber.put(key, old); - throw new DescriptorValidationException(field, - "Field number " + field.getNumber() + - " has already been used in \"" + - field.getContainingType().getFullName() + - "\" by field \"" + old.getName() + "\"."); + throw new DescriptorValidationException( + field, + "Field number " + + field.getNumber() + + " has already been used in \"" + + field.getContainingType().getFullName() + + "\" by field \"" + + old.getName() + + "\"."); } } /** - * Adds an enum value to the enumValuesByNumber table. If an enum value - * with the same type and number already exists, does nothing. (This is - * allowed; the first value define with the number takes precedence.) + * Adds an enum value to the enumValuesByNumber table. If an enum value with the same type and + * number already exists, does nothing. (This is allowed; the first value define with the number + * takes precedence.) */ void addEnumValueByNumber(final EnumValueDescriptor value) { - final DescriptorIntPair key = - new DescriptorIntPair(value.getType(), value.getNumber()); + final DescriptorIntPair key = new DescriptorIntPair(value.getType(), value.getNumber()); final EnumValueDescriptor old = enumValuesByNumber.put(key, value); if (old != null) { enumValuesByNumber.put(key, old); @@ -2454,11 +2471,11 @@ public final class Descriptors { } /** - * Verifies that the descriptor's name is valid (i.e. it contains only - * letters, digits, and underscores, and does not start with a digit). + * Verifies that the descriptor's name is valid (i.e. it contains only letters, digits, and + * underscores, and does not start with a digit). */ static void validateSymbolName(final GenericDescriptor descriptor) - throws DescriptorValidationException { + throws DescriptorValidationException { final String name = descriptor.getName(); if (name.length() == 0) { throw new DescriptorValidationException(descriptor, "Missing name."); @@ -2473,16 +2490,15 @@ public final class Descriptors { } // First character must be letter or _. Subsequent characters may // be letters, numbers, or digits. - if (Character.isLetter(c) || c == '_' || - (Character.isDigit(c) && i > 0)) { + if (Character.isLetter(c) || c == '_' || (Character.isDigit(c) && i > 0)) { // Valid } else { valid = false; } } if (!valid) { - throw new DescriptorValidationException(descriptor, - '\"' + name + "\" is not a valid identifier."); + throw new DescriptorValidationException( + descriptor, '\"' + name + "\" is not a valid identifier."); } } } @@ -2491,17 +2507,29 @@ public final class Descriptors { /** Describes an oneof of a message type. */ public static final class OneofDescriptor { /** Get the index of this descriptor within its parent. */ - public int getIndex() { return index; } + public int getIndex() { + return index; + } - public String getName() { return proto.getName(); } + public String getName() { + return proto.getName(); + } - public FileDescriptor getFile() { return file; } + public FileDescriptor getFile() { + return file; + } - public String getFullName() { return fullName; } + public String getFullName() { + return fullName; + } - public Descriptor getContainingType() { return containingType; } + public Descriptor getContainingType() { + return containingType; + } - public int getFieldCount() { return fieldCount; } + public int getFieldCount() { + return fieldCount; + } public OneofOptions getOptions() { return proto.getOptions(); @@ -2520,11 +2548,12 @@ public final class Descriptors { this.proto = proto; } - private OneofDescriptor(final OneofDescriptorProto proto, - final FileDescriptor file, - final Descriptor parent, - final int index) - throws DescriptorValidationException { + private OneofDescriptor( + final OneofDescriptorProto proto, + final FileDescriptor file, + final Descriptor parent, + final int index) + throws DescriptorValidationException { this.proto = proto; fullName = computeFullName(file, parent, proto.getName()); this.file = file; diff --git a/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java b/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java index 7ae9434906..fefa636e9b 100644 --- a/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java +++ b/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java @@ -30,9 +30,7 @@ package com.google.protobuf; -/** - * Parsers to discard unknown fields during parsing. - */ +/** Parsers to discard unknown fields during parsing. */ public final class DiscardUnknownFieldsParser { /** @@ -40,11 +38,12 @@ public final class DiscardUnknownFieldsParser { * parsing. * *

Usage example: + * *

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

Like all other implementations of {@code Parser}, this parser is stateless and thread-safe. diff --git a/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java b/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java index 8d987b2e33..e7b8fa8335 100644 --- a/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java +++ b/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java @@ -42,11 +42,11 @@ import java.util.RandomAccess; * * @author dweis@google.com (Daniel Weis) */ -final class DoubleArrayList - extends AbstractProtobufList +final class DoubleArrayList extends AbstractProtobufList implements DoubleList, RandomAccess, PrimitiveNonBoxingCollection { private static final DoubleArrayList EMPTY_LIST = new DoubleArrayList(); + static { EMPTY_LIST.makeImmutable(); } @@ -55,9 +55,7 @@ final class DoubleArrayList return EMPTY_LIST; } - /** - * The backing store for the list. - */ + /** The backing store for the list. */ private double[] array; /** @@ -66,16 +64,13 @@ final class DoubleArrayList */ private int size; - /** - * Constructs a new mutable {@code DoubleArrayList} with default capacity. - */ + /** Constructs a new mutable {@code DoubleArrayList} with default capacity. */ DoubleArrayList() { this(new double[DEFAULT_CAPACITY], 0); } /** - * Constructs a new mutable {@code DoubleArrayList} - * containing the same elements as {@code other}. + * Constructs a new mutable {@code DoubleArrayList} containing the same elements as {@code other}. */ private DoubleArrayList(double[] other, int size) { array = other; @@ -170,17 +165,13 @@ final class DoubleArrayList addDouble(index, element); } - /** - * Like {@link #add(Double)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #add(Double)} but more efficient in that it doesn't box the element. */ @Override public void addDouble(double element) { addDouble(size, element); } - /** - * Like {@link #add(int, Double)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #add(int, Double)} but more efficient in that it doesn't box the element. */ private void addDouble(int index, double element) { ensureIsMutable(); if (index < 0 || index > size) { diff --git a/java/core/src/main/java/com/google/protobuf/DynamicMessage.java b/java/core/src/main/java/com/google/protobuf/DynamicMessage.java index 2c346e031c..63dda6b9f2 100644 --- a/java/core/src/main/java/com/google/protobuf/DynamicMessage.java +++ b/java/core/src/main/java/com/google/protobuf/DynamicMessage.java @@ -43,8 +43,8 @@ import java.util.List; import java.util.Map; /** - * An implementation of {@link Message} that can represent arbitrary types, - * given a {@link Descriptors.Descriptor}. + * An implementation of {@link Message} that can represent arbitrary types, given a {@link + * Descriptors.Descriptor}. * * @author kenton@google.com Kenton Varda */ @@ -56,88 +56,83 @@ public final class DynamicMessage extends AbstractMessage { private int memoizedSize = -1; /** - * Construct a {@code DynamicMessage} using the given {@code FieldSet}. - * oneofCases stores the FieldDescriptor for each oneof to indicate - * which field is set. Caller should make sure the array is immutable. + * Construct a {@code DynamicMessage} using the given {@code FieldSet}. oneofCases stores the + * FieldDescriptor for each oneof to indicate which field is set. Caller should make sure the + * array is immutable. * - * This constructor is package private and will be used in - * {@code DynamicMutableMessage} to convert a mutable message to an immutable - * message. + *

This constructor is package private and will be used in {@code DynamicMutableMessage} to + * convert a mutable message to an immutable message. */ - DynamicMessage(Descriptor type, FieldSet fields, - FieldDescriptor[] oneofCases, - UnknownFieldSet unknownFields) { + DynamicMessage( + Descriptor type, + FieldSet fields, + FieldDescriptor[] oneofCases, + UnknownFieldSet unknownFields) { this.type = type; this.fields = fields; this.oneofCases = oneofCases; this.unknownFields = unknownFields; } - /** - * Get a {@code DynamicMessage} representing the default instance of the - * given type. - */ + /** Get a {@code DynamicMessage} representing the default instance of the given type. */ public static DynamicMessage getDefaultInstance(Descriptor type) { int oneofDeclCount = type.toProto().getOneofDeclCount(); FieldDescriptor[] oneofCases = new FieldDescriptor[oneofDeclCount]; - return new DynamicMessage(type, FieldSet.emptySet(), - oneofCases, - UnknownFieldSet.getDefaultInstance()); + return new DynamicMessage( + type, + FieldSet.emptySet(), + oneofCases, + UnknownFieldSet.getDefaultInstance()); } /** Parse a message of the given type from the given input stream. */ - public static DynamicMessage parseFrom(Descriptor type, - CodedInputStream input) - throws IOException { + public static DynamicMessage parseFrom(Descriptor type, CodedInputStream input) + throws IOException { return newBuilder(type).mergeFrom(input).buildParsed(); } /** Parse a message of the given type from the given input stream. */ public static DynamicMessage parseFrom( - Descriptor type, - CodedInputStream input, - ExtensionRegistry extensionRegistry) + Descriptor type, CodedInputStream input, ExtensionRegistry extensionRegistry) throws IOException { return newBuilder(type).mergeFrom(input, extensionRegistry).buildParsed(); } /** Parse {@code data} as a message of the given type and return it. */ public static DynamicMessage parseFrom(Descriptor type, ByteString data) - throws InvalidProtocolBufferException { + throws InvalidProtocolBufferException { return newBuilder(type).mergeFrom(data).buildParsed(); } /** Parse {@code data} as a message of the given type and return it. */ - public static DynamicMessage parseFrom(Descriptor type, ByteString data, - ExtensionRegistry extensionRegistry) - throws InvalidProtocolBufferException { + public static DynamicMessage parseFrom( + Descriptor type, ByteString data, ExtensionRegistry extensionRegistry) + throws InvalidProtocolBufferException { return newBuilder(type).mergeFrom(data, extensionRegistry).buildParsed(); } /** Parse {@code data} as a message of the given type and return it. */ public static DynamicMessage parseFrom(Descriptor type, byte[] data) - throws InvalidProtocolBufferException { + throws InvalidProtocolBufferException { return newBuilder(type).mergeFrom(data).buildParsed(); } /** Parse {@code data} as a message of the given type and return it. */ - public static DynamicMessage parseFrom(Descriptor type, byte[] data, - ExtensionRegistry extensionRegistry) - throws InvalidProtocolBufferException { + public static DynamicMessage parseFrom( + Descriptor type, byte[] data, ExtensionRegistry extensionRegistry) + throws InvalidProtocolBufferException { return newBuilder(type).mergeFrom(data, extensionRegistry).buildParsed(); } /** Parse a message of the given type from {@code input} and return it. */ - public static DynamicMessage parseFrom(Descriptor type, InputStream input) - throws IOException { + public static DynamicMessage parseFrom(Descriptor type, InputStream input) throws IOException { return newBuilder(type).mergeFrom(input).buildParsed(); } /** Parse a message of the given type from {@code input} and return it. */ - public static DynamicMessage parseFrom(Descriptor type, InputStream input, - ExtensionRegistry extensionRegistry) - throws IOException { + public static DynamicMessage parseFrom( + Descriptor type, InputStream input, ExtensionRegistry extensionRegistry) throws IOException { return newBuilder(type).mergeFrom(input, extensionRegistry).buildParsed(); } @@ -147,8 +142,8 @@ public final class DynamicMessage extends AbstractMessage { } /** - * Construct a {@link Message.Builder} for a message of the same type as - * {@code prototype}, and initialize it with {@code prototype}'s contents. + * Construct a {@link Message.Builder} for a message of the same type as {@code prototype}, and + * initialize it with {@code prototype}'s contents. */ public static Builder newBuilder(Message prototype) { return new Builder(prototype.getDescriptorForType()).mergeFrom(prototype); @@ -227,8 +222,7 @@ public final class DynamicMessage extends AbstractMessage { return unknownFields; } - static boolean isInitialized(Descriptor type, - FieldSet fields) { + static boolean isInitialized(Descriptor type, FieldSet fields) { // Check that all required fields are present. for (final FieldDescriptor field : type.getFields()) { if (field.isRequired()) { @@ -298,8 +292,7 @@ public final class DynamicMessage extends AbstractMessage { } catch (InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (IOException e) { - throw new InvalidProtocolBufferException(e) - .setUnfinishedMessage(builder.buildPartial()); + throw new InvalidProtocolBufferException(e).setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } @@ -309,24 +302,20 @@ public final class DynamicMessage extends AbstractMessage { /** Verifies that the field is a field of this message. */ private void verifyContainingType(FieldDescriptor field) { if (field.getContainingType() != type) { - throw new IllegalArgumentException( - "FieldDescriptor does not match message type."); + throw new IllegalArgumentException("FieldDescriptor does not match message type."); } } /** Verifies that the oneof is an oneof of this message. */ private void verifyOneofContainingType(OneofDescriptor oneof) { if (oneof.getContainingType() != type) { - throw new IllegalArgumentException( - "OneofDescriptor does not match message type."); + throw new IllegalArgumentException("OneofDescriptor does not match message type."); } } // ================================================================= - /** - * Builder for {@link DynamicMessage}s. - */ + /** Builder for {@link DynamicMessage}s. */ public static final class Builder extends AbstractMessage.Builder { private final Descriptor type; private FieldSet fields; @@ -380,7 +369,7 @@ public final class DynamicMessage extends AbstractMessage { DynamicMessage otherDynamicMessage = (DynamicMessage) other; if (otherDynamicMessage.type != type) { throw new IllegalArgumentException( - "mergeFrom(Message) can only merge messages of the same type."); + "mergeFrom(Message) can only merge messages of the same type."); } ensureIsMutable(); fields.mergeFrom(otherDynamicMessage.fields); @@ -406,23 +395,28 @@ public final class DynamicMessage extends AbstractMessage { public DynamicMessage build() { if (!isInitialized()) { throw newUninitializedMessageException( - new DynamicMessage(type, fields, - java.util.Arrays.copyOf(oneofCases, oneofCases.length), unknownFields)); + new DynamicMessage( + type, + fields, + java.util.Arrays.copyOf(oneofCases, oneofCases.length), + unknownFields)); } return buildPartial(); } /** - * Helper for DynamicMessage.parseFrom() methods to call. Throws - * {@link InvalidProtocolBufferException} instead of - * {@link UninitializedMessageException}. + * Helper for DynamicMessage.parseFrom() methods to call. Throws {@link + * InvalidProtocolBufferException} instead of {@link UninitializedMessageException}. */ private DynamicMessage buildParsed() throws InvalidProtocolBufferException { if (!isInitialized()) { throw newUninitializedMessageException( - new DynamicMessage(type, fields, - java.util.Arrays.copyOf(oneofCases, oneofCases.length), unknownFields)) - .asInvalidProtocolBufferException(); + new DynamicMessage( + type, + fields, + java.util.Arrays.copyOf(oneofCases, oneofCases.length), + unknownFields)) + .asInvalidProtocolBufferException(); } return buildPartial(); } @@ -431,8 +425,8 @@ public final class DynamicMessage extends AbstractMessage { public DynamicMessage buildPartial() { fields.makeImmutable(); DynamicMessage result = - new DynamicMessage(type, fields, - java.util.Arrays.copyOf(oneofCases, oneofCases.length), unknownFields); + new DynamicMessage( + type, fields, java.util.Arrays.copyOf(oneofCases, oneofCases.length), unknownFields); return result; } @@ -441,7 +435,7 @@ public final class DynamicMessage extends AbstractMessage { Builder result = new Builder(type); result.fields.mergeFrom(fields); result.mergeUnknownFields(unknownFields); - System.arraycopy(oneofCases, 0, result.oneofCases, 0 , oneofCases.length); + System.arraycopy(oneofCases, 0, result.oneofCases, 0, oneofCases.length); return result; } @@ -471,7 +465,7 @@ public final class DynamicMessage extends AbstractMessage { if (field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) { throw new IllegalArgumentException( - "newBuilderForField is only valid for fields with message type."); + "newBuilderForField is only valid for fields with message type."); } return new Builder(field.getMessageType()); @@ -615,35 +609,30 @@ public final class DynamicMessage extends AbstractMessage { @Override public Builder mergeUnknownFields(UnknownFieldSet unknownFields) { this.unknownFields = - UnknownFieldSet.newBuilder(this.unknownFields) - .mergeFrom(unknownFields) - .build(); + UnknownFieldSet.newBuilder(this.unknownFields).mergeFrom(unknownFields).build(); return this; } /** Verifies that the field is a field of this message. */ private void verifyContainingType(FieldDescriptor field) { if (field.getContainingType() != type) { - throw new IllegalArgumentException( - "FieldDescriptor does not match message type."); + throw new IllegalArgumentException("FieldDescriptor does not match message type."); } } /** Verifies that the oneof is an oneof of this message. */ private void verifyOneofContainingType(OneofDescriptor oneof) { if (oneof.getContainingType() != type) { - throw new IllegalArgumentException( - "OneofDescriptor does not match message type."); + throw new IllegalArgumentException("OneofDescriptor does not match message type."); } } /** Verifies that the value is EnumValueDescriptor and matches Enum Type. */ - private void ensureSingularEnumValueDescriptor( - FieldDescriptor field, Object value) { + private void ensureSingularEnumValueDescriptor(FieldDescriptor field, Object value) { checkNotNull(value); if (!(value instanceof EnumValueDescriptor)) { throw new IllegalArgumentException( - "DynamicMessage should use EnumValueDescriptor to set Enum Value."); + "DynamicMessage should use EnumValueDescriptor to set Enum Value."); } // TODO(xiaofeng): Re-enable this check after Orgstore is fixed to not // set incorrect EnumValueDescriptors. @@ -657,14 +646,13 @@ public final class DynamicMessage extends AbstractMessage { } /** Verifies the value for an enum field. */ - private void ensureEnumValueDescriptor( - FieldDescriptor field, Object value) { + private void ensureEnumValueDescriptor(FieldDescriptor field, Object value) { if (field.isRepeated()) { for (Object item : (List) value) { ensureSingularEnumValueDescriptor(field, item); } } else { - ensureSingularEnumValueDescriptor(field, value); + ensureSingularEnumValueDescriptor(field, value); } } @@ -678,14 +666,14 @@ public final class DynamicMessage extends AbstractMessage { public com.google.protobuf.Message.Builder getFieldBuilder(FieldDescriptor field) { // TODO(xiangl): need implementation for dynamic message throw new UnsupportedOperationException( - "getFieldBuilder() called on a dynamic message type."); + "getFieldBuilder() called on a dynamic message type."); } @Override - public com.google.protobuf.Message.Builder getRepeatedFieldBuilder(FieldDescriptor field, - int index) { + public com.google.protobuf.Message.Builder getRepeatedFieldBuilder( + FieldDescriptor field, int index) { throw new UnsupportedOperationException( - "getRepeatedFieldBuilder() called on a dynamic message type."); + "getRepeatedFieldBuilder() called on a dynamic message type."); } } } diff --git a/java/core/src/main/java/com/google/protobuf/ExperimentalApi.java b/java/core/src/main/java/com/google/protobuf/ExperimentalApi.java index 3cd4c88492..d55b278c3f 100644 --- a/java/core/src/main/java/com/google/protobuf/ExperimentalApi.java +++ b/java/core/src/main/java/com/google/protobuf/ExperimentalApi.java @@ -41,26 +41,25 @@ import java.lang.annotation.Target; * backward-compatibility. * *

Usage guidelines: + * *

    - *
  1. This annotation is used only on public API. Internal interfaces should not use it.
  2. - *
  3. This annotation should only be added to new APIs. Adding it to an existing API is - * considered API-breaking.
  4. - *
  5. Removing this annotation from an API gives it stable status.
  6. + *
  7. This annotation is used only on public API. Internal interfaces should not use it. + *
  8. This annotation should only be added to new APIs. Adding it to an existing API is + * considered API-breaking. + *
  9. Removing this annotation from an API gives it stable status. *
*/ @Retention(RetentionPolicy.SOURCE) @Target({ - ElementType.ANNOTATION_TYPE, - ElementType.CONSTRUCTOR, - ElementType.FIELD, - ElementType.METHOD, - ElementType.PACKAGE, - ElementType.TYPE}) + ElementType.ANNOTATION_TYPE, + ElementType.CONSTRUCTOR, + ElementType.FIELD, + ElementType.METHOD, + ElementType.PACKAGE, + ElementType.TYPE +}) @Documented public @interface ExperimentalApi { - /** - * Context information such as links to discussion thread, tracking issue etc. - */ + /** Context information such as links to discussion thread, tracking issue etc. */ String value() default ""; } - diff --git a/java/core/src/main/java/com/google/protobuf/Extension.java b/java/core/src/main/java/com/google/protobuf/Extension.java index 5df12e6422..e5da634f1c 100644 --- a/java/core/src/main/java/com/google/protobuf/Extension.java +++ b/java/core/src/main/java/com/google/protobuf/Extension.java @@ -49,9 +49,7 @@ public abstract class Extension // All the methods below are extension implementation details. - /** - * The API type that the extension is used for. - */ + /** The API type that the extension is used for. */ protected enum ExtensionType { IMMUTABLE, MUTABLE, @@ -60,24 +58,25 @@ public abstract class Extension protected abstract ExtensionType getExtensionType(); - /** - * Type of a message extension. - */ + /** Type of a message extension. */ public enum MessageType { PROTO1, PROTO2, } /** - * If the extension is a message extension (i.e., getLiteType() == MESSAGE), - * returns the type of the message, otherwise undefined. + * If the extension is a message extension (i.e., getLiteType() == MESSAGE), returns the type of + * the message, otherwise undefined. */ public MessageType getMessageType() { return MessageType.PROTO2; } protected abstract Object fromReflectionType(Object value); + protected abstract Object singularFromReflectionType(Object value); + protected abstract Object toReflectionType(Object value); + protected abstract Object singularToReflectionType(Object value); } diff --git a/java/core/src/main/java/com/google/protobuf/ExtensionLite.java b/java/core/src/main/java/com/google/protobuf/ExtensionLite.java index f8f5bd2c4f..0fb5f49e98 100644 --- a/java/core/src/main/java/com/google/protobuf/ExtensionLite.java +++ b/java/core/src/main/java/com/google/protobuf/ExtensionLite.java @@ -32,9 +32,9 @@ package com.google.protobuf; /** * Lite interface that generated extensions implement. - *

- * Methods are for use by generated code only. You can hold a reference to - * extensions using this type name. + * + *

Methods are for use by generated code only. You can hold a reference to extensions using this + * type name. */ public abstract class ExtensionLite { @@ -50,12 +50,9 @@ public abstract class ExtensionLite { /** Returns the default value of the extension field. */ public abstract Type getDefaultValue(); - /** - * Returns the default instance of the extension field, if it's a message - * extension. - */ + /** Returns the default instance of the extension field, if it's a message extension. */ public abstract MessageLite getMessageDefaultInstance(); - + /** Returns whether or not this extension is a Lite Extension. */ boolean isLite() { return true; diff --git a/java/core/src/main/java/com/google/protobuf/ExtensionRegistry.java b/java/core/src/main/java/com/google/protobuf/ExtensionRegistry.java index a22a74a03c..aeeaee53e2 100644 --- a/java/core/src/main/java/com/google/protobuf/ExtensionRegistry.java +++ b/java/core/src/main/java/com/google/protobuf/ExtensionRegistry.java @@ -40,11 +40,10 @@ import java.util.Map; import java.util.Set; /** - * A table of known extensions, searchable by name or field number. When - * parsing a protocol message that might have extensions, you must provide - * an {@code ExtensionRegistry} in which you have registered any extensions - * that you want to be able to parse. Otherwise, those extensions will just - * be treated like unknown fields. + * A table of known extensions, searchable by name or field number. When parsing a protocol message + * that might have extensions, you must provide an {@code ExtensionRegistry} in which you have + * registered any extensions that you want to be able to parse. Otherwise, those extensions will + * just be treated like unknown fields. * *

For example, if you had the {@code .proto} file: * @@ -70,25 +69,22 @@ import java.util.Set; * *

Background: * - *

You might wonder why this is necessary. Two alternatives might come to - * mind. First, you might imagine a system where generated extensions are - * automatically registered when their containing classes are loaded. This - * is a popular technique, but is bad design; among other things, it creates a - * situation where behavior can change depending on what classes happen to be - * loaded. It also introduces a security vulnerability, because an - * unprivileged class could cause its code to be called unexpectedly from a - * privileged class by registering itself as an extension of the right type. + *

You might wonder why this is necessary. Two alternatives might come to mind. First, you might + * imagine a system where generated extensions are automatically registered when their containing + * classes are loaded. This is a popular technique, but is bad design; among other things, it + * creates a situation where behavior can change depending on what classes happen to be loaded. It + * also introduces a security vulnerability, because an unprivileged class could cause its code to + * be called unexpectedly from a privileged class by registering itself as an extension of the right + * type. * - *

Another option you might consider is lazy parsing: do not parse an - * extension until it is first requested, at which point the caller must - * provide a type to use. This introduces a different set of problems. First, - * it would require a mutex lock any time an extension was accessed, which - * would be slow. Second, corrupt data would not be detected until first - * access, at which point it would be much harder to deal with it. Third, it - * could violate the expectation that message objects are immutable, since the - * type provided could be any arbitrary message class. An unprivileged user - * could take advantage of this to inject a mutable object into a message - * belonging to privileged code and create mischief. + *

Another option you might consider is lazy parsing: do not parse an extension until it is first + * requested, at which point the caller must provide a type to use. This introduces a different set + * of problems. First, it would require a mutex lock any time an extension was accessed, which would + * be slow. Second, corrupt data would not be detected until first access, at which point it would + * be much harder to deal with it. Third, it could violate the expectation that message objects are + * immutable, since the type provided could be any arbitrary message class. An unprivileged user + * could take advantage of this to inject a mutable object into a message belonging to privileged + * code and create mischief. * * @author kenton@google.com Kenton Varda */ @@ -116,8 +112,8 @@ public class ExtensionRegistry extends ExtensionRegistryLite { public final FieldDescriptor descriptor; /** - * A default instance of the extension's type, if it has a message type. - * Otherwise, {@code null}. + * A default instance of the extension's type, if it has a message type. Otherwise, {@code + * null}. */ public final Message defaultInstance; @@ -125,48 +121,41 @@ public class ExtensionRegistry extends ExtensionRegistryLite { this.descriptor = descriptor; defaultInstance = null; } - private ExtensionInfo(final FieldDescriptor descriptor, - final Message defaultInstance) { + + private ExtensionInfo(final FieldDescriptor descriptor, final Message defaultInstance) { this.descriptor = descriptor; this.defaultInstance = defaultInstance; } } - /** - * Deprecated. Use {@link #findImmutableExtensionByName(String)} instead. - */ + /** Deprecated. Use {@link #findImmutableExtensionByName(String)} instead. */ + @Deprecated public ExtensionInfo findExtensionByName(final String fullName) { return findImmutableExtensionByName(fullName); } /** - * Find an extension for immutable APIs by fully-qualified field name, - * in the proto namespace. i.e. {@code result.descriptor.fullName()} will - * match {@code fullName} if a match is found. + * Find an extension for immutable APIs by fully-qualified field name, in the proto namespace. + * i.e. {@code result.descriptor.fullName()} will match {@code fullName} if a match is found. * - * @return Information about the extension if found, or {@code null} - * otherwise. + * @return Information about the extension if found, or {@code null} otherwise. */ public ExtensionInfo findImmutableExtensionByName(final String fullName) { return immutableExtensionsByName.get(fullName); } /** - * Find an extension for mutable APIs by fully-qualified field name, - * in the proto namespace. i.e. {@code result.descriptor.fullName()} will - * match {@code fullName} if a match is found. + * Find an extension for mutable APIs by fully-qualified field name, in the proto namespace. i.e. + * {@code result.descriptor.fullName()} will match {@code fullName} if a match is found. * - * @return Information about the extension if found, or {@code null} - * otherwise. + * @return Information about the extension if found, or {@code null} otherwise. */ public ExtensionInfo findMutableExtensionByName(final String fullName) { return mutableExtensionsByName.get(fullName); } - /** - * Deprecated. Use {@link #findImmutableExtensionByNumber( - * Descriptors.Descriptor, int)} - */ + /** Deprecated. Use {@link #findImmutableExtensionByNumber( Descriptors.Descriptor, int)} */ + @Deprecated public ExtensionInfo findExtensionByNumber( final Descriptor containingType, final int fieldNumber) { return findImmutableExtensionByNumber(containingType, fieldNumber); @@ -175,34 +164,28 @@ public class ExtensionRegistry extends ExtensionRegistryLite { /** * Find an extension by containing type and field number for immutable APIs. * - * @return Information about the extension if found, or {@code null} - * otherwise. + * @return Information about the extension if found, or {@code null} otherwise. */ public ExtensionInfo findImmutableExtensionByNumber( final Descriptor containingType, final int fieldNumber) { - return immutableExtensionsByNumber.get( - new DescriptorIntPair(containingType, fieldNumber)); + return immutableExtensionsByNumber.get(new DescriptorIntPair(containingType, fieldNumber)); } /** * Find an extension by containing type and field number for mutable APIs. * - * @return Information about the extension if found, or {@code null} - * otherwise. + * @return Information about the extension if found, or {@code null} otherwise. */ public ExtensionInfo findMutableExtensionByNumber( final Descriptor containingType, final int fieldNumber) { - return mutableExtensionsByNumber.get( - new DescriptorIntPair(containingType, fieldNumber)); + return mutableExtensionsByNumber.get(new DescriptorIntPair(containingType, fieldNumber)); } /** - * Find all extensions for mutable APIs by fully-qualified name of - * extended class. Note that this method is more computationally expensive - * than getting a single extension by name or number. + * Find all extensions for mutable APIs by fully-qualified name of extended class. Note that this + * method is more computationally expensive than getting a single extension by name or number. * - * @return Information about the extensions found, or {@code null} if there - * are none. + * @return Information about the extensions found, or {@code null} if there are none. */ public Set getAllMutableExtensionsByExtendedType(final String fullName) { HashSet extensions = new HashSet(); @@ -215,12 +198,11 @@ public class ExtensionRegistry extends ExtensionRegistryLite { } /** - * Find all extensions for immutable APIs by fully-qualified name of - * extended class. Note that this method is more computationally expensive - * than getting a single extension by name or number. + * Find all extensions for immutable APIs by fully-qualified name of extended class. Note that + * this method is more computationally expensive than getting a single extension by name or + * number. * - * @return Information about the extensions found, or {@code null} if there - * are none. + * @return Information about the extensions found, or {@code null} if there are none. */ public Set getAllImmutableExtensionsByExtendedType(final String fullName) { HashSet extensions = new HashSet(); @@ -234,8 +216,8 @@ public class ExtensionRegistry extends ExtensionRegistryLite { /** Add an extension from a generated file to the registry. */ public void add(final Extension extension) { - if (extension.getExtensionType() != Extension.ExtensionType.IMMUTABLE && - extension.getExtensionType() != Extension.ExtensionType.MUTABLE) { + if (extension.getExtensionType() != Extension.ExtensionType.IMMUTABLE + && extension.getExtensionType() != Extension.ExtensionType.MUTABLE) { // do not support other extension types. ignore return; } @@ -248,15 +230,14 @@ public class ExtensionRegistry extends ExtensionRegistryLite { } static ExtensionInfo newExtensionInfo(final Extension extension) { - if (extension.getDescriptor().getJavaType() == - FieldDescriptor.JavaType.MESSAGE) { + if (extension.getDescriptor().getJavaType() == FieldDescriptor.JavaType.MESSAGE) { if (extension.getMessageDefaultInstance() == null) { throw new IllegalStateException( - "Registered message-type extension had null default instance: " + - extension.getDescriptor().getFullName()); + "Registered message-type extension had null default instance: " + + extension.getDescriptor().getFullName()); } - return new ExtensionInfo(extension.getDescriptor(), - (Message) extension.getMessageDefaultInstance()); + return new ExtensionInfo( + extension.getDescriptor(), (Message) extension.getMessageDefaultInstance()); } else { return new ExtensionInfo(extension.getDescriptor(), null); } @@ -266,8 +247,8 @@ public class ExtensionRegistry extends ExtensionRegistryLite { public void add(final FieldDescriptor type) { if (type.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { throw new IllegalArgumentException( - "ExtensionRegistry.add() must be provided a default instance when " + - "adding an embedded message extension."); + "ExtensionRegistry.add() must be provided a default instance when " + + "adding an embedded message extension."); } ExtensionInfo info = new ExtensionInfo(type, null); add(info, Extension.ExtensionType.IMMUTABLE); @@ -278,11 +259,9 @@ public class ExtensionRegistry extends ExtensionRegistryLite { public void add(final FieldDescriptor type, final Message defaultInstance) { if (type.getJavaType() != FieldDescriptor.JavaType.MESSAGE) { throw new IllegalArgumentException( - "ExtensionRegistry.add() provided a default instance for a " + - "non-message extension."); + "ExtensionRegistry.add() provided a default instance for a non-message extension."); } - add(new ExtensionInfo(type, defaultInstance), - Extension.ExtensionType.IMMUTABLE); + add(new ExtensionInfo(type, defaultInstance), Extension.ExtensionType.IMMUTABLE); } // ================================================================= @@ -291,22 +270,17 @@ public class ExtensionRegistry extends ExtensionRegistryLite { private ExtensionRegistry() { this.immutableExtensionsByName = new HashMap(); this.mutableExtensionsByName = new HashMap(); - this.immutableExtensionsByNumber = - new HashMap(); - this.mutableExtensionsByNumber = - new HashMap(); + this.immutableExtensionsByNumber = new HashMap(); + this.mutableExtensionsByNumber = new HashMap(); } private ExtensionRegistry(ExtensionRegistry other) { super(other); - this.immutableExtensionsByName = - Collections.unmodifiableMap(other.immutableExtensionsByName); - this.mutableExtensionsByName = - Collections.unmodifiableMap(other.mutableExtensionsByName); + this.immutableExtensionsByName = Collections.unmodifiableMap(other.immutableExtensionsByName); + this.mutableExtensionsByName = Collections.unmodifiableMap(other.mutableExtensionsByName); this.immutableExtensionsByNumber = Collections.unmodifiableMap(other.immutableExtensionsByNumber); - this.mutableExtensionsByNumber = - Collections.unmodifiableMap(other.mutableExtensionsByNumber); + this.mutableExtensionsByNumber = Collections.unmodifiableMap(other.mutableExtensionsByNumber); } private final Map immutableExtensionsByName; @@ -316,24 +290,19 @@ public class ExtensionRegistry extends ExtensionRegistryLite { ExtensionRegistry(boolean empty) { super(EMPTY_REGISTRY_LITE); - this.immutableExtensionsByName = - Collections.emptyMap(); - this.mutableExtensionsByName = - Collections.emptyMap(); - this.immutableExtensionsByNumber = - Collections.emptyMap(); - this.mutableExtensionsByNumber = - Collections.emptyMap(); + this.immutableExtensionsByName = Collections.emptyMap(); + this.mutableExtensionsByName = Collections.emptyMap(); + this.immutableExtensionsByNumber = Collections.emptyMap(); + this.mutableExtensionsByNumber = Collections.emptyMap(); } + static final ExtensionRegistry EMPTY_REGISTRY = new ExtensionRegistry(true); - private void add( - final ExtensionInfo extension, - final Extension.ExtensionType extensionType) { + private void add(final ExtensionInfo extension, final Extension.ExtensionType extensionType) { if (!extension.descriptor.isExtension()) { throw new IllegalArgumentException( - "ExtensionRegistry.add() was given a FieldDescriptor for a regular " + - "(non-extension) field."); + "ExtensionRegistry.add() was given a FieldDescriptor for a regular " + + "(non-extension) field."); } Map extensionsByName; @@ -354,15 +323,15 @@ public class ExtensionRegistry extends ExtensionRegistryLite { extensionsByName.put(extension.descriptor.getFullName(), extension); extensionsByNumber.put( - new DescriptorIntPair(extension.descriptor.getContainingType(), - extension.descriptor.getNumber()), - extension); + new DescriptorIntPair( + extension.descriptor.getContainingType(), extension.descriptor.getNumber()), + extension); final FieldDescriptor field = extension.descriptor; - if (field.getContainingType().getOptions().getMessageSetWireFormat() && - field.getType() == FieldDescriptor.Type.MESSAGE && - field.isOptional() && - field.getExtensionScope() == field.getMessageType()) { + if (field.getContainingType().getOptions().getMessageSetWireFormat() + && field.getType() == FieldDescriptor.Type.MESSAGE + && field.isOptional() + && field.getExtensionScope() == field.getMessageType()) { // This is an extension of a MessageSet type defined within the extension // type's own scope. For backwards-compatibility, allow it to be looked // up by type name. @@ -384,12 +353,13 @@ public class ExtensionRegistry extends ExtensionRegistryLite { public int hashCode() { return descriptor.hashCode() * ((1 << 16) - 1) + number; } + @Override public boolean equals(final Object obj) { if (!(obj instanceof DescriptorIntPair)) { return false; } - final DescriptorIntPair other = (DescriptorIntPair)obj; + final DescriptorIntPair other = (DescriptorIntPair) obj; return descriptor == other.descriptor && number == other.number; } } diff --git a/java/core/src/main/java/com/google/protobuf/ExtensionRegistryFactory.java b/java/core/src/main/java/com/google/protobuf/ExtensionRegistryFactory.java index 89f7ab9b33..f070aae796 100644 --- a/java/core/src/main/java/com/google/protobuf/ExtensionRegistryFactory.java +++ b/java/core/src/main/java/com/google/protobuf/ExtensionRegistryFactory.java @@ -35,16 +35,15 @@ import static com.google.protobuf.ExtensionRegistryLite.EMPTY_REGISTRY_LITE; /** * A factory object to create instances of {@link ExtensionRegistryLite}. * - *

- * This factory detects (via reflection) if the full (non-Lite) protocol buffer libraries - * are available, and if so, the instances returned are actually {@link ExtensionRegistry}. + *

This factory detects (via reflection) if the full (non-Lite) protocol buffer libraries are + * available, and if so, the instances returned are actually {@link ExtensionRegistry}. */ final class ExtensionRegistryFactory { static final String FULL_REGISTRY_CLASS_NAME = "com.google.protobuf.ExtensionRegistry"; /* Visible for Testing - @Nullable */ + @Nullable */ static final Class EXTENSION_REGISTRY_CLASS = reflectExtensionRegistry(); /* @Nullable */ @@ -90,7 +89,7 @@ final class ExtensionRegistryFactory { private static final ExtensionRegistryLite invokeSubclassFactory(String methodName) throws Exception { - return (ExtensionRegistryLite) EXTENSION_REGISTRY_CLASS - .getDeclaredMethod(methodName).invoke(null); + return (ExtensionRegistryLite) + EXTENSION_REGISTRY_CLASS.getDeclaredMethod(methodName).invoke(null); } } diff --git a/java/core/src/main/java/com/google/protobuf/ExtensionRegistryLite.java b/java/core/src/main/java/com/google/protobuf/ExtensionRegistryLite.java index f3d48d3af3..0ce5f5493f 100644 --- a/java/core/src/main/java/com/google/protobuf/ExtensionRegistryLite.java +++ b/java/core/src/main/java/com/google/protobuf/ExtensionRegistryLite.java @@ -36,22 +36,20 @@ import java.util.Map; /** * Equivalent to {@link ExtensionRegistry} but supports only "lite" types. - *

- * If all of your types are lite types, then you only need to use - * {@code ExtensionRegistryLite}. Similarly, if all your types are regular - * types, then you only need {@link ExtensionRegistry}. Typically it does not - * make sense to mix the two, since if you have any regular types in your - * program, you then require the full runtime and lose all the benefits of - * the lite runtime, so you might as well make all your types be regular types. - * However, in some cases (e.g. when depending on multiple third-party libraries - * where one uses lite types and one uses regular), you may find yourself - * wanting to mix the two. In this case things get more complicated. - *

- * There are three factors to consider: Whether the type being extended is - * lite, whether the embedded type (in the case of a message-typed extension) - * is lite, and whether the extension itself is lite. Since all three are - * declared in different files, they could all be different. Here are all - * the combinations and which type of registry to use: + * + *

If all of your types are lite types, then you only need to use {@code ExtensionRegistryLite}. + * Similarly, if all your types are regular types, then you only need {@link ExtensionRegistry}. + * Typically it does not make sense to mix the two, since if you have any regular types in your + * program, you then require the full runtime and lose all the benefits of the lite runtime, so you + * might as well make all your types be regular types. However, in some cases (e.g. when depending + * on multiple third-party libraries where one uses lite types and one uses regular), you may find + * yourself wanting to mix the two. In this case things get more complicated. + * + *

There are three factors to consider: Whether the type being extended is lite, whether the + * embedded type (in the case of a message-typed extension) is lite, and whether the extension + * itself is lite. Since all three are declared in different files, they could all be different. + * Here are all the combinations and which type of registry to use: + * *

  *   Extended type     Inner type    Extension         Use registry
  *   =======================================================================
@@ -60,13 +58,12 @@ import java.util.Map;
  *   regular           regular       regular           ExtensionRegistry
  *   all other combinations                            not supported
  * 
- *

- * Note that just as regular types are not allowed to contain lite-type fields, - * they are also not allowed to contain lite-type extensions. This is because - * regular types must be fully accessible via reflection, which in turn means - * that all the inner messages must also support reflection. On the other hand, - * since regular types implement the entire lite interface, there is no problem - * with embedding regular types inside lite types. + * + *

Note that just as regular types are not allowed to contain lite-type fields, they are also not + * allowed to contain lite-type extensions. This is because regular types must be fully accessible + * via reflection, which in turn means that all the inner messages must also support reflection. On + * the other hand, since regular types implement the entire lite interface, there is no problem with + * embedding regular types inside lite types. * * @author kenton@google.com Kenton Varda */ @@ -114,8 +111,8 @@ public class ExtensionRegistryLite { } /** - * Get the unmodifiable singleton empty instance of either ExtensionRegistryLite or - * {@code ExtensionRegistry} (if the full (non-Lite) proto libraries are available). + * Get the unmodifiable singleton empty instance of either ExtensionRegistryLite or {@code + * ExtensionRegistry} (if the full (non-Lite) proto libraries are available). */ public static ExtensionRegistryLite getEmptyRegistry() { return ExtensionRegistryFactory.createEmpty(); @@ -130,32 +127,27 @@ public class ExtensionRegistryLite { /** * Find an extension by containing type and field number. * - * @return Information about the extension if found, or {@code null} - * otherwise. + * @return Information about the extension if found, or {@code null} otherwise. */ @SuppressWarnings("unchecked") public - GeneratedMessageLite.GeneratedExtension - findLiteExtensionByNumber( - final ContainingType containingTypeDefaultInstance, - final int fieldNumber) { + GeneratedMessageLite.GeneratedExtension findLiteExtensionByNumber( + final ContainingType containingTypeDefaultInstance, final int fieldNumber) { return (GeneratedMessageLite.GeneratedExtension) - extensionsByNumber.get( - new ObjectIntPair(containingTypeDefaultInstance, fieldNumber)); + extensionsByNumber.get(new ObjectIntPair(containingTypeDefaultInstance, fieldNumber)); } /** Add an extension from a lite generated file to the registry. */ - public final void add( - final GeneratedMessageLite.GeneratedExtension extension) { + public final void add(final GeneratedMessageLite.GeneratedExtension extension) { extensionsByNumber.put( - new ObjectIntPair(extension.getContainingTypeDefaultInstance(), - extension.getNumber()), - extension); + new ObjectIntPair(extension.getContainingTypeDefaultInstance(), extension.getNumber()), + extension); } /** - * Add an extension from a lite generated file to the registry only if it is - * a non-lite extension i.e. {@link GeneratedMessageLite.GeneratedExtension}. */ + * Add an extension from a lite generated file to the registry only if it is a non-lite extension + * i.e. {@link GeneratedMessageLite.GeneratedExtension}. + */ public final void add(ExtensionLite extension) { if (GeneratedMessageLite.GeneratedExtension.class.isAssignableFrom(extension.getClass())) { add((GeneratedMessageLite.GeneratedExtension) extension); @@ -178,23 +170,20 @@ public class ExtensionRegistryLite { ExtensionRegistryLite() { this.extensionsByNumber = - new HashMap>(); + new HashMap>(); } - static final ExtensionRegistryLite EMPTY_REGISTRY_LITE = - new ExtensionRegistryLite(true); + + static final ExtensionRegistryLite EMPTY_REGISTRY_LITE = new ExtensionRegistryLite(true); ExtensionRegistryLite(ExtensionRegistryLite other) { if (other == EMPTY_REGISTRY_LITE) { this.extensionsByNumber = Collections.emptyMap(); } else { - this.extensionsByNumber = - Collections.unmodifiableMap(other.extensionsByNumber); + this.extensionsByNumber = Collections.unmodifiableMap(other.extensionsByNumber); } } - private final Map> + private final Map> extensionsByNumber; ExtensionRegistryLite(boolean empty) { @@ -215,12 +204,13 @@ public class ExtensionRegistryLite { public int hashCode() { return System.identityHashCode(object) * ((1 << 16) - 1) + number; } + @Override public boolean equals(final Object obj) { if (!(obj instanceof ObjectIntPair)) { return false; } - final ObjectIntPair other = (ObjectIntPair)obj; + final ObjectIntPair other = (ObjectIntPair) obj; return object == other.object && number == other.number; } } diff --git a/java/core/src/main/java/com/google/protobuf/FieldSet.java b/java/core/src/main/java/com/google/protobuf/FieldSet.java index c09daa32c7..40a37625ac 100644 --- a/java/core/src/main/java/com/google/protobuf/FieldSet.java +++ b/java/core/src/main/java/com/google/protobuf/FieldSet.java @@ -41,32 +41,35 @@ import java.util.List; import java.util.Map; /** - * A class which represents an arbitrary set of fields of some message type. - * This is used to implement {@link DynamicMessage}, and also to represent - * extensions in {@link GeneratedMessage}. This class is package-private, - * since outside users should probably be using {@link DynamicMessage}. + * A class which represents an arbitrary set of fields of some message type. This is used to + * implement {@link DynamicMessage}, and also to represent extensions in {@link GeneratedMessage}. + * This class is package-private, since outside users should probably be using {@link + * DynamicMessage}. * * @author kenton@google.com Kenton Varda */ -final class FieldSet> { +final class FieldSet< + FieldDescriptorType extends FieldSet.FieldDescriptorLite> { /** - * Interface for a FieldDescriptor or lite extension descriptor. This - * prevents FieldSet from depending on {@link Descriptors.FieldDescriptor}. + * Interface for a FieldDescriptor or lite extension descriptor. This prevents FieldSet from + * depending on {@link Descriptors.FieldDescriptor}. */ - public interface FieldDescriptorLite> - extends Comparable { + public interface FieldDescriptorLite> extends Comparable { int getNumber(); + WireFormat.FieldType getLiteType(); + WireFormat.JavaType getLiteJavaType(); + boolean isRepeated(); + boolean isPacked(); + Internal.EnumLiteMap getEnumType(); // If getLiteJavaType() == MESSAGE, this merges a message object of the // type into a builder of the type. Returns {@code to}. - MessageLite.Builder internalMergeFrom( - MessageLite.Builder to, MessageLite from); + MessageLite.Builder internalMergeFrom(MessageLite.Builder to, MessageLite from); } private final SmallSortedMap fields; @@ -78,27 +81,23 @@ final class FieldSet> - FieldSet newFieldSet() { + public static > FieldSet newFieldSet() { return new FieldSet(); } /** Get an immutable empty FieldSet. */ @SuppressWarnings("unchecked") - public static > - FieldSet emptySet() { + public static > FieldSet emptySet() { return DEFAULT_INSTANCE; } + @SuppressWarnings("rawtypes") private static final FieldSet DEFAULT_INSTANCE = new FieldSet(true); @@ -118,8 +117,8 @@ final class FieldSet entry : - fields.getOverflowEntries()) { + for (Map.Entry entry : fields.getOverflowEntries()) { FieldDescriptorType descriptor = entry.getKey(); clone.setField(descriptor, entry.getValue()); } @@ -180,18 +178,14 @@ final class FieldSet getAllFields() { if (hasLazyField) { - SmallSortedMap result = - SmallSortedMap.newFieldMap(16); + SmallSortedMap result = SmallSortedMap.newFieldMap(16); for (int i = 0; i < fields.getNumArrayEntries(); i++) { cloneFieldEntry(result, fields.getArrayEntryAt(i)); } - for (Map.Entry entry : - fields.getOverflowEntries()) { + for (Map.Entry entry : fields.getOverflowEntries()) { cloneFieldEntry(result, entry); } if (fields.isImmutable()) { @@ -202,8 +196,8 @@ final class FieldSet map, - Map.Entry entry) { + private void cloneFieldEntry( + Map map, Map.Entry entry) { FieldDescriptorType key = entry.getKey(); Object value = entry.getValue(); if (value instanceof LazyField) { @@ -214,37 +208,30 @@ final class FieldSet> iterator() { if (hasLazyField) { - return new LazyIterator( - fields.entrySet().iterator()); + return new LazyIterator(fields.entrySet().iterator()); } return fields.entrySet().iterator(); } - /** - * Useful for implementing - * {@link Message#hasField(Descriptors.FieldDescriptor)}. - */ + /** Useful for implementing {@link Message#hasField(Descriptors.FieldDescriptor)}. */ public boolean hasField(final FieldDescriptorType descriptor) { if (descriptor.isRepeated()) { - throw new IllegalArgumentException( - "hasField() can only be called on non-repeated fields."); + throw new IllegalArgumentException("hasField() can only be called on non-repeated fields."); } return fields.get(descriptor) != null; } /** - * Useful for implementing - * {@link Message#getField(Descriptors.FieldDescriptor)}. This method - * returns {@code null} if the field is not set; in this case it is up - * to the caller to fetch the field's default value. + * Useful for implementing {@link Message#getField(Descriptors.FieldDescriptor)}. This method + * returns {@code null} if the field is not set; in this case it is up to the caller to fetch the + * field's default value. */ public Object getField(final FieldDescriptorType descriptor) { Object o = fields.get(descriptor); @@ -255,16 +242,14 @@ final class FieldSet entry : - fields.getOverflowEntries()) { + for (final Map.Entry entry : fields.getOverflowEntries()) { if (!isInitialized(entry)) { return false; } @@ -454,13 +434,11 @@ final class FieldSet entry) { + private boolean isInitialized(final Map.Entry entry) { final FieldDescriptorType descriptor = entry.getKey(); if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE) { if (descriptor.isRepeated()) { - for (final MessageLite element: - (List) entry.getValue()) { + for (final MessageLite element : (List) entry.getValue()) { if (!element.isInitialized()) { return false; } @@ -485,11 +463,9 @@ final class FieldSet other) { for (int i = 0; i < other.fields.getNumArrayEntries(); i++) { mergeFromField(other.fields.getArrayEntryAt(i)); } - for (final Map.Entry entry : - other.fields.getOverflowEntries()) { + for (final Map.Entry entry : other.fields.getOverflowEntries()) { mergeFromField(entry); } } @@ -523,8 +495,7 @@ final class FieldSet entry) { + private void mergeFromField(final Map.Entry entry) { final FieldDescriptorType descriptor = entry.getKey(); Object otherValue = entry.getValue(); if (otherValue instanceof LazyField) { @@ -546,9 +517,10 @@ final class FieldSet entry = - fields.getArrayEntryAt(i); + final Map.Entry entry = fields.getArrayEntryAt(i); writeField(entry.getKey(), entry.getValue(), output); } - for (final Map.Entry entry : - fields.getOverflowEntries()) { + for (final Map.Entry entry : fields.getOverflowEntries()) { writeField(entry.getKey(), entry.getValue(), output); } } - /** - * Like {@link #writeTo} but uses MessageSet wire format. - */ - public void writeMessageSetTo(final CodedOutputStream output) - throws IOException { + /** Like {@link #writeTo} but uses MessageSet wire format. */ + public void writeMessageSetTo(final CodedOutputStream output) throws IOException { for (int i = 0; i < fields.getNumArrayEntries(); i++) { writeMessageSetTo(fields.getArrayEntryAt(i), output); } - for (final Map.Entry entry : - fields.getOverflowEntries()) { + for (final Map.Entry entry : fields.getOverflowEntries()) { writeMessageSetTo(entry, output); } } private void writeMessageSetTo( - final Map.Entry entry, - final CodedOutputStream output) throws IOException { + final Map.Entry entry, final CodedOutputStream output) + throws IOException { final FieldDescriptorType descriptor = entry.getKey(); - if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE && - !descriptor.isRepeated() && !descriptor.isPacked()) { + if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE + && !descriptor.isRepeated() + && !descriptor.isPacked()) { Object value = entry.getValue(); if (value instanceof LazyField) { value = ((LazyField) value).getValue(); } - output.writeMessageSetExtension(entry.getKey().getNumber(), - (MessageLite) value); + output.writeMessageSetExtension(entry.getKey().getNumber(), (MessageLite) value); } else { writeField(descriptor, entry.getValue(), output); } @@ -636,18 +595,17 @@ final class FieldSet descriptor, - final Object value, - final CodedOutputStream output) - throws IOException { + public static void writeField( + final FieldDescriptorLite descriptor, final Object value, final CodedOutputStream output) + throws IOException { WireFormat.FieldType type = descriptor.getLiteType(); int number = descriptor.getNumber(); if (descriptor.isRepeated()) { - final List valueList = (List)value; + final List valueList = (List) value; if (descriptor.isPacked()) { output.writeTag(number, WireFormat.WIRETYPE_LENGTH_DELIMITED); // Compute the total data size so the length can be written. @@ -749,44 +733,39 @@ final class FieldSet entry = - fields.getArrayEntryAt(i); + final Map.Entry entry = fields.getArrayEntryAt(i); size += computeFieldSize(entry.getKey(), entry.getValue()); } - for (final Map.Entry entry : - fields.getOverflowEntries()) { + for (final Map.Entry entry : fields.getOverflowEntries()) { size += computeFieldSize(entry.getKey(), entry.getValue()); } return size; } - /** - * Like {@link #getSerializedSize} but uses MessageSet wire format. - */ + /** Like {@link #getSerializedSize} but uses MessageSet wire format. */ public int getMessageSetSerializedSize() { int size = 0; for (int i = 0; i < fields.getNumArrayEntries(); i++) { size += getMessageSetSerializedSize(fields.getArrayEntryAt(i)); } - for (final Map.Entry entry : - fields.getOverflowEntries()) { + for (final Map.Entry entry : fields.getOverflowEntries()) { size += getMessageSetSerializedSize(entry); } return size; } - private int getMessageSetSerializedSize( - final Map.Entry entry) { + private int getMessageSetSerializedSize(final Map.Entry entry) { final FieldDescriptorType descriptor = entry.getKey(); Object value = entry.getValue(); if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE - && !descriptor.isRepeated() && !descriptor.isPacked()) { + && !descriptor.isRepeated() + && !descriptor.isPacked()) { if (value instanceof LazyField) { return CodedOutputStream.computeLazyFieldMessageSetExtensionSize( entry.getKey().getNumber(), (LazyField) value); @@ -800,15 +779,13 @@ final class FieldSet descriptor, - final Object value) { + /** Compute the number of bytes needed to encode a particular field. */ + public static int computeFieldSize(final FieldDescriptorLite descriptor, final Object value) { WireFormat.FieldType type = descriptor.getLiteType(); int number = descriptor.getNumber(); if (descriptor.isRepeated()) { if (descriptor.isPacked()) { int dataSize = 0; - for (final Object element : (List)value) { + for (final Object element : (List) value) { dataSize += computeElementSizeNoTag(type, element); } - return dataSize + - CodedOutputStream.computeTagSize(number) + - CodedOutputStream.computeRawVarint32Size(dataSize); + return dataSize + + CodedOutputStream.computeTagSize(number) + + CodedOutputStream.computeRawVarint32Size(dataSize); } else { int size = 0; - for (final Object element : (List)value) { + for (final Object element : (List) value) { size += computeElementSize(type, number, element); } return size; diff --git a/java/core/src/main/java/com/google/protobuf/FloatArrayList.java b/java/core/src/main/java/com/google/protobuf/FloatArrayList.java index 41749f6dbd..85e09becb5 100644 --- a/java/core/src/main/java/com/google/protobuf/FloatArrayList.java +++ b/java/core/src/main/java/com/google/protobuf/FloatArrayList.java @@ -42,11 +42,11 @@ import java.util.RandomAccess; * * @author dweis@google.com (Daniel Weis) */ -final class FloatArrayList - extends AbstractProtobufList +final class FloatArrayList extends AbstractProtobufList implements FloatList, RandomAccess, PrimitiveNonBoxingCollection { private static final FloatArrayList EMPTY_LIST = new FloatArrayList(); + static { EMPTY_LIST.makeImmutable(); } @@ -55,9 +55,7 @@ final class FloatArrayList return EMPTY_LIST; } - /** - * The backing store for the list. - */ + /** The backing store for the list. */ private float[] array; /** @@ -66,16 +64,13 @@ final class FloatArrayList */ private int size; - /** - * Constructs a new mutable {@code FloatArrayList} with default capacity. - */ + /** Constructs a new mutable {@code FloatArrayList} with default capacity. */ FloatArrayList() { this(new float[DEFAULT_CAPACITY], 0); } /** - * Constructs a new mutable {@code FloatArrayList} - * containing the same elements as {@code other}. + * Constructs a new mutable {@code FloatArrayList} containing the same elements as {@code other}. */ private FloatArrayList(float[] other, int size) { array = other; @@ -169,17 +164,13 @@ final class FloatArrayList addFloat(index, element); } - /** - * Like {@link #add(Float)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #add(Float)} but more efficient in that it doesn't box the element. */ @Override public void addFloat(float element) { addFloat(size, element); } - /** - * Like {@link #add(int, Float)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #add(int, Float)} but more efficient in that it doesn't box the element. */ private void addFloat(int index, float element) { ensureIsMutable(); if (index < 0 || index > size) { diff --git a/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java b/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java index ff670fd831..0034c58c88 100644 --- a/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java +++ b/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java @@ -58,9 +58,9 @@ import java.util.concurrent.ConcurrentHashMap; * @author kenton@google.com Kenton Varda */ public abstract class GeneratedMessageLite< - MessageType extends GeneratedMessageLite, - BuilderType extends GeneratedMessageLite.Builder> - extends AbstractMessageLite { + MessageType extends GeneratedMessageLite, + BuilderType extends GeneratedMessageLite.Builder> + extends AbstractMessageLite { // BEGIN REGULAR static final boolean ENABLE_EXPERIMENTAL_RUNTIME_AT_BUILD_TIME = false; // END REGULAR @@ -71,7 +71,7 @@ public abstract class GeneratedMessageLite< /** For use by generated code only. Lazily initialized to reduce allocations. */ protected UnknownFieldSetLite unknownFields = UnknownFieldSetLite.getDefaultInstance(); - /** For use by generated code only. */ + /** For use by generated code only. */ protected int memoizedSerializedSize = -1; @Override @@ -97,11 +97,11 @@ public abstract class GeneratedMessageLite< * binary size down. The first line of the {@code toString()} representation includes a commented * version of {@code super.toString()} to act as an indicator that this should not be relied on * for comparisons. - *

- * NOTE: This method relies on the field getter methods not being stripped or renamed by proguard. - * If they are, the fields will not be included in the returned string representation. - *

- * NOTE: This implementation is liable to change in the future, and should not be relied on in + * + *

NOTE: This method relies on the field getter methods not being stripped or renamed by + * proguard. If they are, the fields will not be included in the returned string representation. + * + *

NOTE: This implementation is liable to change in the future, and should not be relied on in * code. */ @Override @@ -209,25 +209,19 @@ public abstract class GeneratedMessageLite< return unknownFields.mergeFieldFrom(tag, input); } - /** - * Called by subclasses to parse an unknown field. For use by generated code only. - */ + /** Called by subclasses to parse an unknown field. For use by generated code only. */ protected void mergeVarintField(int tag, int value) { ensureUnknownFieldsInitialized(); unknownFields.mergeVarintField(tag, value); } - /** - * Called by subclasses to parse an unknown field. For use by generated code only. - */ + /** Called by subclasses to parse an unknown field. For use by generated code only. */ protected void mergeLengthDelimitedField(int fieldNumber, ByteString value) { ensureUnknownFieldsInitialized(); unknownFields.mergeLengthDelimitedField(fieldNumber, value); } - /** - * Called by subclasses to complete parsing. For use by generated code only. - */ + /** Called by subclasses to complete parsing. For use by generated code only. */ protected void makeImmutable() { // BEGIN REGULAR dynamicMethod(MethodToInvoke.MAKE_IMMUTABLE); @@ -239,16 +233,16 @@ public abstract class GeneratedMessageLite< } protected final < - MessageType extends GeneratedMessageLite, - BuilderType extends GeneratedMessageLite.Builder> - BuilderType createBuilder() { + MessageType extends GeneratedMessageLite, + BuilderType extends GeneratedMessageLite.Builder> + BuilderType createBuilder() { return (BuilderType) dynamicMethod(MethodToInvoke.NEW_BUILDER); } protected final < - MessageType extends GeneratedMessageLite, - BuilderType extends GeneratedMessageLite.Builder> - BuilderType createBuilder(MessageType prototype) { + MessageType extends GeneratedMessageLite, + BuilderType extends GeneratedMessageLite.Builder> + BuilderType createBuilder(MessageType prototype) { return ((BuilderType) createBuilder()).mergeFrom(prototype); } @@ -268,8 +262,8 @@ public abstract class GeneratedMessageLite< /** * Defines which method path to invoke in {@link GeneratedMessageLite * #dynamicMethod(MethodToInvoke, Object...)}. - *

- * For use by generated code only. + * + *

For use by generated code only. */ public static enum MethodToInvoke { // BEGIN REGULAR @@ -321,16 +315,12 @@ public abstract class GeneratedMessageLite< */ protected abstract Object dynamicMethod(MethodToInvoke method, Object arg0, Object arg1); - /** - * Same as {@link #dynamicMethod(MethodToInvoke, Object, Object)} with {@code null} padding. - */ + /** Same as {@link #dynamicMethod(MethodToInvoke, Object, Object)} with {@code null} padding. */ protected Object dynamicMethod(MethodToInvoke method, Object arg0) { return dynamicMethod(method, arg0, null); } - /** - * Same as {@link #dynamicMethod(MethodToInvoke, Object, Object)} with {@code null} padding. - */ + /** Same as {@link #dynamicMethod(MethodToInvoke, Object, Object)} with {@code null} padding. */ protected Object dynamicMethod(MethodToInvoke method) { return dynamicMethod(method, null, null); } @@ -365,9 +355,9 @@ public abstract class GeneratedMessageLite< @SuppressWarnings("unchecked") public abstract static class Builder< - MessageType extends GeneratedMessageLite, - BuilderType extends Builder> - extends AbstractMessageLite.Builder { + MessageType extends GeneratedMessageLite, + BuilderType extends Builder> + extends AbstractMessageLite.Builder { private final MessageType defaultInstance; protected MessageType instance; @@ -381,8 +371,8 @@ public abstract class GeneratedMessageLite< } /** - * Called before any method that would mutate the builder to ensure that it correctly copies - * any state before the write happens to preserve immutability guarantees. + * Called before any method that would mutate the builder to ensure that it correctly copies any + * state before the write happens to preserve immutability guarantees. */ protected void copyOnWrite() { if (isBuilt) { @@ -396,7 +386,7 @@ public abstract class GeneratedMessageLite< @Override public final boolean isInitialized() { - return GeneratedMessageLite.isInitialized(instance, false /* shouldMemoize */); + return GeneratedMessageLite.isInitialized(instance, /* shouldMemoize= */ false); } @Override @@ -408,8 +398,7 @@ public abstract class GeneratedMessageLite< @Override public BuilderType clone() { - BuilderType builder = - (BuilderType) getDefaultInstanceForType().newBuilderForType(); + BuilderType builder = (BuilderType) getDefaultInstanceForType().newBuilderForType(); builder.mergeFrom(buildPartial()); return builder; } @@ -511,39 +500,31 @@ public abstract class GeneratedMessageLite< // ================================================================= // Extensions-related stuff - /** - * Lite equivalent of {@link com.google.protobuf.GeneratedMessage.ExtendableMessageOrBuilder}. - */ + /** Lite equivalent of {@link com.google.protobuf.GeneratedMessage.ExtendableMessageOrBuilder}. */ public interface ExtendableMessageOrBuilder< - MessageType extends ExtendableMessage, - BuilderType extends ExtendableBuilder> - extends MessageLiteOrBuilder { + MessageType extends ExtendableMessage, + BuilderType extends ExtendableBuilder> + extends MessageLiteOrBuilder { /** 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); /** Get one element of a repeated extension. */ - Type getExtension( - ExtensionLite> extension, - int index); + Type getExtension(ExtensionLite> extension, int index); } - /** - * Lite equivalent of {@link GeneratedMessage.ExtendableMessage}. - */ + /** Lite equivalent of {@link GeneratedMessage.ExtendableMessage}. */ public abstract static class ExtendableMessage< - MessageType extends ExtendableMessage, - BuilderType extends ExtendableBuilder> - extends GeneratedMessageLite - implements ExtendableMessageOrBuilder { + MessageType extends ExtendableMessage, + BuilderType extends ExtendableBuilder> + extends GeneratedMessageLite + implements ExtendableMessageOrBuilder { /** Represents the set of extensions on this message. For use by generated code only. */ protected FieldSet extensions = FieldSet.emptySet(); @@ -581,8 +562,8 @@ public abstract class GeneratedMessageLite< // TODO(dweis): How much bytecode would be saved by not requiring the generated code to // provide the default instance? - GeneratedExtension extension = extensionRegistry.findLiteExtensionByNumber( - defaultInstance, fieldNumber); + GeneratedExtension extension = + extensionRegistry.findLiteExtensionByNumber(defaultInstance, fieldNumber); return parseExtension(input, extensionRegistry, extension, tag, fieldNumber); } @@ -598,22 +579,22 @@ public abstract class GeneratedMessageLite< boolean unknown = false; boolean packed = false; if (extension == null) { - unknown = true; // Unknown field. - } else if (wireType == FieldSet.getWireFormatForFieldType( - extension.descriptor.getLiteType(), - false /* isPacked */)) { - packed = false; // Normal, unpacked value. - } else if (extension.descriptor.isRepeated && - extension.descriptor.type.isPackable() && - wireType == FieldSet.getWireFormatForFieldType( - extension.descriptor.getLiteType(), - true /* isPacked */)) { - packed = true; // Packed value. + unknown = true; // Unknown field. + } else if (wireType + == FieldSet.getWireFormatForFieldType( + extension.descriptor.getLiteType(), /* isPacked= */ false)) { + packed = false; // Normal, unpacked value. + } else if (extension.descriptor.isRepeated + && extension.descriptor.type.isPackable() + && wireType + == FieldSet.getWireFormatForFieldType( + extension.descriptor.getLiteType(), /* isPacked= */ true)) { + packed = true; // Packed value. } else { - unknown = true; // Wrong wire type. + unknown = true; // Wrong wire type. } - if (unknown) { // Unknown field or wrong wire type. Skip. + if (unknown) { // Unknown field or wrong wire type. Skip. return parseUnknownField(tag, input); } @@ -625,22 +606,20 @@ public abstract class GeneratedMessageLite< if (extension.descriptor.getLiteType() == WireFormat.FieldType.ENUM) { while (input.getBytesUntilLimit() > 0) { int rawValue = input.readEnum(); - Object value = - extension.descriptor.getEnumType().findValueByNumber(rawValue); + Object value = extension.descriptor.getEnumType().findValueByNumber(rawValue); if (value == null) { // If the number isn't recognized as a valid value for this // enum, drop it (don't even add it to unknownFields). return true; } - extensions.addRepeatedField(extension.descriptor, - extension.singularToFieldSetType(value)); + extensions.addRepeatedField( + extension.descriptor, extension.singularToFieldSetType(value)); } } else { while (input.getBytesUntilLimit() > 0) { Object value = - FieldSet.readPrimitiveField(input, - extension.descriptor.getLiteType(), - /*checkUtf8=*/ false); + FieldSet.readPrimitiveField( + input, extension.descriptor.getLiteType(), /*checkUtf8=*/ false); extensions.addRepeatedField(extension.descriptor, value); } } @@ -648,33 +627,29 @@ public abstract class GeneratedMessageLite< } else { Object value; switch (extension.descriptor.getLiteJavaType()) { - case MESSAGE: { - MessageLite.Builder subBuilder = null; - if (!extension.descriptor.isRepeated()) { - MessageLite existingValue = - (MessageLite) extensions.getField(extension.descriptor); - if (existingValue != null) { - subBuilder = existingValue.toBuilder(); + case MESSAGE: + { + MessageLite.Builder subBuilder = null; + if (!extension.descriptor.isRepeated()) { + MessageLite existingValue = (MessageLite) extensions.getField(extension.descriptor); + if (existingValue != null) { + subBuilder = existingValue.toBuilder(); + } } + if (subBuilder == null) { + subBuilder = extension.getMessageDefaultInstance().newBuilderForType(); + } + if (extension.descriptor.getLiteType() == WireFormat.FieldType.GROUP) { + input.readGroup(extension.getNumber(), subBuilder, extensionRegistry); + } else { + input.readMessage(subBuilder, extensionRegistry); + } + value = subBuilder.build(); + break; } - if (subBuilder == null) { - subBuilder = extension.getMessageDefaultInstance() - .newBuilderForType(); - } - if (extension.descriptor.getLiteType() == - WireFormat.FieldType.GROUP) { - input.readGroup(extension.getNumber(), - subBuilder, extensionRegistry); - } else { - input.readMessage(subBuilder, extensionRegistry); - } - value = subBuilder.build(); - break; - } case ENUM: int rawValue = input.readEnum(); - value = extension.descriptor.getEnumType() - .findValueByNumber(rawValue); + value = extension.descriptor.getEnumType().findValueByNumber(rawValue); // If the number isn't recognized as a valid value for this enum, // write it to unknown fields object. if (value == null) { @@ -683,23 +658,22 @@ public abstract class GeneratedMessageLite< } break; default: - value = FieldSet.readPrimitiveField(input, - extension.descriptor.getLiteType(), - /*checkUtf8=*/ false); + value = + FieldSet.readPrimitiveField( + input, extension.descriptor.getLiteType(), /*checkUtf8=*/ false); break; } if (extension.descriptor.isRepeated()) { - extensions.addRepeatedField(extension.descriptor, - extension.singularToFieldSetType(value)); + extensions.addRepeatedField( + extension.descriptor, extension.singularToFieldSetType(value)); } else { - extensions.setField(extension.descriptor, - extension.singularToFieldSetType(value)); + extensions.setField(extension.descriptor, extension.singularToFieldSetType(value)); } } return true; } - + /** * Parse an unknown field or an extension. For use by generated code only. * @@ -732,7 +706,7 @@ public abstract class GeneratedMessageLite< /** * Merges the message set from the input stream; requires message set wire format. - * + * * @param defaultInstance the default instance of the containing message we are parsing in * @param input the stream to parse from * @param extensionRegistry the registry to use when parsing @@ -836,8 +810,8 @@ public abstract class GeneratedMessageLite< subBuilder.mergeFrom(rawBytes, extensionRegistry); MessageLite value = subBuilder.build(); - ensureExtensionsAreMutable().setField( - extension.descriptor, extension.singularToFieldSetType(value)); + ensureExtensionsAreMutable() + .setField(extension.descriptor, extension.singularToFieldSetType(value)); } private FieldSet ensureExtensionsAreMutable() { @@ -847,22 +821,19 @@ public abstract class GeneratedMessageLite< return extensions; } - private void verifyExtensionContainingType( - final GeneratedExtension extension) { - if (extension.getContainingTypeDefaultInstance() != - getDefaultInstanceForType()) { + private void verifyExtensionContainingType(final GeneratedExtension extension) { + if (extension.getContainingTypeDefaultInstance() != getDefaultInstanceForType()) { // This can only happen if someone uses unchecked operations. throw new IllegalArgumentException( - "This extension is for a different message type. Please make " + - "sure that you are not suppressing any generics type warnings."); + "This extension is for a different message type. Please make " + + "sure that you are not suppressing any generics type warnings."); } } /** Check if a singular extension is present. */ @Override public final boolean hasExtension(final ExtensionLite extension) { - GeneratedExtension extensionLite = - checkIsLite(extension); + GeneratedExtension extensionLite = checkIsLite(extension); verifyExtensionContainingType(extensionLite); return extensions.hasField(extensionLite.descriptor); @@ -872,8 +843,7 @@ public abstract class GeneratedMessageLite< @Override public final int getExtensionCount( final ExtensionLite> extension) { - GeneratedExtension> extensionLite = - checkIsLite(extension); + GeneratedExtension> extensionLite = checkIsLite(extension); verifyExtensionContainingType(extensionLite); return extensions.getRepeatedFieldCount(extensionLite.descriptor); @@ -883,8 +853,7 @@ public abstract class GeneratedMessageLite< @Override @SuppressWarnings("unchecked") public final Type getExtension(final ExtensionLite extension) { - GeneratedExtension extensionLite = - checkIsLite(extension); + GeneratedExtension extensionLite = checkIsLite(extension); verifyExtensionContainingType(extensionLite); final Object value = extensions.getField(extensionLite.descriptor); @@ -900,12 +869,12 @@ public abstract class GeneratedMessageLite< @SuppressWarnings("unchecked") public final Type getExtension( final ExtensionLite> extension, final int index) { - GeneratedExtension> extensionLite = - checkIsLite(extension); + GeneratedExtension> extensionLite = checkIsLite(extension); verifyExtensionContainingType(extensionLite); - return (Type) extensionLite.singularFromFieldSetType( - extensions.getRepeatedField(extensionLite.descriptor, index)); + return (Type) + extensionLite.singularFromFieldSetType( + extensions.getRepeatedField(extensionLite.descriptor, index)); } /** Called by subclasses to check if all extensions are initialized. */ @@ -921,19 +890,16 @@ public abstract class GeneratedMessageLite< // END REGULAR } - /** - * 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; @@ -944,15 +910,13 @@ public abstract class GeneratedMessageLite< 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) { ExtensionDescriptor extension = next.getKey(); - if (messageSetWireFormat && extension.getLiteJavaType() == - WireFormat.JavaType.MESSAGE && - !extension.isRepeated()) { - output.writeMessageSetExtension(extension.getNumber(), - (MessageLite) next.getValue()); + if (messageSetWireFormat + && extension.getLiteJavaType() == WireFormat.JavaType.MESSAGE + && !extension.isRepeated()) { + output.writeMessageSetExtension(extension.getNumber(), (MessageLite) next.getValue()); } else { FieldSet.writeField(extension, next.getValue(), output); } @@ -968,6 +932,7 @@ public abstract class GeneratedMessageLite< protected ExtensionWriter newExtensionWriter() { return new ExtensionWriter(false); } + protected ExtensionWriter newMessageSetExtensionWriter() { return new ExtensionWriter(true); } @@ -976,18 +941,17 @@ public abstract class GeneratedMessageLite< protected int extensionsSerializedSize() { return extensions.getSerializedSize(); } + protected int extensionsSerializedSizeAsMessageSet() { return extensions.getMessageSetSerializedSize(); } } - /** - * Lite equivalent of {@link GeneratedMessage.ExtendableBuilder}. - */ + /** Lite equivalent of {@link GeneratedMessage.ExtendableBuilder}. */ @SuppressWarnings("unchecked") public abstract static class ExtendableBuilder< - MessageType extends ExtendableMessage, - BuilderType extends ExtendableBuilder> + MessageType extends ExtendableMessage, + BuilderType extends ExtendableBuilder> extends Builder implements ExtendableMessageOrBuilder { protected ExtendableBuilder(MessageType defaultInstance) { @@ -1029,14 +993,12 @@ public abstract class GeneratedMessageLite< return super.buildPartial(); } - private void verifyExtensionContainingType( - final GeneratedExtension extension) { - if (extension.getContainingTypeDefaultInstance() != - getDefaultInstanceForType()) { + private void verifyExtensionContainingType(final GeneratedExtension extension) { + if (extension.getContainingTypeDefaultInstance() != getDefaultInstanceForType()) { // This can only happen if someone uses unchecked operations. throw new IllegalArgumentException( - "This extension is for a different message type. Please make " + - "sure that you are not suppressing any generics type warnings."); + "This extension is for a different message type. Please make " + + "sure that you are not suppressing any generics type warnings."); } } @@ -1070,10 +1032,8 @@ public abstract class GeneratedMessageLite< /** Set the value of an extension. */ public final BuilderType setExtension( - final ExtensionLite extension, - final Type value) { - GeneratedExtension extensionLite = - checkIsLite(extension); + final ExtensionLite extension, final Type value) { + GeneratedExtension extensionLite = checkIsLite(extension); verifyExtensionContainingType(extensionLite); copyOnWrite(); @@ -1084,10 +1044,8 @@ public abstract class GeneratedMessageLite< /** Set the value of one element of a repeated extension. */ public final BuilderType setExtension( - final ExtensionLite> extension, - final int index, final Type value) { - GeneratedExtension> extensionLite = - checkIsLite(extension); + final ExtensionLite> extension, final int index, final Type value) { + GeneratedExtension> extensionLite = checkIsLite(extension); verifyExtensionContainingType(extensionLite); copyOnWrite(); @@ -1099,10 +1057,8 @@ public abstract class GeneratedMessageLite< /** Append a value to a repeated extension. */ public final BuilderType addExtension( - final ExtensionLite> extension, - final Type value) { - GeneratedExtension> extensionLite = - checkIsLite(extension); + final ExtensionLite> extension, final Type value) { + GeneratedExtension> extensionLite = checkIsLite(extension); verifyExtensionContainingType(extensionLite); copyOnWrite(); @@ -1112,8 +1068,7 @@ public abstract class GeneratedMessageLite< } /** Clear an extension. */ - public final BuilderType clearExtension( - final ExtensionLite extension) { + public final BuilderType clearExtension(final ExtensionLite extension) { GeneratedExtension extensionLite = checkIsLite(extension); verifyExtensionContainingType(extensionLite); @@ -1127,50 +1082,45 @@ public abstract class GeneratedMessageLite< /** For use by generated code only. */ public static - GeneratedExtension - newSingularGeneratedExtension( - final ContainingType containingTypeDefaultInstance, - final Type defaultValue, - final MessageLite messageDefaultInstance, - final Internal.EnumLiteMap enumTypeMap, - final int number, - final WireFormat.FieldType type, - final Class singularType) { + GeneratedExtension newSingularGeneratedExtension( + final ContainingType containingTypeDefaultInstance, + final Type defaultValue, + final MessageLite messageDefaultInstance, + final Internal.EnumLiteMap enumTypeMap, + final int number, + final WireFormat.FieldType type, + final Class singularType) { return new GeneratedExtension( containingTypeDefaultInstance, defaultValue, messageDefaultInstance, - new ExtensionDescriptor(enumTypeMap, number, type, - false /* isRepeated */, - false /* isPacked */), + new ExtensionDescriptor( + enumTypeMap, number, type, /* isRepeated= */ false, /* isPacked= */ false), singularType); } /** For use by generated code only. */ public static - GeneratedExtension - newRepeatedGeneratedExtension( - final ContainingType containingTypeDefaultInstance, - final MessageLite messageDefaultInstance, - final Internal.EnumLiteMap enumTypeMap, - final int number, - final WireFormat.FieldType type, - final boolean isPacked, - final Class singularType) { - @SuppressWarnings("unchecked") // Subclasses ensure Type is a List + GeneratedExtension newRepeatedGeneratedExtension( + final ContainingType containingTypeDefaultInstance, + final MessageLite messageDefaultInstance, + final Internal.EnumLiteMap enumTypeMap, + final int number, + final WireFormat.FieldType type, + final boolean isPacked, + final Class singularType) { + @SuppressWarnings("unchecked") // Subclasses ensure Type is a List Type emptyList = (Type) Collections.emptyList(); return new GeneratedExtension( containingTypeDefaultInstance, emptyList, messageDefaultInstance, - new ExtensionDescriptor( - enumTypeMap, number, type, true /* isRepeated */, isPacked), + new ExtensionDescriptor(enumTypeMap, number, type, /* isRepeated= */ true, isPacked), singularType); } static final class ExtensionDescriptor - implements FieldSet.FieldDescriptorLite< - ExtensionDescriptor> { + implements FieldSet.FieldDescriptorLite { ExtensionDescriptor( final Internal.EnumLiteMap enumTypeMap, final int number, @@ -1242,8 +1192,8 @@ public abstract class GeneratedMessageLite< 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); } } @@ -1253,8 +1203,7 @@ public abstract class GeneratedMessageLite< 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) { @@ -1263,7 +1212,7 @@ public abstract class GeneratedMessageLite< throw (Error) cause; } else { throw new RuntimeException( - "Unexpected exception thrown by generated accessor method.", cause); + "Unexpected exception thrown by generated accessor method.", cause); } } } @@ -1272,20 +1221,18 @@ public abstract class GeneratedMessageLite< /** * Lite equivalent to {@link GeneratedMessage.GeneratedExtension}. * - * Users should ignore the contents of this class and only use objects of - * this type as parameters to extension accessors and ExtensionRegistry.add(). + *

Users should ignore the contents of this class and only use objects of this type as + * parameters to extension accessors and ExtensionRegistry.add(). */ - public static class GeneratedExtension< - ContainingType extends MessageLite, Type> - extends ExtensionLite { + public static class GeneratedExtension + extends ExtensionLite { /** * Create a new instance with the given parameters. * - * The last parameter {@code singularType} is only needed for enum types. - * We store integer values for enum types in a {@link ExtendableMessage} - * and use Java reflection to convert an integer value back into a concrete - * enum object. + *

The last parameter {@code singularType} is only needed for enum types. We store integer + * values for enum types in a {@link ExtendableMessage} and use Java reflection to convert an + * integer value back into a concrete enum object. */ GeneratedExtension( final ContainingType containingTypeDefaultInstance, @@ -1296,13 +1243,11 @@ public abstract class GeneratedMessageLite< // Defensive checks to verify the correct initialization order of // GeneratedExtensions and their related GeneratedMessages. if (containingTypeDefaultInstance == null) { - throw new IllegalArgumentException( - "Null containingTypeDefaultInstance"); + throw new IllegalArgumentException("Null containingTypeDefaultInstance"); } - if (descriptor.getLiteType() == WireFormat.FieldType.MESSAGE && - messageDefaultInstance == null) { - throw new IllegalArgumentException( - "Null messageDefaultInstance"); + if (descriptor.getLiteType() == WireFormat.FieldType.MESSAGE + && messageDefaultInstance == null) { + throw new IllegalArgumentException("Null messageDefaultInstance"); } this.containingTypeDefaultInstance = containingTypeDefaultInstance; this.defaultValue = defaultValue; @@ -1315,9 +1260,7 @@ public abstract class GeneratedMessageLite< final MessageLite messageDefaultInstance; final ExtensionDescriptor descriptor; - /** - * Default instance of the type being extended, used to identify that type. - */ + /** Default instance of the type being extended, used to identify that type. */ public ContainingType getContainingTypeDefaultInstance() { return containingTypeDefaultInstance; } @@ -1328,10 +1271,9 @@ public abstract class GeneratedMessageLite< return descriptor.getNumber(); } - /** - * 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 MessageLite getMessageDefaultInstance() { @@ -1405,8 +1347,8 @@ public abstract class GeneratedMessageLite< } /** - * A serialized (serializable) form of the generated message. Stores the - * message as a class and a byte array. + * A serialized (serializable) form of the generated message. Stores the message as a class name + * and a byte array. */ protected static final class SerializedForm implements Serializable { @@ -1424,6 +1366,7 @@ public abstract class GeneratedMessageLite< /** * Creates the serialized form by calling {@link com.google.protobuf.MessageLite#toByteArray}. + * * @param regularForm the message to serialize */ SerializedForm(MessageLite regularForm) { @@ -1433,8 +1376,9 @@ public abstract class GeneratedMessageLite< } /** - * When read from an ObjectInputStream, this method converts this object - * back to the regular form. Part of Java's serialization magic. + * When read from an ObjectInputStream, this method converts this object back to the regular + * form. Part of Java's serialization magic. + * * @return a GeneratedMessage of the type that was serialized */ @SuppressWarnings("unchecked") @@ -1445,9 +1389,7 @@ public abstract class GeneratedMessageLite< messageClass.getDeclaredField("DEFAULT_INSTANCE"); defaultInstanceField.setAccessible(true); MessageLite defaultInstance = (MessageLite) defaultInstanceField.get(null); - return defaultInstance.newBuilderForType() - .mergeFrom(asBytes) - .buildPartial(); + return defaultInstance.newBuilderForType().mergeFrom(asBytes).buildPartial(); } catch (ClassNotFoundException e) { throw new RuntimeException("Unable to find proto buffer class: " + messageClassName, e); } catch (NoSuchFieldException e) { @@ -1493,16 +1435,12 @@ public abstract class GeneratedMessageLite< } } - /** - * Checks that the {@link Extension} is Lite and returns it as a - * {@link GeneratedExtension}. - */ + /** Checks that the {@link Extension} is Lite and returns it as a {@link GeneratedExtension}. */ private static < - MessageType extends ExtendableMessage, - BuilderType extends ExtendableBuilder, - T> - GeneratedExtension checkIsLite( - ExtensionLite extension) { + MessageType extends ExtendableMessage, + BuilderType extends ExtendableBuilder, + T> + GeneratedExtension checkIsLite(ExtensionLite extension) { if (!extension.isLite()) { throw new IllegalArgumentException("Expected a lite extension."); } @@ -1512,8 +1450,8 @@ public abstract class GeneratedMessageLite< /** * A static helper method for checking if a message is initialized, optionally memoizing. - *

- * For use by generated code only. + * + *

For use by generated code only. */ protected static final > boolean isInitialized( T message, boolean shouldMemoize) { @@ -1601,8 +1539,8 @@ public abstract class GeneratedMessageLite< /** * A {@link Parser} implementation that delegates to the default instance. - *

- * For use by generated code only. + * + *

For use by generated code only. */ protected static class DefaultInstanceBasedParser> extends AbstractParser { @@ -1632,7 +1570,7 @@ public abstract class GeneratedMessageLite< // TODO(dweis): Should this verify that the last tag was 0? static > T parsePartialFrom( T instance, CodedInputStream input, ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { + throws InvalidProtocolBufferException { @SuppressWarnings("unchecked") // Guaranteed by protoc T result = (T) instance.dynamicMethod(MethodToInvoke.NEW_MUTABLE_INSTANCE); try { @@ -1689,9 +1627,7 @@ public abstract class GeneratedMessageLite< } protected static > T parsePartialFrom( - T defaultInstance, - CodedInputStream input) - throws InvalidProtocolBufferException { + T defaultInstance, CodedInputStream input) throws InvalidProtocolBufferException { return parsePartialFrom(defaultInstance, input, ExtensionRegistryLite.getEmptyRegistry()); } @@ -1704,7 +1640,8 @@ public abstract class GeneratedMessageLite< private static > T checkMessageInitialized(T message) throws InvalidProtocolBufferException { if (message != null && !message.isInitialized()) { - throw message.newUninitializedMessageException() + throw message + .newUninitializedMessageException() .asInvalidProtocolBufferException() .setUnfinishedMessage(message); } @@ -1727,8 +1664,7 @@ public abstract class GeneratedMessageLite< // Validates last tag. protected static > T parseFrom( - T defaultInstance, ByteString data) - throws InvalidProtocolBufferException { + T defaultInstance, ByteString data) throws InvalidProtocolBufferException { return checkMessageInitialized( parseFrom(defaultInstance, data, ExtensionRegistryLite.getEmptyRegistry())); } @@ -1782,8 +1718,7 @@ public abstract class GeneratedMessageLite< // Validates last tag. protected static > T parseFrom( - T defaultInstance, byte[] data) - throws InvalidProtocolBufferException { + T defaultInstance, byte[] data) throws InvalidProtocolBufferException { return checkMessageInitialized(parsePartialFrom(defaultInstance, data)); } @@ -1796,10 +1731,11 @@ public abstract class GeneratedMessageLite< // Does not validate last tag. protected static > T parseFrom( - T defaultInstance, InputStream input) - throws InvalidProtocolBufferException { + T defaultInstance, InputStream input) throws InvalidProtocolBufferException { return checkMessageInitialized( - parsePartialFrom(defaultInstance, CodedInputStream.newInstance(input), + parsePartialFrom( + defaultInstance, + CodedInputStream.newInstance(input), ExtensionRegistryLite.getEmptyRegistry())); } @@ -1813,8 +1749,7 @@ public abstract class GeneratedMessageLite< // Does not validate last tag. protected static > T parseFrom( - T defaultInstance, CodedInputStream input) - throws InvalidProtocolBufferException { + T defaultInstance, CodedInputStream input) throws InvalidProtocolBufferException { return parseFrom(defaultInstance, input, ExtensionRegistryLite.getEmptyRegistry()); } @@ -1822,17 +1757,15 @@ public abstract class GeneratedMessageLite< protected static > T parseFrom( T defaultInstance, CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { - return checkMessageInitialized( - parsePartialFrom(defaultInstance, input, extensionRegistry)); + return checkMessageInitialized(parsePartialFrom(defaultInstance, input, extensionRegistry)); } // Validates last tag. protected static > T parseDelimitedFrom( - T defaultInstance, InputStream input) - throws InvalidProtocolBufferException { + T defaultInstance, InputStream input) throws InvalidProtocolBufferException { return checkMessageInitialized( - parsePartialDelimitedFrom(defaultInstance, input, - ExtensionRegistryLite.getEmptyRegistry())); + parsePartialDelimitedFrom( + defaultInstance, input, ExtensionRegistryLite.getEmptyRegistry())); } // Validates last tag. @@ -1844,9 +1777,7 @@ public abstract class GeneratedMessageLite< } private static > T parsePartialDelimitedFrom( - T defaultInstance, - InputStream input, - ExtensionRegistryLite extensionRegistry) + T defaultInstance, InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { int size; try { @@ -1878,44 +1809,62 @@ public abstract class GeneratedMessageLite< */ protected interface Visitor { boolean visitBoolean(boolean minePresent, boolean mine, boolean otherPresent, boolean other); + int visitInt(boolean minePresent, int mine, boolean otherPresent, int other); + double visitDouble(boolean minePresent, double mine, boolean otherPresent, double other); + float visitFloat(boolean minePresent, float mine, boolean otherPresent, float other); + long visitLong(boolean minePresent, long mine, boolean otherPresent, long other); + String visitString(boolean minePresent, String mine, boolean otherPresent, String other); + ByteString visitByteString( boolean minePresent, ByteString mine, boolean otherPresent, ByteString other); Object visitOneofBoolean(boolean minePresent, Object mine, Object other); + Object visitOneofInt(boolean minePresent, Object mine, Object other); + Object visitOneofDouble(boolean minePresent, Object mine, Object other); + Object visitOneofFloat(boolean minePresent, Object mine, Object other); + Object visitOneofLong(boolean minePresent, Object mine, Object other); + Object visitOneofString(boolean minePresent, Object mine, Object other); + Object visitOneofByteString(boolean minePresent, Object mine, Object other); + Object visitOneofMessage(boolean minePresent, Object mine, Object other); + void visitOneofNotSet(boolean minePresent); - /** - * Message fields use null sentinals. - */ + /** Message fields use null sentinals. */ T visitMessage(T mine, T other); ProtobufList visitList(ProtobufList mine, ProtobufList other); + BooleanList visitBooleanList(BooleanList mine, BooleanList other); + IntList visitIntList(IntList mine, IntList other); + DoubleList visitDoubleList(DoubleList mine, DoubleList other); + FloatList visitFloatList(FloatList mine, FloatList other); + LongList visitLongList(LongList mine, LongList other); + FieldSet visitExtensions( FieldSet mine, FieldSet other); + UnknownFieldSetLite visitUnknownFields(UnknownFieldSetLite mine, UnknownFieldSetLite other); + MapFieldLite visitMap(MapFieldLite mine, MapFieldLite other); } - /** - * Implements equals. Throws a {@link NotEqualsException} when not equal. - */ + /** Implements equals. Throws a {@link NotEqualsException} when not equal. */ static class EqualsVisitor implements Visitor { static final class NotEqualsException extends RuntimeException {} @@ -2122,8 +2071,7 @@ public abstract class GeneratedMessageLite< @Override public FieldSet visitExtensions( - FieldSet mine, - FieldSet other) { + FieldSet mine, FieldSet other) { if (!mine.equals(other)) { throw NOT_EQUALS; } @@ -2132,8 +2080,7 @@ public abstract class GeneratedMessageLite< @Override public UnknownFieldSetLite visitUnknownFields( - UnknownFieldSetLite mine, - UnknownFieldSetLite other) { + UnknownFieldSetLite mine, UnknownFieldSetLite other) { if (!mine.equals(other)) { throw NOT_EQUALS; } @@ -2149,9 +2096,7 @@ public abstract class GeneratedMessageLite< } } - /** - * Implements hashCode by accumulating state. - */ + /** Implements hashCode by accumulating state. */ static class HashCodeVisitor implements Visitor { // The caller must ensure that the visitor is invoked parameterized with this and this such that @@ -2314,16 +2259,14 @@ public abstract class GeneratedMessageLite< @Override public FieldSet visitExtensions( - FieldSet mine, - FieldSet other) { + FieldSet mine, FieldSet other) { hashCode = (53 * hashCode) + mine.hashCode(); return mine; } @Override public UnknownFieldSetLite visitUnknownFields( - UnknownFieldSetLite mine, - UnknownFieldSetLite other) { + UnknownFieldSetLite mine, UnknownFieldSetLite other) { hashCode = (53 * hashCode) + mine.hashCode(); return mine; } @@ -2335,9 +2278,7 @@ public abstract class GeneratedMessageLite< } } - /** - * Implements field merging semantics over the visitor interface. - */ + /** Implements field merging semantics over the visitor interface. */ protected static class MergeFromVisitor implements Visitor { public static final MergeFromVisitor INSTANCE = new MergeFromVisitor(); @@ -2527,8 +2468,7 @@ public abstract class GeneratedMessageLite< @Override public FieldSet visitExtensions( - FieldSet mine, - FieldSet other) { + FieldSet mine, FieldSet other) { if (mine.isImmutable()) { mine = mine.clone(); } @@ -2538,10 +2478,10 @@ public abstract class GeneratedMessageLite< @Override public UnknownFieldSetLite visitUnknownFields( - UnknownFieldSetLite mine, - UnknownFieldSetLite other) { + UnknownFieldSetLite mine, UnknownFieldSetLite other) { return other == UnknownFieldSetLite.getDefaultInstance() - ? mine : UnknownFieldSetLite.mutableCopyOf(mine, other); + ? mine + : UnknownFieldSetLite.mutableCopyOf(mine, other); } @Override diff --git a/java/core/src/main/java/com/google/protobuf/IntArrayList.java b/java/core/src/main/java/com/google/protobuf/IntArrayList.java index 4993eea746..c9b12c4266 100644 --- a/java/core/src/main/java/com/google/protobuf/IntArrayList.java +++ b/java/core/src/main/java/com/google/protobuf/IntArrayList.java @@ -42,11 +42,11 @@ import java.util.RandomAccess; * * @author dweis@google.com (Daniel Weis) */ -final class IntArrayList - extends AbstractProtobufList +final class IntArrayList extends AbstractProtobufList implements IntList, RandomAccess, PrimitiveNonBoxingCollection { private static final IntArrayList EMPTY_LIST = new IntArrayList(); + static { EMPTY_LIST.makeImmutable(); } @@ -55,9 +55,7 @@ final class IntArrayList return EMPTY_LIST; } - /** - * The backing store for the list. - */ + /** The backing store for the list. */ private int[] array; /** @@ -66,16 +64,13 @@ final class IntArrayList */ private int size; - /** - * Constructs a new mutable {@code IntArrayList} with default capacity. - */ + /** Constructs a new mutable {@code IntArrayList} with default capacity. */ IntArrayList() { this(new int[DEFAULT_CAPACITY], 0); } /** - * Constructs a new mutable {@code IntArrayList} - * containing the same elements as {@code other}. + * Constructs a new mutable {@code IntArrayList} containing the same elements as {@code other}. */ private IntArrayList(int[] other, int size) { array = other; @@ -169,17 +164,13 @@ final class IntArrayList addInt(index, element); } - /** - * Like {@link #add(Integer)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #add(Integer)} but more efficient in that it doesn't box the element. */ @Override public void addInt(int element) { addInt(size, element); } - /** - * Like {@link #add(int, Integer)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #add(int, Integer)} but more efficient in that it doesn't box the element. */ private void addInt(int index, int element) { ensureIsMutable(); if (index < 0 || index > size) { diff --git a/java/core/src/main/java/com/google/protobuf/Internal.java b/java/core/src/main/java/com/google/protobuf/Internal.java index 878573d565..713ccb583c 100644 --- a/java/core/src/main/java/com/google/protobuf/Internal.java +++ b/java/core/src/main/java/com/google/protobuf/Internal.java @@ -45,10 +45,9 @@ import java.util.RandomAccess; import java.util.Set; /** - * The classes contained within are used internally by the Protocol Buffer - * library and generated message implementations. They are public only because - * those generated messages do not reside in the {@code protobuf} package. - * Others should not use this class directly. + * The classes contained within are used internally by the Protocol Buffer library and generated + * message implementations. They are public only because those generated messages do not reside in + * the {@code protobuf} package. Others should not use this class directly. * * @author kenton@google.com (Kenton Varda) */ @@ -59,9 +58,7 @@ public final class Internal { static final Charset UTF_8 = Charset.forName("UTF-8"); static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); - /** - * Throws an appropriate {@link NullPointerException} if the given objects is {@code null}. - */ + /** Throws an appropriate {@link NullPointerException} if the given objects is {@code null}. */ static T checkNotNull(T obj) { if (obj == null) { throw new NullPointerException(); @@ -69,9 +66,7 @@ public final class Internal { return obj; } - /** - * Throws an appropriate {@link NullPointerException} if the given objects is {@code null}. - */ + /** Throws an appropriate {@link NullPointerException} if the given objects is {@code null}. */ static T checkNotNull(T obj, String message) { if (obj == null) { throw new NullPointerException(message); @@ -80,73 +75,63 @@ public final class Internal { } /** - * Helper called by generated code to construct default values for string - * fields. - *

- * The protocol compiler does not actually contain a UTF-8 decoder -- it - * just pushes UTF-8-encoded text around without touching it. The one place - * where this presents a problem is when generating Java string literals. - * Unicode characters in the string literal would normally need to be encoded - * using a Unicode escape sequence, which would require decoding them. - * To get around this, protoc instead embeds the UTF-8 bytes into the - * generated code and leaves it to the runtime library to decode them. - *

- * It gets worse, though. If protoc just generated a byte array, like: - * new byte[] {0x12, 0x34, 0x56, 0x78} - * Java actually generates *code* which allocates an array and then fills - * in each value. This is much less efficient than just embedding the bytes - * directly into the bytecode. To get around this, we need another - * work-around. String literals are embedded directly, so protoc actually - * generates a string literal corresponding to the bytes. The easiest way - * to do this is to use the ISO-8859-1 character set, which corresponds to - * the first 256 characters of the Unicode range. Protoc can then use - * good old CEscape to generate the string. - *

- * So we have a string literal which represents a set of bytes which - * represents another string. This function -- stringDefaultValue -- - * converts from the generated string to the string we actually want. The - * generated code calls this automatically. + * Helper called by generated code to construct default values for string fields. + * + *

The protocol compiler does not actually contain a UTF-8 decoder -- it just pushes + * UTF-8-encoded text around without touching it. The one place where this presents a problem is + * when generating Java string literals. Unicode characters in the string literal would normally + * need to be encoded using a Unicode escape sequence, which would require decoding them. To get + * around this, protoc instead embeds the UTF-8 bytes into the generated code and leaves it to the + * runtime library to decode them. + * + *

It gets worse, though. If protoc just generated a byte array, like: new byte[] {0x12, 0x34, + * 0x56, 0x78} Java actually generates *code* which allocates an array and then fills in each + * value. This is much less efficient than just embedding the bytes directly into the bytecode. To + * get around this, we need another work-around. String literals are embedded directly, so protoc + * actually generates a string literal corresponding to the bytes. The easiest way to do this is + * to use the ISO-8859-1 character set, which corresponds to the first 256 characters of the + * Unicode range. Protoc can then use good old CEscape to generate the string. + * + *

So we have a string literal which represents a set of bytes which represents another string. + * This function -- stringDefaultValue -- converts from the generated string to the string we + * actually want. The generated code calls this automatically. */ public static String stringDefaultValue(String bytes) { return new String(bytes.getBytes(ISO_8859_1), UTF_8); } /** - * Helper called by generated code to construct default values for bytes - * fields. - *

- * This is a lot like {@link #stringDefaultValue}, but for bytes fields. - * In this case we only need the second of the two hacks -- allowing us to - * embed raw bytes as a string literal with ISO-8859-1 encoding. + * Helper called by generated code to construct default values for bytes fields. + * + *

This is a lot like {@link #stringDefaultValue}, but for bytes fields. In this case we only + * need the second of the two hacks -- allowing us to embed raw bytes as a string literal with + * ISO-8859-1 encoding. */ public static ByteString bytesDefaultValue(String bytes) { return ByteString.copyFrom(bytes.getBytes(ISO_8859_1)); } /** - * Helper called by generated code to construct default values for bytes - * fields. - *

- * This is like {@link #bytesDefaultValue}, but returns a byte array. + * Helper called by generated code to construct default values for bytes fields. + * + *

This is like {@link #bytesDefaultValue}, but returns a byte array. */ public static byte[] byteArrayDefaultValue(String bytes) { return bytes.getBytes(ISO_8859_1); } /** - * Helper called by generated code to construct default values for bytes - * fields. - *

- * This is like {@link #bytesDefaultValue}, but returns a ByteBuffer. + * Helper called by generated code to construct default values for bytes fields. + * + *

This is like {@link #bytesDefaultValue}, but returns a ByteBuffer. */ public static ByteBuffer byteBufferDefaultValue(String bytes) { return ByteBuffer.wrap(byteArrayDefaultValue(bytes)); } /** - * Create a new ByteBuffer and copy all the content of {@code source} - * ByteBuffer to the new ByteBuffer. The new ByteBuffer's limit and - * capacity will be source.capacity(), and its position will be 0. - * Note that the state of {@code source} ByteBuffer won't be changed. + * Create a new ByteBuffer and copy all the content of {@code source} ByteBuffer to the new + * ByteBuffer. The new ByteBuffer's limit and capacity will be source.capacity(), and its position + * will be 0. Note that the state of {@code source} ByteBuffer won't be changed. */ public static ByteBuffer copyByteBuffer(ByteBuffer source) { // Make a duplicate of the source ByteBuffer and read data from the @@ -162,29 +147,27 @@ public final class Internal { } /** - * Helper called by generated code to determine if a byte array is a valid - * UTF-8 encoded string such that the original bytes can be converted to - * a String object and then back to a byte array round tripping the bytes - * without loss. More precisely, returns {@code true} whenever: - *

   {@code
+   * Helper called by generated code to determine if a byte array is a valid UTF-8 encoded string
+   * such that the original bytes can be converted to a String object and then back to a byte array
+   * round tripping the bytes without loss. More precisely, returns {@code true} whenever:
+   *
+   * 
{@code
    * Arrays.equals(byteString.toByteArray(),
    *     new String(byteString.toByteArray(), "UTF-8").getBytes("UTF-8"))
    * }
* - *

This method rejects "overlong" byte sequences, as well as - * 3-byte sequences that would map to a surrogate character, in - * accordance with the restricted definition of UTF-8 introduced in - * Unicode 3.1. Note that the UTF-8 decoder included in Oracle's - * JDK has been modified to also reject "overlong" byte sequences, - * but currently (2011) still accepts 3-byte surrogate character + *

This method rejects "overlong" byte sequences, as well as 3-byte sequences that would map to + * a surrogate character, in accordance with the restricted definition of UTF-8 introduced in + * Unicode 3.1. Note that the UTF-8 decoder included in Oracle's JDK has been modified to also + * reject "overlong" byte sequences, but currently (2011) still accepts 3-byte surrogate character * byte sequences. * *

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

As of 2011-02, this method simply returns the result of {@link - * ByteString#isValidUtf8()}. Calling that method directly is preferred. + *

As of 2011-02, this method simply returns the result of {@link ByteString#isValidUtf8()}. + * Calling that method directly is preferred. * * @param byteString the string to check * @return whether the byte array is round trippable @@ -193,42 +176,36 @@ public final class Internal { return byteString.isValidUtf8(); } - /** - * Like {@link #isValidUtf8(ByteString)} but for byte arrays. - */ + /** Like {@link #isValidUtf8(ByteString)} but for byte arrays. */ public static boolean isValidUtf8(byte[] byteArray) { return Utf8.isValidUtf8(byteArray); } - /** - * Helper method to get the UTF-8 bytes of a string. - */ + /** Helper method to get the UTF-8 bytes of a string. */ public static byte[] toByteArray(String value) { return value.getBytes(UTF_8); } - /** - * Helper method to convert a byte array to a string using UTF-8 encoding. - */ + /** Helper method to convert a byte array to a string using UTF-8 encoding. */ public static String toStringUtf8(byte[] bytes) { return new String(bytes, UTF_8); } /** - * Interface for an enum value or value descriptor, to be used in FieldSet. - * The lite library stores enum values directly in FieldSets but the full - * library stores EnumValueDescriptors in order to better support reflection. + * Interface for an enum value or value descriptor, to be used in FieldSet. The lite library + * stores enum values directly in FieldSets but the full library stores EnumValueDescriptors in + * order to better support reflection. */ public interface EnumLite { int getNumber(); } /** - * Interface for an object which maps integers to {@link EnumLite}s. - * {@link Descriptors.EnumDescriptor} implements this interface by mapping - * numbers to {@link Descriptors.EnumValueDescriptor}s. Additionally, - * every generated enum type has a static method internalGetValueMap() which - * returns an implementation of this type that maps numbers to enum values. + * Interface for an object which maps integers to {@link EnumLite}s. {@link + * Descriptors.EnumDescriptor} implements this interface by mapping numbers to {@link + * Descriptors.EnumValueDescriptor}s. Additionally, every generated enum type has a static method + * internalGetValueMap() which returns an implementation of this type that maps numbers to enum + * values. */ public interface EnumLiteMap { T findValueByNumber(int number); @@ -241,6 +218,7 @@ public final class Internal { /** * Helper method for implementing {@link Message#hashCode()} for longs. + * * @see Long#hashCode() */ public static int hashLong(long n) { @@ -248,8 +226,8 @@ public final class Internal { } /** - * Helper method for implementing {@link Message#hashCode()} for - * booleans. + * Helper method for implementing {@link Message#hashCode()} for booleans. + * * @see Boolean#hashCode() */ public static int hashBoolean(boolean b) { @@ -258,19 +236,16 @@ public final class Internal { /** * Helper method for implementing {@link Message#hashCode()} for enums. - *

- * This is needed because {@link java.lang.Enum#hashCode()} is final, but we - * need to use the field number as the hash code to ensure compatibility - * between statically and dynamically generated enum objects. + * + *

This is needed because {@link java.lang.Enum#hashCode()} is final, but we need to use the + * field number as the hash code to ensure compatibility between statically and dynamically + * generated enum objects. */ public static int hashEnum(EnumLite e) { return e.getNumber(); } - /** - * Helper method for implementing {@link Message#hashCode()} for - * enum lists. - */ + /** Helper method for implementing {@link Message#hashCode()} for enum lists. */ public static int hashEnumList(List list) { int hash = 1; for (EnumLite e : list) { @@ -279,9 +254,7 @@ public final class Internal { return hash; } - /** - * Helper method for implementing {@link Message#equals(Object)} for bytes field. - */ + /** Helper method for implementing {@link Message#equals(Object)} for bytes field. */ public static boolean equals(List a, List b) { if (a.size() != b.size()) return false; for (int i = 0; i < a.size(); ++i) { @@ -292,9 +265,7 @@ public final class Internal { return true; } - /** - * Helper method for implementing {@link Message#hashCode()} for bytes field. - */ + /** Helper method for implementing {@link Message#hashCode()} for bytes field. */ public static int hashCode(List list) { int hash = 1; for (byte[] bytes : list) { @@ -303,9 +274,7 @@ public final class Internal { return hash; } - /** - * Helper method for implementing {@link Message#hashCode()} for bytes field. - */ + /** Helper method for implementing {@link Message#hashCode()} for bytes field. */ public static int hashCode(byte[] bytes) { // The hash code for a byte array should be the same as the hash code for a // ByteString with the same content. This is to ensure that the generated @@ -313,10 +282,8 @@ public final class Internal { // based hashCode() method. return Internal.hashCode(bytes, 0, bytes.length); } - - /** - * Helper method for implementing {@link LiteralByteString#hashCode()}. - */ + + /** Helper method for implementing {@link LiteralByteString#hashCode()}. */ static int hashCode(byte[] bytes, int offset, int length) { // The hash code for a byte array should be the same as the hash code for a // ByteString with the same content. This is to ensure that the generated @@ -326,20 +293,15 @@ public final class Internal { return h == 0 ? 1 : h; } - /** - * Helper method for continuously hashing bytes. - */ + /** Helper method for continuously hashing bytes. */ static int partialHash(int h, byte[] bytes, int offset, int length) { for (int i = offset; i < offset + length; i++) { h = h * 31 + bytes[i]; } return h; } - - /** - * Helper method for implementing {@link Message#equals(Object)} for bytes - * field. - */ + + /** Helper method for implementing {@link Message#equals(Object)} for bytes field. */ public static boolean equalsByteBuffer(ByteBuffer a, ByteBuffer b) { if (a.capacity() != b.capacity()) { return false; @@ -349,12 +311,8 @@ public final class Internal { return a.duplicate().clear().equals(b.duplicate().clear()); } - /** - * Helper method for implementing {@link Message#equals(Object)} for bytes - * field. - */ - public static boolean equalsByteBuffer( - List a, List b) { + /** Helper method for implementing {@link Message#equals(Object)} for bytes field. */ + public static boolean equalsByteBuffer(List a, List b) { if (a.size() != b.size()) { return false; } @@ -366,10 +324,7 @@ public final class Internal { return true; } - /** - * Helper method for implementing {@link Message#hashCode()} for bytes - * field. - */ + /** Helper method for implementing {@link Message#hashCode()} for bytes field. */ public static int hashCodeByteBuffer(List list) { int hash = 1; for (ByteBuffer bytes : list) { @@ -380,10 +335,7 @@ public final class Internal { private static final int DEFAULT_BUFFER_SIZE = 4096; - /** - * Helper method for implementing {@link Message#hashCode()} for bytes - * field. - */ + /** Helper method for implementing {@link Message#hashCode()} for bytes field. */ public static int hashCodeByteBuffer(ByteBuffer bytes) { if (bytes.hasArray()) { // Fast path. @@ -392,15 +344,15 @@ public final class Internal { } else { // Read the data into a temporary byte array before calculating the // hash value. - final int bufferSize = bytes.capacity() > DEFAULT_BUFFER_SIZE - ? DEFAULT_BUFFER_SIZE : bytes.capacity(); + final int bufferSize = + bytes.capacity() > DEFAULT_BUFFER_SIZE ? DEFAULT_BUFFER_SIZE : bytes.capacity(); final byte[] buffer = new byte[bufferSize]; final ByteBuffer duplicated = bytes.duplicate(); duplicated.clear(); int h = bytes.capacity(); while (duplicated.remaining() > 0) { - final int length = duplicated.remaining() <= bufferSize ? - duplicated.remaining() : bufferSize; + final int length = + duplicated.remaining() <= bufferSize ? duplicated.remaining() : bufferSize; duplicated.get(buffer, 0, length); h = partialHash(h, buffer, 0, length); } @@ -414,8 +366,7 @@ public final class Internal { Method method = clazz.getMethod("getDefaultInstance"); return (T) method.invoke(method); } catch (Exception e) { - throw new RuntimeException( - "Failed to get default instance for " + clazz, e); + throw new RuntimeException("Failed to get default instance for " + clazz, e); } } @@ -423,11 +374,8 @@ public final class Internal { /** An empty byte array constant used in generated code. */ public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; - /** - * An empty byte array constant used in generated code. - */ - public static final ByteBuffer EMPTY_BYTE_BUFFER = - ByteBuffer.wrap(EMPTY_BYTE_ARRAY); + /** An empty byte array constant used in generated code. */ + public static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.wrap(EMPTY_BYTE_ARRAY); /** An empty coded input stream constant used in generated code. */ public static final CodedInputStream EMPTY_CODED_INPUT_STREAM = @@ -442,12 +390,10 @@ public final class Internal { /** * Provides an immutable view of {@code List} around a {@code List}. * - * Protobuf internal. Used in protobuf generated code only. + *

Protobuf internal. Used in protobuf generated code only. */ public static class ListAdapter extends AbstractList { - /** - * Convert individual elements of the List from F to T. - */ + /** Convert individual elements of the List from F to T. */ public interface Converter { T convert(F from); } @@ -471,16 +417,12 @@ public final class Internal { } } - /** - * Wrap around a {@code Map} and provide a {@code Map} - * interface. - */ + /** Wrap around a {@code Map} and provide a {@code Map} interface. */ public static class MapAdapter extends AbstractMap { - /** - * An interface used to convert between two types. - */ + /** An interface used to convert between two types. */ public interface Converter { B doForward(A object); + A doBackward(B object); } @@ -503,8 +445,7 @@ public final class Internal { private final Map realMap; private final Converter valueConverter; - public MapAdapter(Map realMap, - Converter valueConverter) { + public MapAdapter(Map realMap, Converter valueConverter) { this.realMap = realMap; this.valueConverter = valueConverter; } @@ -535,6 +476,7 @@ public final class Internal { private class SetAdapter extends AbstractSet> { private final Set> realSet; + public SetAdapter(Set> realSet) { this.realSet = realSet; } @@ -553,8 +495,7 @@ public final class Internal { private class IteratorAdapter implements Iterator> { private final Iterator> realIterator; - public IteratorAdapter( - Iterator> realIterator) { + public IteratorAdapter(Iterator> realIterator) { this.realIterator = realIterator; } @@ -593,8 +534,7 @@ public final class Internal { @Override public V setValue(V value) { - RealValue oldValue = realEntry.setValue( - valueConverter.doBackward(value)); + RealValue oldValue = realEntry.setValue(valueConverter.doBackward(value)); if (oldValue == null) { return null; } @@ -606,14 +546,14 @@ public final class Internal { /** * Extends {@link List} to add the capability to make the list immutable and inspect if it is * modifiable. - *

- * All implementations must support efficient random access. + * + *

All implementations must support efficient random access. */ public static interface ProtobufList extends List, RandomAccess { /** - * Makes this list immutable. All subsequent modifications will throw an - * {@link UnsupportedOperationException}. + * Makes this list immutable. All subsequent modifications will throw an {@link + * UnsupportedOperationException}. */ void makeImmutable(); @@ -622,9 +562,7 @@ public final class Internal { */ boolean isModifiable(); - /** - * Returns a mutable clone of this list with the specified capacity. - */ + /** Returns a mutable clone of this list with the specified capacity. */ ProtobufList mutableCopyWithCapacity(int capacity); } @@ -634,24 +572,16 @@ public final class Internal { */ public static interface IntList extends ProtobufList { - /** - * Like {@link #get(int)} but more efficient in that it doesn't box the returned value. - */ + /** Like {@link #get(int)} but more efficient in that it doesn't box the returned value. */ int getInt(int index); - /** - * Like {@link #add(Object)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #add(Object)} but more efficient in that it doesn't box the element. */ void addInt(int element); - /** - * Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */ int setInt(int index, int element); - /** - * Returns a mutable clone of this list with the specified capacity. - */ + /** Returns a mutable clone of this list with the specified capacity. */ @Override IntList mutableCopyWithCapacity(int capacity); } @@ -662,52 +592,36 @@ public final class Internal { */ public static interface BooleanList extends ProtobufList { - /** - * Like {@link #get(int)} but more efficient in that it doesn't box the returned value. - */ + /** Like {@link #get(int)} but more efficient in that it doesn't box the returned value. */ boolean getBoolean(int index); - /** - * Like {@link #add(Object)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #add(Object)} but more efficient in that it doesn't box the element. */ void addBoolean(boolean element); - /** - * Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */ boolean setBoolean(int index, boolean element); - /** - * Returns a mutable clone of this list with the specified capacity. - */ + /** Returns a mutable clone of this list with the specified capacity. */ @Override BooleanList mutableCopyWithCapacity(int capacity); } /** - * A {@link java.util.List} implementation that avoids boxing the elements into Longs if - * possible. Does not support null elements. + * A {@link java.util.List} implementation that avoids boxing the elements into Longs if possible. + * Does not support null elements. */ public static interface LongList extends ProtobufList { - /** - * Like {@link #get(int)} but more efficient in that it doesn't box the returned value. - */ + /** Like {@link #get(int)} but more efficient in that it doesn't box the returned value. */ long getLong(int index); - /** - * Like {@link #add(Object)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #add(Object)} but more efficient in that it doesn't box the element. */ void addLong(long element); - /** - * Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */ long setLong(int index, long element); - /** - * Returns a mutable clone of this list with the specified capacity. - */ + /** Returns a mutable clone of this list with the specified capacity. */ @Override LongList mutableCopyWithCapacity(int capacity); } @@ -718,24 +632,16 @@ public final class Internal { */ public static interface DoubleList extends ProtobufList { - /** - * Like {@link #get(int)} but more efficient in that it doesn't box the returned value. - */ + /** Like {@link #get(int)} but more efficient in that it doesn't box the returned value. */ double getDouble(int index); - /** - * Like {@link #add(Object)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #add(Object)} but more efficient in that it doesn't box the element. */ void addDouble(double element); - /** - * Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */ double setDouble(int index, double element); - /** - * Returns a mutable clone of this list with the specified capacity. - */ + /** Returns a mutable clone of this list with the specified capacity. */ @Override DoubleList mutableCopyWithCapacity(int capacity); } @@ -746,24 +652,16 @@ public final class Internal { */ public static interface FloatList extends ProtobufList { - /** - * Like {@link #get(int)} but more efficient in that it doesn't box the returned value. - */ + /** Like {@link #get(int)} but more efficient in that it doesn't box the returned value. */ float getFloat(int index); - /** - * Like {@link #add(Object)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #add(Object)} but more efficient in that it doesn't box the element. */ void addFloat(float element); - /** - * Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */ float setFloat(int index, float element); - /** - * Returns a mutable clone of this list with the specified capacity. - */ + /** Returns a mutable clone of this list with the specified capacity. */ @Override FloatList mutableCopyWithCapacity(int capacity); } diff --git a/java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java b/java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java index 510c6aac74..22f31bbc0b 100644 --- a/java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java +++ b/java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java @@ -33,8 +33,8 @@ package com.google.protobuf; import java.io.IOException; /** - * Thrown when a protocol message being parsed is invalid in some way, - * e.g. it contains a malformed varint or a negative byte length. + * Thrown when a protocol message being parsed is invalid in some way, e.g. it contains a malformed + * varint or a negative byte length. * * @author kenton@google.com Kenton Varda */ @@ -55,28 +55,26 @@ public class InvalidProtocolBufferException extends IOException { } /** - * Attaches an unfinished message to the exception to support best-effort - * parsing in {@code Parser} interface. + * Attaches an unfinished message to the exception to support best-effort parsing in {@code + * Parser} interface. * * @return this */ - public InvalidProtocolBufferException setUnfinishedMessage( - MessageLite unfinishedMessage) { + public InvalidProtocolBufferException setUnfinishedMessage(MessageLite unfinishedMessage) { this.unfinishedMessage = unfinishedMessage; return this; } /** - * Returns the unfinished message attached to the exception, or null if - * no message is attached. + * Returns the unfinished message attached to the exception, or null if no message is attached. */ public MessageLite getUnfinishedMessage() { return unfinishedMessage; } /** - * Unwraps the underlying {@link IOException} if this exception was caused by an I/O - * problem. Otherwise, returns {@code this}. + * Unwraps the underlying {@link IOException} if this exception was caused by an I/O problem. + * Otherwise, returns {@code this}. */ public IOException unwrapIOException() { return getCause() instanceof IOException ? (IOException) getCause() : this; @@ -84,41 +82,36 @@ public class InvalidProtocolBufferException extends IOException { static InvalidProtocolBufferException truncatedMessage() { return new InvalidProtocolBufferException( - "While parsing a protocol message, the input ended unexpectedly " + - "in the middle of a field. This could mean either that the " + - "input has been truncated or that an embedded message " + - "misreported its own length."); + "While parsing a protocol message, the input ended unexpectedly " + + "in the middle of a field. This could mean either that the " + + "input has been truncated or that an embedded message " + + "misreported its own length."); } static InvalidProtocolBufferException negativeSize() { return new InvalidProtocolBufferException( - "CodedInputStream encountered an embedded string or message " + - "which claimed to have negative size."); + "CodedInputStream encountered an embedded string or message " + + "which claimed to have negative size."); } static InvalidProtocolBufferException malformedVarint() { - return new InvalidProtocolBufferException( - "CodedInputStream encountered a malformed varint."); + return new InvalidProtocolBufferException("CodedInputStream encountered a malformed varint."); } static InvalidProtocolBufferException invalidTag() { - return new InvalidProtocolBufferException( - "Protocol message contained an invalid tag (zero)."); + return new InvalidProtocolBufferException("Protocol message contained an invalid tag (zero)."); } static InvalidProtocolBufferException invalidEndTag() { return new InvalidProtocolBufferException( - "Protocol message end-group tag did not match expected tag."); + "Protocol message end-group tag did not match expected tag."); } static InvalidWireTypeException invalidWireType() { - return new InvalidWireTypeException( - "Protocol message tag had invalid wire type."); + return new InvalidWireTypeException("Protocol message tag had invalid wire type."); } - /** - * Exception indicating that and unexpected wire type was encountered for a field. - */ + /** Exception indicating that and unexpected wire type was encountered for a field. */ @ExperimentalApi public static class InvalidWireTypeException extends InvalidProtocolBufferException { private static final long serialVersionUID = 3283890091615336259L; @@ -130,14 +123,14 @@ public class InvalidProtocolBufferException extends IOException { static InvalidProtocolBufferException recursionLimitExceeded() { return new InvalidProtocolBufferException( - "Protocol message had too many levels of nesting. May be malicious. " + - "Use CodedInputStream.setRecursionLimit() to increase the depth limit."); + "Protocol message had too many levels of nesting. May be malicious. " + + "Use CodedInputStream.setRecursionLimit() to increase the depth limit."); } static InvalidProtocolBufferException sizeLimitExceeded() { return new InvalidProtocolBufferException( - "Protocol message was too large. May be malicious. " + - "Use CodedInputStream.setSizeLimit() to increase the size limit."); + "Protocol message was too large. May be malicious. " + + "Use CodedInputStream.setSizeLimit() to increase the size limit."); } static InvalidProtocolBufferException parseFailure() { diff --git a/java/core/src/main/java/com/google/protobuf/LazyField.java b/java/core/src/main/java/com/google/protobuf/LazyField.java index 98e13ca199..891171d7c8 100644 --- a/java/core/src/main/java/com/google/protobuf/LazyField.java +++ b/java/core/src/main/java/com/google/protobuf/LazyField.java @@ -34,12 +34,12 @@ import java.util.Iterator; import java.util.Map.Entry; /** - * LazyField encapsulates the logic of lazily parsing message fields. It stores - * the message in a ByteString initially and then parse it on-demand. + * LazyField encapsulates the logic of lazily parsing message fields. It stores the message in a + * ByteString initially and then parse it on-demand. * - * Most of key methods are implemented in {@link LazyFieldLite} but this class - * can contain default instance of the message to provide {@code hashCode()}, - * {@code euqals()} and {@code toString()}. + *

Most of key methods are implemented in {@link LazyFieldLite} but this class can contain + * default instance of the message to provide {@code hashCode()}, {@code euqals()} and {@code + * toString()}. * * @author xiangl@google.com (Xiang Li) */ @@ -51,8 +51,8 @@ public class LazyField extends LazyFieldLite { */ private final MessageLite defaultInstance; - public LazyField(MessageLite defaultInstance, - ExtensionRegistryLite extensionRegistry, ByteString bytes) { + public LazyField( + MessageLite defaultInstance, ExtensionRegistryLite extensionRegistry, ByteString bytes) { super(extensionRegistry, bytes); this.defaultInstance = defaultInstance; @@ -85,8 +85,8 @@ public class LazyField extends LazyFieldLite { // ==================================================== /** - * LazyEntry and LazyIterator are used to encapsulate the LazyField, when - * users iterate all fields from FieldSet. + * LazyEntry and LazyIterator are used to encapsulate the LazyField, when users iterate all fields + * from FieldSet. */ static class LazyEntry implements Entry { private Entry entry; @@ -118,7 +118,7 @@ public class LazyField extends LazyFieldLite { if (!(value instanceof MessageLite)) { throw new IllegalArgumentException( "LazyField now only used for MessageSet, " - + "and the value of MessageSet must be an instance of MessageLite"); + + "and the value of MessageSet must be an instance of MessageLite"); } return entry.getValue().setValue((MessageLite) value); } diff --git a/java/core/src/main/java/com/google/protobuf/LazyFieldLite.java b/java/core/src/main/java/com/google/protobuf/LazyFieldLite.java index 49ecfc0be6..5651e131b3 100644 --- a/java/core/src/main/java/com/google/protobuf/LazyFieldLite.java +++ b/java/core/src/main/java/com/google/protobuf/LazyFieldLite.java @@ -33,23 +33,23 @@ package com.google.protobuf; import java.io.IOException; /** - * LazyFieldLite encapsulates the logic of lazily parsing message fields. It stores - * the message in a ByteString initially and then parses it on-demand. + * LazyFieldLite encapsulates the logic of lazily parsing message fields. It stores the message in a + * ByteString initially and then parses it on-demand. * - * LazyFieldLite is thread-compatible: concurrent reads are safe once the proto that this + *

LazyFieldLite is thread-compatible: concurrent reads are safe once the proto that this * LazyFieldLite is a part of is no longer being mutated by its Builder. However, explicit * synchronization is needed under read/write situations. * - * When a LazyFieldLite is used in the context of a MessageLite object, its behavior is considered - * to be immutable and none of the setter methods in its API are expected to be invoked. All of the - * getters are expected to be thread-safe. When used in the context of a MessageLite.Builder, - * setters can be invoked, but there is no guarantee of thread safety. - * - * TODO(yatin,dweis): Consider splitting this class's functionality and put the mutable methods + *

When a LazyFieldLite is used in the context of a MessageLite object, its behavior is + * considered to be immutable and none of the setter methods in its API are expected to be invoked. + * All of the getters are expected to be thread-safe. When used in the context of a + * MessageLite.Builder, setters can be invoked, but there is no guarantee of thread safety. + * + *

TODO(yatin,dweis): Consider splitting this class's functionality and put the mutable methods * into a separate builder class to allow us to give stronger compile-time guarantees. * - * This class is internal implementation detail of the protobuf library, so you don't need to use it - * directly. + *

This class is internal implementation detail of the protobuf library, so you don't need to use + * it directly. * * @author xiangl@google.com (Xiang Li) */ @@ -57,23 +57,27 @@ public class LazyFieldLite { private static final ExtensionRegistryLite EMPTY_REGISTRY = ExtensionRegistryLite.getEmptyRegistry(); - /** + /* * The value associated with the LazyFieldLite object is stored in one or more of the following * three fields (delayedBytes, value, memoizedBytes). They should together be interpreted as * follows. + * * 1) delayedBytes can be non-null, while value and memoizedBytes is null. The object will be in - * this state while the value for the object has not yet been parsed. + * this state while the value for the object has not yet been parsed. + * * 2) Both delayedBytes and value are non-null. The object transitions to this state as soon as - * some caller needs to access the value (by invoking getValue()). + * some caller needs to access the value (by invoking getValue()). + * * 3) memoizedBytes is merely an optimization for calls to LazyFieldLite.toByteString() to avoid - * recomputing the ByteString representation on each call. Instead, when the value is parsed - * from delayedBytes, we will also assign the contents of delayedBytes to memoizedBytes (since - * that is the ByteString representation of value). + * recomputing the ByteString representation on each call. Instead, when the value is parsed from + * delayedBytes, we will also assign the contents of delayedBytes to memoizedBytes (since that is + * the ByteString representation of value). + * * 4) Finally, if the LazyFieldLite was created directly with a parsed MessageLite value, then - * delayedBytes will be null, and memoizedBytes will be initialized only upon the first call to - * LazyFieldLite.toByteString(). + * delayedBytes will be null, and memoizedBytes will be initialized only upon the first call to + * LazyFieldLite.toByteString(). * - * Given the above conditions, any caller that needs a serialized representation of this object + *

Given the above conditions, any caller that needs a serialized representation of this object * must first check if the memoizedBytes or delayedBytes ByteString is non-null and use it * directly; if both of those are null, it can look at the parsed value field. Similarly, any * caller that needs a parsed value must first check if the value field is already non-null, if @@ -84,16 +88,16 @@ public class LazyFieldLite { * A delayed-parsed version of the contents of this field. When this field is non-null, then the * "value" field is allowed to be null until the time that the value needs to be read. * - * When delayedBytes is non-null then {@code extensionRegistry} is required to also be non-null. - * {@code value} and {@code memoizedBytes} will be initialized lazily. + *

When delayedBytes is non-null then {@code extensionRegistry} is required to also be + * non-null. {@code value} and {@code memoizedBytes} will be initialized lazily. */ private ByteString delayedBytes; /** * An {@code ExtensionRegistryLite} for parsing bytes. It is non-null on a best-effort basis. It - * is only guaranteed to be non-null if this message was initialized using bytes and an - * {@code ExtensionRegistry}. If it directly had a value set then it will be null, unless it has - * been merged with another {@code LazyFieldLite} that had an {@code ExtensionRegistry}. + * is only guaranteed to be non-null if this message was initialized using bytes and an {@code + * ExtensionRegistry}. If it directly had a value set then it will be null, unless it has been + * merged with another {@code LazyFieldLite} that had an {@code ExtensionRegistry}. */ private ExtensionRegistryLite extensionRegistry; @@ -105,25 +109,20 @@ public class LazyFieldLite { /** * The memoized bytes for {@code value}. This is an optimization for the toByteString() method to - * not have to recompute its return-value on each invocation. - * TODO(yatin): Figure out whether this optimization is actually necessary. + * not have to recompute its return-value on each invocation. TODO(yatin): Figure out whether this + * optimization is actually necessary. */ private volatile ByteString memoizedBytes; - /** - * Constructs a LazyFieldLite with bytes that will be parsed lazily. - */ + /** Constructs a LazyFieldLite with bytes that will be parsed lazily. */ public LazyFieldLite(ExtensionRegistryLite extensionRegistry, ByteString bytes) { checkArguments(extensionRegistry, bytes); this.extensionRegistry = extensionRegistry; this.delayedBytes = bytes; } - /** - * Constructs a LazyFieldLite with no contents, and no ability to parse extensions. - */ - public LazyFieldLite() { - } + /** Constructs a LazyFieldLite with no contents, and no ability to parse extensions. */ + public LazyFieldLite() {} /** * Constructs a LazyFieldLite instance with a value. The LazyFieldLite may not be able to parse @@ -140,13 +139,13 @@ public class LazyFieldLite { if (this == o) { return true; } - + if (!(o instanceof LazyFieldLite)) { return false; } LazyFieldLite other = (LazyFieldLite) o; - + // Lazy fields do not work well with equals... If both are delayedBytes, we do not have a // mechanism to deserialize them so we rely on bytes equality. Otherwise we coerce into an // actual message (if necessary) and call equals on the message itself. This implies that two @@ -163,7 +162,7 @@ public class LazyFieldLite { return getValue(value2.getDefaultInstanceForType()).equals(value2); } } - + @Override public int hashCode() { // We can't provide a memoizable hash code for lazy fields. The byte strings may have different @@ -171,7 +170,7 @@ public class LazyFieldLite { // a message here if we were not already holding a value. return 1; } - + /** * Determines whether this LazyFieldLite instance represents the default instance of this type. */ @@ -183,8 +182,8 @@ public class LazyFieldLite { /** * Clears the value state of this instance. * - *

LazyField is not thread-safe for write access. Synchronizations are needed - * under read/write situations. + *

LazyField is not thread-safe for write access. Synchronizations are needed under read/write + * situations. */ public void clear() { // Don't clear the ExtensionRegistry. It might prove useful later on when merging in another @@ -198,8 +197,8 @@ public class LazyFieldLite { /** * Overrides the contents of this LazyField. * - *

LazyField is not thread-safe for write access. Synchronizations are needed - * under read/write situations. + *

LazyField is not thread-safe for write access. Synchronizations are needed under read/write + * situations. */ public void set(LazyFieldLite other) { this.delayedBytes = other.delayedBytes; @@ -218,7 +217,7 @@ public class LazyFieldLite { * Returns message instance. It may do some thread-safe delayed parsing of bytes. * * @param defaultInstance its message's default instance. It's also used to get parser for the - * message type. + * message type. */ public MessageLite getValue(MessageLite defaultInstance) { ensureInitialized(defaultInstance); @@ -228,8 +227,8 @@ public class LazyFieldLite { /** * Sets the value of the instance and returns the old value without delay parsing anything. * - *

LazyField is not thread-safe for write access. Synchronizations are needed - * under read/write situations. + *

LazyField is not thread-safe for write access. Synchronizations are needed under read/write + * situations. */ public MessageLite setValue(MessageLite value) { MessageLite originalValue = this.value; @@ -244,8 +243,8 @@ public class LazyFieldLite { * contain data. If the other field has an {@code ExtensionRegistry} but this does not, then this * field will copy over that {@code ExtensionRegistry}. * - *

LazyField is not thread-safe for write access. Synchronizations are needed - * under read/write situations. + *

LazyField is not thread-safe for write access. Synchronizations are needed under read/write + * situations. */ public void merge(LazyFieldLite other) { if (other.containsDefaultInstance()) { @@ -287,12 +286,12 @@ public class LazyFieldLite { // At this point we have two fully parsed messages. setValue(this.value.toBuilder().mergeFrom(other.value).build()); } - + /** * Merges another instance's contents from a stream. * - *

LazyField is not thread-safe for write access. Synchronizations are needed - * under read/write situations. + *

LazyField is not thread-safe for write access. Synchronizations are needed under read/write + * situations. */ public void mergeFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws IOException { @@ -339,9 +338,7 @@ public class LazyFieldLite { } } - /** - * Sets this field with bytes to delay-parse. - */ + /** Sets this field with bytes to delay-parse. */ public void setByteString(ByteString bytes, ExtensionRegistryLite extensionRegistry) { checkArguments(extensionRegistry, bytes); this.delayedBytes = bytes; @@ -351,9 +348,8 @@ public class LazyFieldLite { } /** - * Due to the optional field can be duplicated at the end of serialized - * bytes, which will make the serialized size changed after LazyField - * parsed. Be careful when using this method. + * Due to the optional field can be duplicated at the end of serialized bytes, which will make the + * serialized size changed after LazyField parsed. Be careful when using this method. */ public int getSerializedSize() { // We *must* return delayed bytes size if it was ever set because the dependent messages may @@ -369,9 +365,7 @@ public class LazyFieldLite { } } - /** - * Returns a BytesString for this field in a thread-safe way. - */ + /** Returns a BytesString for this field in a thread-safe way. */ public ByteString toByteString() { if (memoizedBytes != null) { return memoizedBytes; @@ -395,9 +389,7 @@ public class LazyFieldLite { } - /** - * Might lazily parse the bytes that were previously passed in. Is thread-safe. - */ + /** Might lazily parse the bytes that were previously passed in. Is thread-safe. */ protected void ensureInitialized(MessageLite defaultInstance) { if (value != null) { return; @@ -409,8 +401,8 @@ public class LazyFieldLite { try { if (delayedBytes != null) { // The extensionRegistry shouldn't be null here since we have delayedBytes. - MessageLite parsedValue = defaultInstance.getParserForType() - .parseFrom(delayedBytes, extensionRegistry); + MessageLite parsedValue = + defaultInstance.getParserForType().parseFrom(delayedBytes, extensionRegistry); this.value = parsedValue; this.memoizedBytes = delayedBytes; } else { @@ -426,7 +418,6 @@ public class LazyFieldLite { } } - private static void checkArguments(ExtensionRegistryLite extensionRegistry, ByteString bytes) { if (extensionRegistry == null) { throw new NullPointerException("found null ExtensionRegistry"); diff --git a/java/core/src/main/java/com/google/protobuf/LazyStringArrayList.java b/java/core/src/main/java/com/google/protobuf/LazyStringArrayList.java index 6cfc14a512..a2de6f9cfe 100644 --- a/java/core/src/main/java/com/google/protobuf/LazyStringArrayList.java +++ b/java/core/src/main/java/com/google/protobuf/LazyStringArrayList.java @@ -39,26 +39,22 @@ import java.util.List; import java.util.RandomAccess; /** - * An implementation of {@link LazyStringList} that wraps an ArrayList. Each - * element is one of String, ByteString, or byte[]. It caches the last one - * requested which is most likely the one needed next. This minimizes memory - * usage while satisfying the most common use cases. - *

- * Note that this implementation is not synchronized. - * If multiple threads access an ArrayList instance concurrently, - * and at least one of the threads modifies the list structurally, it - * must be synchronized externally. (A structural modification is - * any operation that adds or deletes one or more elements, or explicitly - * resizes the backing array; merely setting the value of an element is not - * a structural modification.) This is typically accomplished by - * synchronizing on some object that naturally encapsulates the list. - *

- * If the implementation is accessed via concurrent reads, this is thread safe. - * Conversions are done in a thread safe manner. It's possible that the - * conversion may happen more than once if two threads attempt to access the - * same element and the modifications were not visible to each other, but this - * will not result in any corruption of the list or change in behavior other - * than performance. + * An implementation of {@link LazyStringList} that wraps an ArrayList. Each element is one of + * String, ByteString, or byte[]. It caches the last one requested which is most likely the one + * needed next. This minimizes memory usage while satisfying the most common use cases. + * + *

Note that this implementation is not synchronized. If multiple threads access + * an ArrayList instance concurrently, and at least one of the threads modifies the list + * structurally, it must be synchronized externally. (A structural modification is any + * operation that adds or deletes one or more elements, or explicitly resizes the backing array; + * merely setting the value of an element is not a structural modification.) This is typically + * accomplished by synchronizing on some object that naturally encapsulates the list. + * + *

If the implementation is accessed via concurrent reads, this is thread safe. Conversions are + * done in a thread safe manner. It's possible that the conversion may happen more than once if two + * threads attempt to access the same element and the modifications were not visible to each other, + * but this will not result in any corruption of the list or change in behavior other than + * performance. * * @author jonp@google.com (Jon Perlow) */ @@ -66,6 +62,7 @@ public class LazyStringArrayList extends AbstractProtobufList implements LazyStringList, RandomAccess { private static final LazyStringArrayList EMPTY_LIST = new LazyStringArrayList(); + static { EMPTY_LIST.makeImmutable(); } @@ -177,8 +174,8 @@ public class LazyStringArrayList extends AbstractProtobufList ensureIsMutable(); // When copying from another LazyStringList, directly copy the underlying // elements rather than forcing each element to be decoded to a String. - Collection collection = c instanceof LazyStringList - ? ((LazyStringList) c).getUnderlyingElements() : c; + Collection collection = + c instanceof LazyStringList ? ((LazyStringList) c).getUnderlyingElements() : c; boolean ret = list.addAll(index, collection); modCount++; return ret; @@ -324,8 +321,7 @@ public class LazyStringArrayList extends AbstractProtobufList } } - private static class ByteArrayListView extends AbstractList - implements RandomAccess { + private static class ByteArrayListView extends AbstractList implements RandomAccess { private final LazyStringArrayList list; ByteArrayListView(LazyStringArrayList list) { @@ -368,8 +364,7 @@ public class LazyStringArrayList extends AbstractProtobufList return new ByteArrayListView(this); } - private static class ByteStringListView extends AbstractList - implements RandomAccess { + private static class ByteStringListView extends AbstractList implements RandomAccess { private final LazyStringArrayList list; ByteStringListView(LazyStringArrayList list) { @@ -419,5 +414,4 @@ public class LazyStringArrayList extends AbstractProtobufList } return this; } - } diff --git a/java/core/src/main/java/com/google/protobuf/LazyStringList.java b/java/core/src/main/java/com/google/protobuf/LazyStringList.java index 3eeedca1d3..6b55022caa 100644 --- a/java/core/src/main/java/com/google/protobuf/LazyStringList.java +++ b/java/core/src/main/java/com/google/protobuf/LazyStringList.java @@ -34,14 +34,12 @@ import java.util.Collection; import java.util.List; /** - * An interface extending {@code List} that also provides access to the - * items of the list as UTF8-encoded ByteString or byte[] objects. This is - * used by the protocol buffer implementation to support lazily converting bytes - * parsed over the wire to String objects until needed and also increases the - * efficiency of serialization if the String was never requested as the - * ByteString or byte[] is already cached. The ByteString methods are used in - * immutable API only and byte[] methods used in mutable API only for they use - * different representations for string/bytes fields. + * An interface extending {@code List} that also provides access to the items of the list as + * UTF8-encoded ByteString or byte[] objects. This is used by the protocol buffer implementation to + * support lazily converting bytes parsed over the wire to String objects until needed and also + * increases the efficiency of serialization if the String was never requested as the ByteString or + * byte[] is already cached. The ByteString methods are used in immutable API only and byte[] + * methods used in mutable API only for they use different representations for string/bytes fields. * * @author jonp@google.com (Jon Perlow) */ @@ -52,19 +50,19 @@ public interface LazyStringList extends ProtocolStringList { * * @param index index of the element to return * @return the element at the specified position in this list - * @throws IndexOutOfBoundsException if the index is out of range - * ({@code index < 0 || index >= size()}) + * @throws IndexOutOfBoundsException if the index is out of range ({@code index < 0 || index >= + * size()}) */ ByteString getByteString(int index); /** - * Returns the element at the specified position in this list as an Object - * that will either be a String or a ByteString. + * Returns the element at the specified position in this list as an Object that will either be a + * String or a ByteString. * * @param index index of the element to return * @return the element at the specified position in this list - * @throws IndexOutOfBoundsException if the index is out of range - * ({@code index < 0 || index >= size()}) + * @throws IndexOutOfBoundsException if the index is out of range ({@code index < 0 || index >= + * size()}) */ Object getRaw(int index); @@ -73,99 +71,91 @@ public interface LazyStringList extends ProtocolStringList { * * @param index index of the element to return * @return the element at the specified position in this list - * @throws IndexOutOfBoundsException if the index is out of range - * ({@code index < 0 || index >= size()}) + * @throws IndexOutOfBoundsException if the index is out of range ({@code index < 0 || index >= + * size()}) */ byte[] getByteArray(int index); /** - * Appends the specified element to the end of this list (optional - * operation). + * Appends the specified element to the end of this list (optional operation). * * @param element element to be appended to this list - * @throws UnsupportedOperationException if the add operation - * is not supported by this list + * @throws UnsupportedOperationException if the add operation is not supported by this + * list */ void add(ByteString element); /** - * Appends the specified element to the end of this list (optional - * operation). + * Appends the specified element to the end of this list (optional operation). * * @param element element to be appended to this list - * @throws UnsupportedOperationException if the add operation - * is not supported by this list + * @throws UnsupportedOperationException if the add operation is not supported by this + * list */ void add(byte[] element); /** - * Replaces the element at the specified position in this list with the - * specified element (optional operation). + * Replaces the element at the specified position in this list with the specified element + * (optional operation). * * @param index index of the element to replace * @param element the element to be stored at the specified position - * @throws UnsupportedOperationException if the set operation - * is not supported by this list - * IndexOutOfBoundsException if the index is out of range - * ({@code index < 0 || index >= size()}) + * @throws UnsupportedOperationException if the set operation is not supported by this + * list IndexOutOfBoundsException if the index is out of range ({@code index < 0 || index >= + * size()}) */ void set(int index, ByteString element); - + /** - * Replaces the element at the specified position in this list with the - * specified element (optional operation). + * Replaces the element at the specified position in this list with the specified element + * (optional operation). * * @param index index of the element to replace * @param element the element to be stored at the specified position - * @throws UnsupportedOperationException if the set operation - * is not supported by this list - * IndexOutOfBoundsException if the index is out of range - * ({@code index < 0 || index >= size()}) + * @throws UnsupportedOperationException if the set operation is not supported by this + * list IndexOutOfBoundsException if the index is out of range ({@code index < 0 || index >= + * size()}) */ void set(int index, byte[] element); /** - * Appends all elements in the specified ByteString collection to the end of - * this list. + * Appends all elements in the specified ByteString collection to the end of this list. * * @param c collection whose elements are to be added to this list * @return true if this list changed as a result of the call - * @throws UnsupportedOperationException if the addAllByteString - * operation is not supported by this list + * @throws UnsupportedOperationException if the addAllByteString operation is not + * supported by this list */ boolean addAllByteString(Collection c); /** - * Appends all elements in the specified byte[] collection to the end of - * this list. + * Appends all elements in the specified byte[] collection to the end of this list. * * @param c collection whose elements are to be added to this list * @return true if this list changed as a result of the call - * @throws UnsupportedOperationException if the addAllByteArray - * operation is not supported by this list + * @throws UnsupportedOperationException if the addAllByteArray operation is not + * supported by this list */ boolean addAllByteArray(Collection c); /** - * Returns an unmodifiable List of the underlying elements, each of which is - * either a {@code String} or its equivalent UTF-8 encoded {@code ByteString} - * or byte[]. It is an error for the caller to modify the returned - * List, and attempting to do so will result in an - * {@link UnsupportedOperationException}. + * Returns an unmodifiable List of the underlying elements, each of which is either a {@code + * String} or its equivalent UTF-8 encoded {@code ByteString} or byte[]. It is an error for the + * caller to modify the returned List, and attempting to do so will result in an {@link + * UnsupportedOperationException}. */ List getUnderlyingElements(); /** - * Merges all elements from another LazyStringList into this one. This method - * differs from {@link #addAll(Collection)} on that underlying byte arrays are - * copied instead of reference shared. Immutable API doesn't need to use this - * method as byte[] is not used there at all. + * Merges all elements from another LazyStringList into this one. This method differs from {@link + * #addAll(Collection)} on that underlying byte arrays are copied instead of reference shared. + * Immutable API doesn't need to use this method as byte[] is not used there at all. */ void mergeFrom(LazyStringList other); /** - * Returns a mutable view of this list. Changes to the view will be made into - * the original list. This method is used in mutable API only. + * Returns a mutable view of this list. Changes to the view will be made into the original list. + * This method is used in mutable API only. */ List asByteArrayList(); diff --git a/java/core/src/main/java/com/google/protobuf/LongArrayList.java b/java/core/src/main/java/com/google/protobuf/LongArrayList.java index 9a5056be09..8cdab12131 100644 --- a/java/core/src/main/java/com/google/protobuf/LongArrayList.java +++ b/java/core/src/main/java/com/google/protobuf/LongArrayList.java @@ -42,11 +42,11 @@ import java.util.RandomAccess; * * @author dweis@google.com (Daniel Weis) */ -final class LongArrayList - extends AbstractProtobufList +final class LongArrayList extends AbstractProtobufList implements LongList, RandomAccess, PrimitiveNonBoxingCollection { private static final LongArrayList EMPTY_LIST = new LongArrayList(); + static { EMPTY_LIST.makeImmutable(); } @@ -55,9 +55,7 @@ final class LongArrayList return EMPTY_LIST; } - /** - * The backing store for the list. - */ + /** The backing store for the list. */ private long[] array; /** @@ -66,16 +64,13 @@ final class LongArrayList */ private int size; - /** - * Constructs a new mutable {@code LongArrayList} with default capacity. - */ + /** Constructs a new mutable {@code LongArrayList} with default capacity. */ LongArrayList() { this(new long[DEFAULT_CAPACITY], 0); } /** - * Constructs a new mutable {@code LongArrayList} - * containing the same elements as {@code other}. + * Constructs a new mutable {@code LongArrayList} containing the same elements as {@code other}. */ private LongArrayList(long[] other, int size) { array = other; @@ -169,17 +164,13 @@ final class LongArrayList addLong(index, element); } - /** - * Like {@link #add(Long)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #add(Long)} but more efficient in that it doesn't box the element. */ @Override public void addLong(long element) { addLong(size, element); } - /** - * Like {@link #add(int, Long)} but more efficient in that it doesn't box the element. - */ + /** Like {@link #add(int, Long)} but more efficient in that it doesn't box the element. */ private void addLong(int index, long element) { ensureIsMutable(); if (index < 0 || index > size) { diff --git a/java/core/src/main/java/com/google/protobuf/MapEntry.java b/java/core/src/main/java/com/google/protobuf/MapEntry.java index 0849b821cf..0175452288 100644 --- a/java/core/src/main/java/com/google/protobuf/MapEntry.java +++ b/java/core/src/main/java/com/google/protobuf/MapEntry.java @@ -41,11 +41,11 @@ import java.util.TreeMap; /** * Implements MapEntry messages. * - * In reflection API, map fields will be treated as repeated message fields and - * each map entry is accessed as a message. This MapEntry class is used to - * represent these map entry messages in reflection API. + *

In reflection API, map fields will be treated as repeated message fields and each map entry is + * accessed as a message. This MapEntry class is used to represent these map entry messages in + * reflection API. * - * Protobuf internal. Users shouldn't use this class. + *

Protobuf internal. Users shouldn't use this class. */ public final class MapEntry extends AbstractMessage { @@ -61,15 +61,16 @@ public final class MapEntry extends AbstractMessage { WireFormat.FieldType valueType) { super(keyType, defaultInstance.key, valueType, defaultInstance.value); this.descriptor = descriptor; - this.parser = new AbstractParser>() { + this.parser = + new AbstractParser>() { - @Override - public MapEntry parsePartialFrom( - CodedInputStream input, ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - return new MapEntry(Metadata.this, input, extensionRegistry); - } - }; + @Override + public MapEntry parsePartialFrom( + CodedInputStream input, ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException { + return new MapEntry(Metadata.this, input, extensionRegistry); + } + }; } } @@ -80,8 +81,10 @@ public final class MapEntry extends AbstractMessage { /** Create a default MapEntry instance. */ private MapEntry( Descriptor descriptor, - WireFormat.FieldType keyType, K defaultKey, - WireFormat.FieldType valueType, V defaultValue) { + WireFormat.FieldType keyType, + K defaultKey, + WireFormat.FieldType valueType, + V defaultValue) { this.key = defaultKey; this.value = defaultValue; this.metadata = new Metadata(descriptor, this, keyType, valueType); @@ -97,9 +100,7 @@ public final class MapEntry extends AbstractMessage { /** Parsing constructor. */ private MapEntry( - Metadata metadata, - CodedInputStream input, - ExtensionRegistryLite extensionRegistry) + Metadata metadata, CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { try { this.metadata = metadata; @@ -114,17 +115,17 @@ public final class MapEntry extends AbstractMessage { } /** - * Create a default MapEntry instance. A default MapEntry instance should be - * created only once for each map entry message type. Generated code should - * store the created default instance and use it later to create new MapEntry - * messages of the same type. + * Create a default MapEntry instance. A default MapEntry instance should be created only once for + * each map entry message type. Generated code should store the created default instance and use + * it later to create new MapEntry messages of the same type. */ public static MapEntry newDefaultInstance( Descriptor descriptor, - WireFormat.FieldType keyType, K defaultKey, - WireFormat.FieldType valueType, V defaultValue) { - return new MapEntry( - descriptor, keyType, defaultKey, valueType, defaultValue); + WireFormat.FieldType keyType, + K defaultKey, + WireFormat.FieldType valueType, + V defaultValue) { + return new MapEntry(descriptor, keyType, defaultKey, valueType, defaultValue); } public K getKey() { @@ -197,14 +198,17 @@ public final class MapEntry extends AbstractMessage { private void checkFieldDescriptor(FieldDescriptor field) { if (field.getContainingType() != metadata.descriptor) { throw new RuntimeException( - "Wrong FieldDescriptor \"" + field.getFullName() - + "\" used in message \"" + metadata.descriptor.getFullName()); + "Wrong FieldDescriptor \"" + + field.getFullName() + + "\" used in message \"" + + metadata.descriptor.getFullName()); } } @Override public boolean hasField(FieldDescriptor field) { - checkFieldDescriptor(field);; + checkFieldDescriptor(field); + ; // A MapEntry always contains two fields. return true; } @@ -215,22 +219,19 @@ public final class MapEntry extends AbstractMessage { Object result = field.getNumber() == 1 ? getKey() : getValue(); // Convert enums to EnumValueDescriptor. if (field.getType() == FieldDescriptor.Type.ENUM) { - result = field.getEnumType().findValueByNumberCreatingIfUnknown( - (java.lang.Integer) result); + result = field.getEnumType().findValueByNumberCreatingIfUnknown((java.lang.Integer) result); } return result; } @Override public int getRepeatedFieldCount(FieldDescriptor field) { - throw new RuntimeException( - "There is no repeated field in a map entry message."); + throw new RuntimeException("There is no repeated field in a map entry message."); } @Override public Object getRepeatedField(FieldDescriptor field, int index) { - throw new RuntimeException( - "There is no repeated field in a map entry message."); + throw new RuntimeException("There is no repeated field in a map entry message."); } @Override @@ -238,11 +239,8 @@ public final class MapEntry extends AbstractMessage { return UnknownFieldSet.getDefaultInstance(); } - /** - * Builder to create {@link MapEntry} messages. - */ - public static class Builder - extends AbstractMessage.Builder> { + /** Builder to create {@link MapEntry} messages. */ + public static class Builder extends AbstractMessage.Builder> { private final Metadata metadata; private K key; private V value; @@ -315,20 +313,21 @@ public final class MapEntry extends AbstractMessage { private void checkFieldDescriptor(FieldDescriptor field) { if (field.getContainingType() != metadata.descriptor) { throw new RuntimeException( - "Wrong FieldDescriptor \"" + field.getFullName() - + "\" used in message \"" + metadata.descriptor.getFullName()); + "Wrong FieldDescriptor \"" + + field.getFullName() + + "\" used in message \"" + + metadata.descriptor.getFullName()); } } @Override public Message.Builder newBuilderForField(FieldDescriptor field) { - checkFieldDescriptor(field);; + checkFieldDescriptor(field); + ; // This method should be called for message fields and in a MapEntry // message only the value field can possibly be a message field. - if (field.getNumber() != 2 - || field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) { - throw new RuntimeException( - "\"" + field.getFullName() + "\" is not a message value field."); + if (field.getNumber() != 2 || field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) { + throw new RuntimeException("\"" + field.getFullName() + "\" is not a message value field."); } return ((Message) value).newBuilderForType(); } @@ -369,16 +368,13 @@ public final class MapEntry extends AbstractMessage { } @Override - public Builder setRepeatedField(FieldDescriptor field, int index, - Object value) { - throw new RuntimeException( - "There is no repeated field in a map entry message."); + public Builder setRepeatedField(FieldDescriptor field, int index, Object value) { + throw new RuntimeException("There is no repeated field in a map entry message."); } @Override public Builder addRepeatedField(FieldDescriptor field, Object value) { - throw new RuntimeException( - "There is no repeated field in a map entry message."); + throw new RuntimeException("There is no repeated field in a map entry message."); } @Override @@ -427,14 +423,12 @@ public final class MapEntry extends AbstractMessage { @Override public int getRepeatedFieldCount(FieldDescriptor field) { - throw new RuntimeException( - "There is no repeated field in a map entry message."); + throw new RuntimeException("There is no repeated field in a map entry message."); } @Override public Object getRepeatedField(FieldDescriptor field, int index) { - throw new RuntimeException( - "There is no repeated field in a map entry message."); + throw new RuntimeException("There is no repeated field in a map entry message."); } @Override @@ -455,7 +449,7 @@ public final class MapEntry extends AbstractMessage { } return true; } - + /** Returns the metadata only for experimental runtime. */ final Metadata getMetadata() { return metadata; diff --git a/java/core/src/main/java/com/google/protobuf/MapEntryLite.java b/java/core/src/main/java/com/google/protobuf/MapEntryLite.java index dcb5dfad3d..ca2a3c2a97 100644 --- a/java/core/src/main/java/com/google/protobuf/MapEntryLite.java +++ b/java/core/src/main/java/com/google/protobuf/MapEntryLite.java @@ -37,11 +37,10 @@ import java.util.Map; /** * Implements the lite version of map entry messages. * - * This class serves as an utility class to help do serialization/parsing of - * map entries. It's used in generated code and also in the full version - * MapEntry message. + *

This class serves as an utility class to help do serialization/parsing of map entries. It's + * used in generated code and also in the full version MapEntry message. * - * Protobuf internal. Users shouldn't use. + *

Protobuf internal. Users shouldn't use. */ public class MapEntryLite { @@ -52,8 +51,10 @@ public class MapEntryLite { public final V defaultValue; public Metadata( - WireFormat.FieldType keyType, K defaultKey, - WireFormat.FieldType valueType, V defaultValue) { + WireFormat.FieldType keyType, + K defaultKey, + WireFormat.FieldType valueType, + V defaultValue) { this.keyType = keyType; this.defaultKey = defaultKey; this.valueType = valueType; @@ -70,8 +71,7 @@ public class MapEntryLite { /** Creates a default MapEntryLite message instance. */ private MapEntryLite( - WireFormat.FieldType keyType, K defaultKey, - WireFormat.FieldType valueType, V defaultValue) { + WireFormat.FieldType keyType, K defaultKey, WireFormat.FieldType valueType, V defaultValue) { this.metadata = new Metadata(keyType, defaultKey, valueType, defaultValue); this.key = defaultKey; this.value = defaultValue; @@ -95,16 +95,13 @@ public class MapEntryLite { /** * Creates a default MapEntryLite message instance. * - * This method is used by generated code to create the default instance for - * a map entry message. The created default instance should be used to create - * new map entry messages of the same type. For each map entry message, only - * one default instance should be created. + *

This method is used by generated code to create the default instance for a map entry + * message. The created default instance should be used to create new map entry messages of the + * same type. For each map entry message, only one default instance should be created. */ public static MapEntryLite newDefaultInstance( - WireFormat.FieldType keyType, K defaultKey, - WireFormat.FieldType valueType, V defaultValue) { - return new MapEntryLite( - keyType, defaultKey, valueType, defaultValue); + WireFormat.FieldType keyType, K defaultKey, WireFormat.FieldType valueType, V defaultValue) { + return new MapEntryLite(keyType, defaultKey, valueType, defaultValue); } static void writeTo(CodedOutputStream output, Metadata metadata, K key, V value) @@ -120,8 +117,11 @@ public class MapEntryLite { @SuppressWarnings("unchecked") static T parseField( - CodedInputStream input, ExtensionRegistryLite extensionRegistry, - WireFormat.FieldType type, T value) throws IOException { + CodedInputStream input, + ExtensionRegistryLite extensionRegistry, + WireFormat.FieldType type, + T value) + throws IOException { switch (type) { case MESSAGE: MessageLite.Builder subBuilder = ((MessageLite) value).toBuilder(); @@ -137,9 +137,9 @@ public class MapEntryLite { } /** - * Serializes the provided key and value as though they were wrapped by a {@link MapEntryLite} - * to the output stream. This helper method avoids allocation of a {@link MapEntryLite} - * built with a key and value and is called from generated code directly. + * Serializes the provided key and value as though they were wrapped by a {@link MapEntryLite} to + * the output stream. This helper method avoids allocation of a {@link MapEntryLite} built with a + * key and value and is called from generated code directly. */ public void serializeTo(CodedOutputStream output, int fieldNumber, K key, V value) throws IOException { @@ -149,9 +149,9 @@ public class MapEntryLite { } /** - * Computes the message size for the provided key and value as though they were wrapped - * by a {@link MapEntryLite}. This helper method avoids allocation of a {@link MapEntryLite} - * built with a key and value and is called from generated code directly. + * Computes the message size for the provided key and value as though they were wrapped by a + * {@link MapEntryLite}. This helper method avoids allocation of a {@link MapEntryLite} built with + * a key and value and is called from generated code directly. */ public int computeMessageSize(int fieldNumber, K key, V value) { return CodedOutputStream.computeTagSize(fieldNumber) @@ -160,8 +160,8 @@ public class MapEntryLite { } /** - * Parses an entry off of the input as a {@link Map.Entry}. This helper requires an allocation - * so using {@link #parseInto} is preferred if possible. + * Parses an entry off of the input as a {@link Map.Entry}. This helper requires an allocation so + * using {@link #parseInto} is preferred if possible. */ public Map.Entry parseEntry(ByteString bytes, ExtensionRegistryLite extensionRegistry) throws IOException { @@ -170,7 +170,7 @@ public class MapEntryLite { static Map.Entry parseEntry( CodedInputStream input, Metadata metadata, ExtensionRegistryLite extensionRegistry) - throws IOException{ + throws IOException { K key = metadata.defaultKey; V value = metadata.defaultValue; while (true) { @@ -192,12 +192,12 @@ public class MapEntryLite { } /** - * Parses an entry off of the input into the map. This helper avoids allocaton of a - * {@link MapEntryLite} by parsing directly into the provided {@link MapFieldLite}. + * Parses an entry off of the input into the map. This helper avoids allocaton of a {@link + * MapEntryLite} by parsing directly into the provided {@link MapFieldLite}. */ public void parseInto( MapFieldLite map, CodedInputStream input, ExtensionRegistryLite extensionRegistry) - throws IOException { + throws IOException { int length = input.readRawVarint32(); final int oldLimit = input.pushLimit(length); K key = metadata.defaultKey; diff --git a/java/core/src/main/java/com/google/protobuf/MapField.java b/java/core/src/main/java/com/google/protobuf/MapField.java index ad8ceb02a9..f487736065 100644 --- a/java/core/src/main/java/com/google/protobuf/MapField.java +++ b/java/core/src/main/java/com/google/protobuf/MapField.java @@ -44,38 +44,44 @@ import java.util.Set; /** * Internal representation of map fields in generated messages. * - * This class supports accessing the map field as a {@link Map} to be used in - * generated API and also supports accessing the field as a {@link List} to be - * used in reflection API. It keeps track of where the data is currently stored - * and do necessary conversions between map and list. + *

This class supports accessing the map field as a {@link Map} to be used in generated API and + * also supports accessing the field as a {@link List} to be used in reflection API. It keeps track + * of where the data is currently stored and do necessary conversions between map and list. * - * This class is a protobuf implementation detail. Users shouldn't use this - * class directly. + *

This class is a protobuf implementation detail. Users shouldn't use this class directly. * - * THREAD-SAFETY NOTE: Read-only access is thread-safe. Users can call getMap() - * and getList() concurrently in multiple threads. If write-access is needed, - * all access must be synchronized. + *

THREAD-SAFETY NOTE: Read-only access is thread-safe. Users can call getMap() and getList() + * concurrently in multiple threads. If write-access is needed, all access must be synchronized. */ public class MapField implements MutabilityOracle { + /** * Indicates where the data of this map field is currently stored. * - * MAP: Data is stored in mapData. - * LIST: Data is stored in listData. - * BOTH: mapData and listData have the same data. + *

    + *
  • MAP: Data is stored in mapData. + *
  • LIST: Data is stored in listData. + *
  • BOTH: mapData and listData have the same data. + *
* - * When the map field is accessed (through generated API or reflection API), - * it will shift between these 3 modes: + *

When the map field is accessed (through generated API or reflection API), it will shift + * between these 3 modes: * - * getMap() getList() getMutableMap() getMutableList() - * MAP MAP BOTH MAP LIST - * LIST BOTH LIST MAP LIST - * BOTH BOTH BOTH MAP LIST + *

+   *          getMap()   getList()    getMutableMap()   getMutableList()
+   * MAP      MAP        BOTH         MAP               LIST
+   * LIST     BOTH       LIST         MAP               LIST
+   * BOTH     BOTH       BOTH         MAP               LIST
+   * 
* - * As the map field changes its mode, the list/map reference returned in a - * previous method call may be invalidated. + *

As the map field changes its mode, the list/map reference returned in a previous method call + * may be invalidated. */ - private enum StorageMode {MAP, LIST, BOTH} + private enum StorageMode { + MAP, + LIST, + BOTH + } private volatile boolean isMutable; private volatile StorageMode mode; @@ -85,6 +91,7 @@ public class MapField implements MutabilityOracle { // Convert between a map entry Message and a key-value pair. private static interface Converter { Message convertKeyAndValueToMessage(K key, V value); + void convertMessageToKeyAndValue(Message message, Map map); Message getMessageDefaultInstance(); @@ -92,6 +99,7 @@ public class MapField implements MutabilityOracle { private static class ImmutableMessageConverter implements Converter { private final MapEntry defaultEntry; + public ImmutableMessageConverter(MapEntry defaultEntry) { this.defaultEntry = defaultEntry; } @@ -117,10 +125,7 @@ public class MapField implements MutabilityOracle { private final Converter converter; - private MapField( - Converter converter, - StorageMode mode, - Map mapData) { + private MapField(Converter converter, StorageMode mode, Map mapData) { this.converter = converter; this.isMutable = true; this.mode = mode; @@ -128,26 +133,20 @@ public class MapField implements MutabilityOracle { this.listData = null; } - private MapField( - MapEntry defaultEntry, - StorageMode mode, - Map mapData) { + private MapField(MapEntry defaultEntry, StorageMode mode, Map mapData) { this(new ImmutableMessageConverter(defaultEntry), mode, mapData); } /** Returns an immutable empty MapField. */ - public static MapField emptyMapField( - MapEntry defaultEntry) { - return new MapField( - defaultEntry, StorageMode.MAP, Collections.emptyMap()); + public static MapField emptyMapField(MapEntry defaultEntry) { + return new MapField(defaultEntry, StorageMode.MAP, Collections.emptyMap()); } /** Creates a new mutable empty MapField. */ public static MapField newMapField(MapEntry defaultEntry) { - return new MapField( - defaultEntry, StorageMode.MAP, new LinkedHashMap()); + return new MapField(defaultEntry, StorageMode.MAP, new LinkedHashMap()); } @@ -163,9 +162,7 @@ public class MapField implements MutabilityOracle { private List convertMapToList(MutatabilityAwareMap mapData) { List listData = new ArrayList(); for (Map.Entry entry : mapData.entrySet()) { - listData.add( - convertKeyAndValueToMessage( - entry.getKey(), entry.getValue())); + listData.add(convertKeyAndValueToMessage(entry.getKey(), entry.getValue())); } return listData; } @@ -229,8 +226,7 @@ public class MapField implements MutabilityOracle { /** Returns a deep copy of this MapField. */ public MapField copy() { - return new MapField( - converter, StorageMode.MAP, MapFieldLite.copy(getMap())); + return new MapField(converter, StorageMode.MAP, MapFieldLite.copy(getMap())); } /** Gets the content of this MapField as a read-only List. */ @@ -258,25 +254,20 @@ public class MapField implements MutabilityOracle { return listData; } - /** - * Gets the default instance of the message stored in the list view of this - * map field. - */ + /** Gets the default instance of the message stored in the list view of this map field. */ Message getMapEntryMessageDefaultInstance() { return converter.getMessageDefaultInstance(); } /** - * Makes this list immutable. All subsequent modifications will throw an - * {@link UnsupportedOperationException}. + * Makes this list immutable. All subsequent modifications will throw an {@link + * UnsupportedOperationException}. */ public void makeImmutable() { isMutable = false; } - /** - * Returns whether this field can be modified. - */ + /** Returns whether this field can be modified. */ public boolean isMutable() { return isMutable; } @@ -291,9 +282,7 @@ public class MapField implements MutabilityOracle { } } - /** - * An internal map that checks for mutability before delegating. - */ + /** An internal map that checks for mutability before delegating. */ private static class MutatabilityAwareMap implements Map { private final MutabilityOracle mutabilityOracle; private final Map delegate; @@ -388,9 +377,7 @@ public class MapField implements MutabilityOracle { return delegate.toString(); } - /** - * An internal collection that checks for mutability before delegating. - */ + /** An internal collection that checks for mutability before delegating. */ private static class MutatabilityAwareCollection implements Collection { private final MutabilityOracle mutabilityOracle; private final Collection delegate; @@ -487,9 +474,7 @@ public class MapField implements MutabilityOracle { } } - /** - * An internal set that checks for mutability before delegating. - */ + /** An internal set that checks for mutability before delegating. */ private static class MutatabilityAwareSet implements Set { private final MutabilityOracle mutabilityOracle; private final Set delegate; @@ -586,9 +571,7 @@ public class MapField implements MutabilityOracle { } } - /** - * An internal iterator that checks for mutability before delegating. - */ + /** An internal iterator that checks for mutability before delegating. */ private static class MutatabilityAwareIterator implements Iterator { private final MutabilityOracle mutabilityOracle; private final Iterator delegate; diff --git a/java/core/src/main/java/com/google/protobuf/MapFieldLite.java b/java/core/src/main/java/com/google/protobuf/MapFieldLite.java index a8b3dd8849..7467487b63 100644 --- a/java/core/src/main/java/com/google/protobuf/MapFieldLite.java +++ b/java/core/src/main/java/com/google/protobuf/MapFieldLite.java @@ -42,8 +42,7 @@ import java.util.Set; /** * Internal representation of map fields in generated lite-runtime messages. * - * This class is a protobuf implementation detail. Users shouldn't use this - * class directly. + *

This class is a protobuf implementation detail. Users shouldn't use this class directly. */ public final class MapFieldLite extends LinkedHashMap { @@ -60,6 +59,7 @@ public final class MapFieldLite extends LinkedHashMap { @SuppressWarnings({"rawtypes", "unchecked"}) private static final MapFieldLite EMPTY_MAP_FIELD = new MapFieldLite(); + static { EMPTY_MAP_FIELD.makeImmutable(); } @@ -78,16 +78,19 @@ public final class MapFieldLite extends LinkedHashMap { } @SuppressWarnings({"unchecked", "cast"}) - @Override public Set> entrySet() { + @Override + public Set> entrySet() { return isEmpty() ? Collections.>emptySet() : super.entrySet(); } - @Override public void clear() { + @Override + public void clear() { ensureMutable(); super.clear(); } - @Override public V put(K key, V value) { + @Override + public V put(K key, V value) { ensureMutable(); checkNotNull(key); @@ -99,13 +102,15 @@ public final class MapFieldLite extends LinkedHashMap { return put(entry.getKey(), entry.getValue()); } - @Override public void putAll(Map m) { + @Override + public void putAll(Map m) { ensureMutable(); checkForNullKeysAndValues(m); super.putAll(m); } - @Override public V remove(Object key) { + @Override + public V remove(Object key) { ensureMutable(); return super.remove(key); } @@ -125,9 +130,8 @@ public final class MapFieldLite extends LinkedHashMap { } /** - * Checks whether two {@link Map}s are equal. We don't use the default equals - * method of {@link Map} because it compares by identity not by content for - * byte arrays. + * Checks whether two {@link Map}s are equal. We don't use the default equals method of {@link + * Map} because it compares by identity not by content for byte arrays. */ static boolean equals(Map a, Map b) { if (a == b) { @@ -147,9 +151,7 @@ public final class MapFieldLite extends LinkedHashMap { return true; } - /** - * Checks whether two map fields are equal. - */ + /** Checks whether two map fields are equal. */ @SuppressWarnings("unchecked") @Override public boolean equals(Object object) { @@ -168,15 +170,14 @@ public final class MapFieldLite extends LinkedHashMap { } /** - * Calculates the hash code for a {@link Map}. We don't use the default hash - * code method of {@link Map} because for byte arrays and protobuf enums it - * use {@link Object#hashCode()}. + * Calculates the hash code for a {@link Map}. We don't use the default hash code method of {@link + * Map} because for byte arrays and protobuf enums it use {@link Object#hashCode()}. */ static int calculateHashCodeForMap(Map a) { int result = 0; for (Map.Entry entry : a.entrySet()) { - result += calculateHashCodeForObject(entry.getKey()) - ^ calculateHashCodeForObject(entry.getValue()); + result += + calculateHashCodeForObject(entry.getKey()) ^ calculateHashCodeForObject(entry.getValue()); } return result; } @@ -195,9 +196,9 @@ public final class MapFieldLite extends LinkedHashMap { } /** - * Makes a deep copy of a {@link Map}. Immutable objects in the map will be - * shared (e.g., integers, strings, immutable messages) and mutable ones will - * have a copy (e.g., byte arrays, mutable messages). + * Makes a deep copy of a {@link Map}. Immutable objects in the map will be shared (e.g., + * integers, strings, immutable messages) and mutable ones will have a copy (e.g., byte arrays, + * mutable messages). */ @SuppressWarnings("unchecked") static Map copy(Map map) { @@ -214,16 +215,14 @@ public final class MapFieldLite extends LinkedHashMap { } /** - * Makes this field immutable. All subsequent modifications will throw an - * {@link UnsupportedOperationException}. + * Makes this field immutable. All subsequent modifications will throw an {@link + * UnsupportedOperationException}. */ public void makeImmutable() { isMutable = false; } - /** - * Returns whether this field can be modified. - */ + /** Returns whether this field can be modified. */ public boolean isMutable() { return isMutable; } diff --git a/java/core/src/main/java/com/google/protobuf/Message.java b/java/core/src/main/java/com/google/protobuf/Message.java index 0770d41787..52b4a20863 100644 --- a/java/core/src/main/java/com/google/protobuf/Message.java +++ b/java/core/src/main/java/com/google/protobuf/Message.java @@ -39,12 +39,11 @@ import java.util.Map; /** * Abstract interface implemented by Protocol Message objects. - *

- * See also {@link MessageLite}, which defines most of the methods that typical - * users care about. {@link Message} adds to it methods that are not available - * in the "lite" runtime. The biggest added features are introspection and - * reflection -- i.e., getting descriptors for the message type and accessing - * the field values dynamically. + * + *

See also {@link MessageLite}, which defines most of the methods that typical users care about. + * {@link Message} adds to it methods that are not available in the "lite" runtime. The biggest + * added features are introspection and reflection -- i.e., getting descriptors for the message type + * and accessing the field values dynamically. * * @author kenton@google.com Kenton Varda */ @@ -59,11 +58,10 @@ public interface Message extends MessageLite, MessageOrBuilder { // Comparison and hashing /** - * Compares the specified object with this message for equality. Returns - * {@code true} if the given object is a message of the same type (as - * defined by {@code getDescriptorForType()}) and has identical values for - * all of its fields. Subclasses must implement this; inheriting - * {@code Object.equals()} is incorrect. + * Compares the specified object with this message for equality. Returns {@code true} if the given + * object is a message of the same type (as defined by {@code getDescriptorForType()}) and has + * identical values for all of its fields. Subclasses must implement this; inheriting {@code + * Object.equals()} is incorrect. * * @param other object to be compared for equality with this message * @return {@code true} if the specified object is equal to this message @@ -72,10 +70,9 @@ public interface Message extends MessageLite, MessageOrBuilder { boolean equals(Object other); /** - * Returns the hash code value for this message. The hash code of a message - * should mix the message's type (object identity of the descriptor) with its - * contents (known and unknown field values). Subclasses must implement this; - * inheriting {@code Object.hashCode()} is incorrect. + * Returns the hash code value for this message. The hash code of a message should mix the + * message's type (object identity of the descriptor) with its contents (known and unknown field + * values). Subclasses must implement this; inheriting {@code Object.hashCode()} is incorrect. * * @return the hash code value for this message * @see Map#hashCode() @@ -87,9 +84,8 @@ public interface Message extends MessageLite, MessageOrBuilder { // Convenience methods. /** - * Converts the message to a string in protocol buffer text format. This is - * just a trivial wrapper around {@link - * TextFormat#printToString(MessageOrBuilder)}. + * Converts the message to a string in protocol buffer text format. This is just a trivial wrapper + * around {@link TextFormat#printToString(MessageOrBuilder)}. */ @Override String toString(); @@ -104,9 +100,7 @@ public interface Message extends MessageLite, MessageOrBuilder { @Override Builder toBuilder(); - /** - * Abstract interface implemented by Protocol Message builders. - */ + /** Abstract interface implemented by Protocol Message builders. */ interface Builder extends MessageLite.Builder, MessageOrBuilder { // (From MessageLite.Builder, re-declared here only for return type // covariance.) @@ -114,23 +108,21 @@ public interface Message extends MessageLite, MessageOrBuilder { Builder clear(); /** - * Merge {@code other} into the message being built. {@code other} must - * have the exact same type as {@code this} (i.e. - * {@code getDescriptorForType() == other.getDescriptorForType()}). + * Merge {@code other} into the message being built. {@code other} must have the exact same type + * as {@code this} (i.e. {@code getDescriptorForType() == other.getDescriptorForType()}). * - * Merging occurs as follows. For each field:
- * * For singular primitive fields, if the field is set in {@code other}, - * then {@code other}'s value overwrites the value in this message.
- * * For singular message fields, if the field is set in {@code other}, - * it is merged into the corresponding sub-message of this message - * using the same merging rules.
- * * For repeated fields, the elements in {@code other} are concatenated - * with the elements in this message.
- * * For oneof groups, if the other message has one of the fields set, - * the group of this message is cleared and replaced by the field - * of the other message, so that the oneof constraint is preserved. + *

Merging occurs as follows. For each field:
+ * * For singular primitive fields, if the field is set in {@code other}, then {@code other}'s + * value overwrites the value in this message.
+ * * For singular message fields, if the field is set in {@code other}, it is merged into the + * corresponding sub-message of this message using the same merging rules.
+ * * For repeated fields, the elements in {@code other} are concatenated with the elements in + * this message.
+ * * For oneof groups, if the other message has one of the fields set, the group of this message + * is cleared and replaced by the field of the other message, so that the oneof constraint is + * preserved. * - * This is equivalent to the {@code Message::MergeFrom} method in C++. + *

This is equivalent to the {@code Message::MergeFrom} method in C++. */ Builder mergeFrom(Message other); @@ -152,101 +144,90 @@ public interface Message extends MessageLite, MessageOrBuilder { Builder mergeFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws IOException; - /** - * Get the message's type's descriptor. - * See {@link Message#getDescriptorForType()}. - */ + /** Get the message's type's descriptor. See {@link Message#getDescriptorForType()}. */ @Override Descriptors.Descriptor getDescriptorForType(); /** - * Create a Builder for messages of the appropriate type for the given - * field. Messages built with this can then be passed to setField(), - * setRepeatedField(), or addRepeatedField(). + * Create a Builder for messages of the appropriate type for the given field. Messages built + * with this can then be passed to setField(), setRepeatedField(), or addRepeatedField(). */ Builder newBuilderForField(Descriptors.FieldDescriptor field); /** * Get a nested builder instance for the given field. - *

- * Normally, we hold a reference to the immutable message object for the - * message type field. Some implementations(the generated message builders), - * however, can also hold a reference to the builder object (a nested - * builder) for the field. - *

- * If the field is already backed up by a nested builder, the nested builder - * will be returned. Otherwise, a new field builder will be created and - * returned. The original message field (if exist) will be merged into the - * field builder, which will then be nested into its parent builder. - *

- * NOTE: implementations that do not support nested builders will throw - * UnsupportedOperationException. + * + *

Normally, we hold a reference to the immutable message object for the message type field. + * Some implementations(the generated message builders), however, can also hold a reference to + * the builder object (a nested builder) for the field. + * + *

If the field is already backed up by a nested builder, the nested builder will be + * returned. Otherwise, a new field builder will be created and returned. The original message + * field (if exist) will be merged into the field builder, which will then be nested into its + * parent builder. + * + *

NOTE: implementations that do not support nested builders will throw + * UnsupportedOperationException. */ Builder getFieldBuilder(Descriptors.FieldDescriptor field); /** * Get a nested builder instance for the given repeated field instance. - *

- * Normally, we hold a reference to the immutable message object for the - * message type field. Some implementations(the generated message builders), - * however, can also hold a reference to the builder object (a nested - * builder) for the field. - *

- * If the field is already backed up by a nested builder, the nested builder - * will be returned. Otherwise, a new field builder will be created and - * returned. The original message field (if exist) will be merged into the - * field builder, which will then be nested into its parent builder. - *

- * NOTE: implementations that do not support nested builders will throw - * UnsupportedOperationException. + * + *

Normally, we hold a reference to the immutable message object for the message type field. + * Some implementations(the generated message builders), however, can also hold a reference to + * the builder object (a nested builder) for the field. + * + *

If the field is already backed up by a nested builder, the nested builder will be + * returned. Otherwise, a new field builder will be created and returned. The original message + * field (if exist) will be merged into the field builder, which will then be nested into its + * parent builder. + * + *

NOTE: implementations that do not support nested builders will throw + * UnsupportedOperationException. */ - Builder getRepeatedFieldBuilder(Descriptors.FieldDescriptor field, - int index); + Builder getRepeatedFieldBuilder(Descriptors.FieldDescriptor field, int index); /** - * Sets a field to the given value. The value must be of the correct type - * for this field, i.e. the same type that - * {@link Message#getField(Descriptors.FieldDescriptor)} would return. + * Sets a field to the given value. The value must be of the correct type for this field, i.e. + * the same type that {@link Message#getField(Descriptors.FieldDescriptor)} would return. */ Builder setField(Descriptors.FieldDescriptor field, Object value); /** - * Clears the field. This is exactly equivalent to calling the generated - * "clear" accessor method corresponding to the field. + * Clears the field. This is exactly equivalent to calling the generated "clear" accessor method + * corresponding to the field. */ Builder clearField(Descriptors.FieldDescriptor field); /** - * Clears the oneof. This is exactly equivalent to calling the generated - * "clear" accessor method corresponding to the oneof. + * Clears the oneof. This is exactly equivalent to calling the generated "clear" accessor method + * corresponding to the oneof. */ Builder clearOneof(Descriptors.OneofDescriptor oneof); /** - * Sets an element of a repeated field to the given value. The value must - * be of the correct type for this field, i.e. the same type that - * {@link Message#getRepeatedField(Descriptors.FieldDescriptor,int)} would - * return. - * @throws IllegalArgumentException The field is not a repeated field, or - * {@code field.getContainingType() != getDescriptorForType()}. + * Sets an element of a repeated field to the given value. The value must be of the correct type + * for this field, i.e. the same type that {@link + * Message#getRepeatedField(Descriptors.FieldDescriptor,int)} would return. + * + * @throws IllegalArgumentException The field is not a repeated field, or {@code + * field.getContainingType() != getDescriptorForType()}. */ - Builder setRepeatedField(Descriptors.FieldDescriptor field, - int index, Object value); + Builder setRepeatedField(Descriptors.FieldDescriptor field, int index, Object value); /** * Like {@code setRepeatedField}, but appends the value as a new element. - * @throws IllegalArgumentException The field is not a repeated field, or - * {@code field.getContainingType() != getDescriptorForType()}. + * + * @throws IllegalArgumentException The field is not a repeated field, or {@code + * field.getContainingType() != getDescriptorForType()}. */ Builder addRepeatedField(Descriptors.FieldDescriptor field, Object value); /** Set the {@link UnknownFieldSet} for this message. */ Builder setUnknownFields(UnknownFieldSet unknownFields); - /** - * Merge some unknown fields into the {@link UnknownFieldSet} for this - * message. - */ + /** Merge some unknown fields into the {@link UnknownFieldSet} for this message. */ Builder mergeUnknownFields(UnknownFieldSet unknownFields); // --------------------------------------------------------------- diff --git a/java/core/src/main/java/com/google/protobuf/MessageLite.java b/java/core/src/main/java/com/google/protobuf/MessageLite.java index 88f531df3e..7d2ef33a17 100644 --- a/java/core/src/main/java/com/google/protobuf/MessageLite.java +++ b/java/core/src/main/java/com/google/protobuf/MessageLite.java @@ -40,91 +40,79 @@ import java.io.OutputStream; /** * Abstract interface implemented by Protocol Message objects. * - *

This interface is implemented by all protocol message objects. Non-lite - * messages additionally implement the Message interface, which is a subclass - * of MessageLite. Use MessageLite instead when you only need the subset of - * features which it supports -- namely, nothing that uses descriptors or - * reflection. You can instruct the protocol compiler to generate classes - * which implement only MessageLite, not the full Message interface, by adding - * the follow line to the .proto file: + *

This interface is implemented by all protocol message objects. Non-lite messages additionally + * implement the Message interface, which is a subclass of MessageLite. Use MessageLite instead when + * you only need the subset of features which it supports -- namely, nothing that uses descriptors + * or reflection. You can instruct the protocol compiler to generate classes which implement only + * MessageLite, not the full Message interface, by adding the follow line to the .proto file: + * *

  *   option optimize_for = LITE_RUNTIME;
  * 
* - *

This is particularly useful on resource-constrained systems where the - * full protocol buffers runtime library is too big. + *

This is particularly useful on resource-constrained systems where the full protocol buffers + * runtime library is too big. * - *

Note that on non-constrained systems (e.g. servers) when you need to link - * in lots of protocol definitions, a better way to reduce total code footprint - * is to use {@code optimize_for = CODE_SIZE}. This will make the generated - * code smaller while still supporting all the same features (at the expense of - * speed). {@code optimize_for = LITE_RUNTIME} is best when you only have a - * small number of message types linked into your binary, in which case the - * size of the protocol buffers runtime itself is the biggest problem. + *

Note that on non-constrained systems (e.g. servers) when you need to link in lots of protocol + * definitions, a better way to reduce total code footprint is to use {@code optimize_for = + * CODE_SIZE}. This will make the generated code smaller while still supporting all the same + * features (at the expense of speed). {@code optimize_for = LITE_RUNTIME} is best when you only + * have a small number of message types linked into your binary, in which case the size of the + * protocol buffers runtime itself is the biggest problem. * * @author kenton@google.com Kenton Varda */ public interface MessageLite extends MessageLiteOrBuilder { - /** - * Serializes the message and writes it to {@code output}. This does not - * flush or close the stream. + * Serializes the message and writes it to {@code output}. This does not flush or close the + * stream. */ void writeTo(CodedOutputStream output) throws IOException; /** - * Get the number of bytes required to encode this message. The result - * is only computed on the first call and memoized after that. + * Get the number of bytes required to encode this message. The result is only computed on the + * first call and memoized after that. */ int getSerializedSize(); - - /** - * Gets the parser for a message of the same type as this message. - */ + /** Gets the parser for a message of the same type as this message. */ Parser getParserForType(); // ----------------------------------------------------------------- // Convenience methods. /** - * Serializes the message to a {@code ByteString} and returns it. This is - * just a trivial wrapper around - * {@link #writeTo(CodedOutputStream)}. + * Serializes the message to a {@code ByteString} and returns it. This is just a trivial wrapper + * around {@link #writeTo(CodedOutputStream)}. */ ByteString toByteString(); /** - * Serializes the message to a {@code byte} array and returns it. This is - * just a trivial wrapper around - * {@link #writeTo(CodedOutputStream)}. + * Serializes the message to a {@code byte} array and returns it. This is just a trivial wrapper + * around {@link #writeTo(CodedOutputStream)}. */ byte[] toByteArray(); /** - * Serializes the message and writes it to {@code output}. This is just a - * trivial wrapper around {@link #writeTo(CodedOutputStream)}. This does - * not flush or close the stream. - *

- * NOTE: Protocol Buffers are not self-delimiting. Therefore, if you write - * any more data to the stream after the message, you must somehow ensure - * that the parser on the receiving end does not interpret this as being - * part of the protocol message. This can be done e.g. by writing the size - * of the message before the data, then making sure to limit the input to - * that size on the receiving end (e.g. by wrapping the InputStream in one - * which limits the input). Alternatively, just use - * {@link #writeDelimitedTo(OutputStream)}. + * Serializes the message and writes it to {@code output}. This is just a trivial wrapper around + * {@link #writeTo(CodedOutputStream)}. This does not flush or close the stream. + * + *

NOTE: Protocol Buffers are not self-delimiting. Therefore, if you write any more data to the + * stream after the message, you must somehow ensure that the parser on the receiving end does not + * interpret this as being part of the protocol message. This can be done e.g. by writing the size + * of the message before the data, then making sure to limit the input to that size on the + * receiving end (e.g. by wrapping the InputStream in one which limits the input). Alternatively, + * just use {@link #writeDelimitedTo(OutputStream)}. */ void writeTo(OutputStream output) throws IOException; /** - * Like {@link #writeTo(OutputStream)}, but writes the size of the message - * as a varint before writing the data. This allows more data to be written - * to the stream after the message without the need to delimit the message - * data yourself. Use {@link Builder#mergeDelimitedFrom(InputStream)} (or - * the static method {@code YourMessageType.parseDelimitedFrom(InputStream)}) - * to parse messages written by this method. + * Like {@link #writeTo(OutputStream)}, but writes the size of the message as a varint before + * writing the data. This allows more data to be written to the stream after the message without + * the need to delimit the message data yourself. Use {@link + * Builder#mergeDelimitedFrom(InputStream)} (or the static method {@code + * YourMessageType.parseDelimitedFrom(InputStream)}) to parse messages written by this method. */ void writeDelimitedTo(OutputStream output) throws IOException; @@ -132,210 +120,179 @@ public interface MessageLite extends MessageLiteOrBuilder { // ================================================================= // Builders - /** - * Constructs a new builder for a message of the same type as this message. - */ + /** Constructs a new builder for a message of the same type as this message. */ Builder newBuilderForType(); /** - * Constructs a builder initialized with the current message. Use this to - * derive a new message from the current one. + * Constructs a builder initialized with the current message. Use this to derive a new message + * from the current one. */ Builder toBuilder(); - /** - * Abstract interface implemented by Protocol Message builders. - */ + /** Abstract interface implemented by Protocol Message builders. */ interface Builder extends MessageLiteOrBuilder, Cloneable { /** Resets all fields to their default values. */ Builder clear(); /** - * Constructs the message based on the state of the Builder. Subsequent - * changes to the Builder will not affect the returned message. - * @throws UninitializedMessageException The message is missing one or more - * required fields (i.e. {@link #isInitialized()} returns false). - * Use {@link #buildPartial()} to bypass this check. + * Constructs the message based on the state of the Builder. Subsequent changes to the Builder + * will not affect the returned message. + * + * @throws UninitializedMessageException The message is missing one or more required fields + * (i.e. {@link #isInitialized()} returns false). Use {@link #buildPartial()} to bypass this + * check. */ MessageLite build(); /** - * Like {@link #build()}, but does not throw an exception if the message - * is missing required fields. Instead, a partial message is returned. - * Subsequent changes to the Builder will not affect the returned message. + * Like {@link #build()}, but does not throw an exception if the message is missing required + * fields. Instead, a partial message is returned. Subsequent changes to the Builder will not + * affect the returned message. */ MessageLite buildPartial(); /** * Clones the Builder. + * * @see Object#clone() */ Builder clone(); /** - * Parses a message of this type from the input and merges it with this - * message. + * Parses a message of this type from the input and merges it with this message. + * + *

Warning: This does not verify that all required fields are present in the input message. + * If you call {@link #build()} without setting all required fields, it will throw an {@link + * UninitializedMessageException}, which is a {@code RuntimeException} and thus might not be + * caught. There are a few good ways to deal with this: * - *

Warning: This does not verify that all required fields are present in - * the input message. If you call {@link #build()} without setting all - * required fields, it will throw an {@link UninitializedMessageException}, - * which is a {@code RuntimeException} and thus might not be caught. There - * are a few good ways to deal with this: *

    - *
  • Call {@link #isInitialized()} to verify that all required fields - * are set before building. - *
  • Use {@code buildPartial()} to build, which ignores missing - * required fields. + *
  • Call {@link #isInitialized()} to verify that all required fields are set before + * building. + *
  • Use {@code buildPartial()} to build, which ignores missing required fields. *
* - *

Note: The caller should call - * {@link CodedInputStream#checkLastTagWas(int)} after calling this to - * verify that the last tag seen was the appropriate end-group tag, - * or zero for EOF. + *

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

- * Despite usually reading the entire input, this does not close the stream. + * Parse a message of this type from {@code input} and merge it with the message being built. + * This is just a small wrapper around {@link #mergeFrom(CodedInputStream)}. Note that this + * method always reads the entire input (unless it throws an exception). If you want it + * to stop earlier, you will need to wrap your input in some wrapper stream that limits reading. + * Or, use {@link MessageLite#writeDelimitedTo(OutputStream)} to write your message and {@link + * #mergeDelimitedFrom(InputStream)} to read it. + * + *

Despite usually reading the entire input, this does not close the stream. * * @return this */ Builder mergeFrom(InputStream input) throws IOException; /** - * Parse a message of this type from {@code input} and merge it with the - * message being built. This is just a small wrapper around - * {@link #mergeFrom(CodedInputStream,ExtensionRegistryLite)}. + * Parse a message of this type from {@code input} and merge it with the message being built. + * This is just a small wrapper around {@link + * #mergeFrom(CodedInputStream,ExtensionRegistryLite)}. * * @return this */ - Builder mergeFrom(InputStream input, - ExtensionRegistryLite extensionRegistry) - throws IOException; - + Builder mergeFrom(InputStream input, ExtensionRegistryLite extensionRegistry) + throws IOException; + /** - * Merge {@code other} into the message being built. {@code other} must - * have the exact same type as {@code this} (i.e. - * {@code getClass().equals(getDefaultInstanceForType().getClass())}). + * Merge {@code other} into the message being built. {@code other} must have the exact same type + * as {@code this} (i.e. {@code getClass().equals(getDefaultInstanceForType().getClass())}). * - * Merging occurs as follows. For each field:
- * * For singular primitive fields, if the field is set in {@code other}, - * then {@code other}'s value overwrites the value in this message.
- * * For singular message fields, if the field is set in {@code other}, - * it is merged into the corresponding sub-message of this message - * using the same merging rules.
- * * For repeated fields, the elements in {@code other} are concatenated - * with the elements in this message. - * * For oneof groups, if the other message has one of the fields set, - * the group of this message is cleared and replaced by the field - * of the other message, so that the oneof constraint is preserved. + *

Merging occurs as follows. For each field:
+ * * For singular primitive fields, if the field is set in {@code other}, then {@code other}'s + * value overwrites the value in this message.
+ * * For singular message fields, if the field is set in {@code other}, it is merged into the + * corresponding sub-message of this message using the same merging rules.
+ * * For repeated fields, the elements in {@code other} are concatenated with the elements in + * this message. * For oneof groups, if the other message has one of the fields set, the group + * of this message is cleared and replaced by the field of the other message, so that the oneof + * constraint is preserved. * - * This is equivalent to the {@code Message::MergeFrom} method in C++. + *

This is equivalent to the {@code Message::MergeFrom} method in C++. */ Builder mergeFrom(MessageLite other); /** - * Like {@link #mergeFrom(InputStream)}, but does not read until EOF. - * Instead, the size of the message (encoded as a varint) is read first, - * then the message data. Use - * {@link MessageLite#writeDelimitedTo(OutputStream)} to write messages in - * this format. + * Like {@link #mergeFrom(InputStream)}, but does not read until EOF. Instead, the size of the + * message (encoded as a varint) is read first, then the message data. Use {@link + * MessageLite#writeDelimitedTo(OutputStream)} to write messages in this format. * - * @return True if successful, or false if the stream is at EOF when the - * method starts. Any other error (including reaching EOF during - * parsing) will cause an exception to be thrown. + * @return True if successful, or false if the stream is at EOF when the method starts. Any + * other error (including reaching EOF during parsing) will cause an exception to be thrown. */ - boolean mergeDelimitedFrom(InputStream input) - throws IOException; + boolean mergeDelimitedFrom(InputStream input) throws IOException; - /** - * Like {@link #mergeDelimitedFrom(InputStream)} but supporting extensions. - */ - boolean mergeDelimitedFrom(InputStream input, - ExtensionRegistryLite extensionRegistry) - throws IOException; + /** Like {@link #mergeDelimitedFrom(InputStream)} but supporting extensions. */ + boolean mergeDelimitedFrom(InputStream input, ExtensionRegistryLite extensionRegistry) + throws IOException; } } diff --git a/java/core/src/main/java/com/google/protobuf/MessageLiteOrBuilder.java b/java/core/src/main/java/com/google/protobuf/MessageLiteOrBuilder.java index 818386ce58..7a5ef3ed51 100644 --- a/java/core/src/main/java/com/google/protobuf/MessageLiteOrBuilder.java +++ b/java/core/src/main/java/com/google/protobuf/MessageLiteOrBuilder.java @@ -31,30 +31,27 @@ package com.google.protobuf; /** - * Base interface for methods common to {@link MessageLite} - * and {@link MessageLite.Builder} to provide type equivalency. + * Base interface for methods common to {@link MessageLite} and {@link MessageLite.Builder} to + * provide type equivalency. * * @author jonp@google.com (Jon Perlow) */ public interface MessageLiteOrBuilder { /** - * Get an instance of the type with no fields set. Because no fields are set, - * all getters for singular fields will return default values and repeated - * fields will appear empty. - * This may or may not be a singleton. This differs from the - * {@code getDefaultInstance()} method of generated message classes in that - * this method is an abstract method of the {@code MessageLite} interface - * whereas {@code getDefaultInstance()} is a static method of a specific - * class. They return the same thing. + * Get an instance of the type with no fields set. Because no fields are set, all getters for + * singular fields will return default values and repeated fields will appear empty. This may or + * may not be a singleton. This differs from the {@code getDefaultInstance()} method of generated + * message classes in that this method is an abstract method of the {@code MessageLite} interface + * whereas {@code getDefaultInstance()} is a static method of a specific class. They return the + * same thing. */ MessageLite getDefaultInstanceForType(); /** - * Returns true if all required fields in the message and all embedded - * messages are set, false otherwise. + * Returns true if all required fields in the message and all embedded messages are set, false + * otherwise. * *

See also: {@link MessageOrBuilder#getInitializationErrorString()} */ boolean isInitialized(); - } diff --git a/java/core/src/main/java/com/google/protobuf/MessageOrBuilder.java b/java/core/src/main/java/com/google/protobuf/MessageOrBuilder.java index 5e7d782132..0254df99ac 100644 --- a/java/core/src/main/java/com/google/protobuf/MessageOrBuilder.java +++ b/java/core/src/main/java/com/google/protobuf/MessageOrBuilder.java @@ -34,8 +34,8 @@ import java.util.List; import java.util.Map; /** - * Base interface for methods common to {@link Message} and - * {@link Message.Builder} to provide type equivalency. + * Base interface for methods common to {@link Message} and {@link Message.Builder} to provide type + * equivalency. * * @author jonp@google.com (Jon Perlow) */ @@ -46,95 +46,85 @@ public interface MessageOrBuilder extends MessageLiteOrBuilder { Message getDefaultInstanceForType(); /** - * Returns a list of field paths (e.g. "foo.bar.baz") of required fields - * which are not set in this message. You should call - * {@link MessageLiteOrBuilder#isInitialized()} first to check if there - * are any missing fields, as that method is likely to be much faster - * than this one even when the message is fully-initialized. + * Returns a list of field paths (e.g. "foo.bar.baz") of required fields which are not set in this + * message. You should call {@link MessageLiteOrBuilder#isInitialized()} first to check if there + * are any missing fields, as that method is likely to be much faster than this one even when the + * message is fully-initialized. */ List findInitializationErrors(); /** - * Returns a comma-delimited list of required fields which are not set - * in this message object. You should call - * {@link MessageLiteOrBuilder#isInitialized()} first to check if there - * are any missing fields, as that method is likely to be much faster - * than this one even when the message is fully-initialized. + * Returns a comma-delimited list of required fields which are not set in this message object. You + * should call {@link MessageLiteOrBuilder#isInitialized()} first to check if there are any + * missing fields, as that method is likely to be much faster than this one even when the message + * is fully-initialized. */ String getInitializationErrorString(); /** - * Get the message's type's descriptor. This differs from the - * {@code getDescriptor()} method of generated message classes in that - * this method is an abstract method of the {@code Message} interface - * whereas {@code getDescriptor()} is a static method of a specific class. - * They return the same thing. + * Get the message's type's descriptor. This differs from the {@code getDescriptor()} method of + * generated message classes in that this method is an abstract method of the {@code Message} + * interface whereas {@code getDescriptor()} is a static method of a specific class. They return + * the same thing. */ Descriptors.Descriptor getDescriptorForType(); /** - * 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 #getField(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. - *
- * If this is for a builder, the returned map may or may not reflect future - * changes to the builder. Either way, the returned map is itself - * unmodifiable. + * 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 #getField(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.
+ * If this is for a builder, the returned map may or may not reflect future changes to the + * builder. Either way, the returned map is itself unmodifiable. */ Map getAllFields(); /** * Returns true if the given oneof is set. - * @throws IllegalArgumentException if - * {@code oneof.getContainingType() != getDescriptorForType()}. + * + * @throws IllegalArgumentException if {@code oneof.getContainingType() != + * getDescriptorForType()}. */ boolean hasOneof(Descriptors.OneofDescriptor oneof); - /** - * Obtains the FieldDescriptor if the given oneof is set. Returns null - * if no field is set. - */ - Descriptors.FieldDescriptor getOneofFieldDescriptor( - Descriptors.OneofDescriptor oneof); + /** Obtains the FieldDescriptor if the given oneof is set. Returns null if no field is set. */ + Descriptors.FieldDescriptor getOneofFieldDescriptor(Descriptors.OneofDescriptor oneof); /** - * Returns true if the given field is set. This is exactly equivalent to - * calling the generated "has" accessor method corresponding to the field. - * @throws IllegalArgumentException The field is a repeated field, or - * {@code field.getContainingType() != getDescriptorForType()}. + * Returns true if the given field is set. This is exactly equivalent to calling the generated + * "has" accessor method corresponding to the field. + * + * @throws IllegalArgumentException The field is a repeated field, or {@code + * field.getContainingType() != getDescriptorForType()}. */ boolean hasField(Descriptors.FieldDescriptor field); /** - * 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 + * 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. */ Object getField(Descriptors.FieldDescriptor field); /** - * Gets the number of elements of a repeated field. This is exactly - * equivalent to calling the generated "Count" accessor method corresponding - * to the field. - * @throws IllegalArgumentException The field is not a repeated field, or - * {@code field.getContainingType() != getDescriptorForType()}. + * Gets the number of elements of a repeated field. This is exactly equivalent to calling the + * generated "Count" accessor method corresponding to the field. + * + * @throws IllegalArgumentException The field is not a repeated field, or {@code + * field.getContainingType() != getDescriptorForType()}. */ int getRepeatedFieldCount(Descriptors.FieldDescriptor field); /** - * Gets an element of a repeated field. 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. - * @throws IllegalArgumentException The field is not a repeated field, or - * {@code field.getContainingType() != getDescriptorForType()}. + * Gets an element of a repeated field. 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. + * + * @throws IllegalArgumentException The field is not a repeated field, or {@code + * field.getContainingType() != getDescriptorForType()}. */ Object getRepeatedField(Descriptors.FieldDescriptor field, int index); diff --git a/java/core/src/main/java/com/google/protobuf/MessageReflection.java b/java/core/src/main/java/com/google/protobuf/MessageReflection.java index 69ad7ddf94..9fc72bd9e1 100644 --- a/java/core/src/main/java/com/google/protobuf/MessageReflection.java +++ b/java/core/src/main/java/com/google/protobuf/MessageReflection.java @@ -54,20 +54,19 @@ class MessageReflection { message.getDescriptorForType().getOptions().getMessageSetWireFormat(); if (alwaysWriteRequiredFields) { fields = new TreeMap(fields); - for (final FieldDescriptor field : - message.getDescriptorForType().getFields()) { + for (final FieldDescriptor field : message.getDescriptorForType().getFields()) { if (field.isRequired() && !fields.containsKey(field)) { fields.put(field, message.getField(field)); } } } - for (final Map.Entry entry : - fields.entrySet()) { + for (final Map.Entry entry : fields.entrySet()) { final Descriptors.FieldDescriptor field = entry.getKey(); final Object value = entry.getValue(); - if (isMessageSet && field.isExtension() && - field.getType() == Descriptors.FieldDescriptor.Type.MESSAGE && - !field.isRepeated()) { + if (isMessageSet + && field.isExtension() + && field.getType() == Descriptors.FieldDescriptor.Type.MESSAGE + && !field.isRepeated()) { output.writeMessageSetExtension(field.getNumber(), (Message) value); } else { FieldSet.writeField(field, value, output); @@ -82,22 +81,20 @@ class MessageReflection { } } - static int getSerializedSize( - Message message, - Map fields) { + static int getSerializedSize(Message message, Map fields) { int size = 0; final boolean isMessageSet = message.getDescriptorForType().getOptions().getMessageSetWireFormat(); - for (final Map.Entry entry : - fields.entrySet()) { + for (final Map.Entry entry : fields.entrySet()) { final Descriptors.FieldDescriptor field = entry.getKey(); final Object value = entry.getValue(); - if (isMessageSet && field.isExtension() && - field.getType() == Descriptors.FieldDescriptor.Type.MESSAGE && - !field.isRepeated()) { - size += CodedOutputStream.computeMessageSetExtensionSize( - field.getNumber(), (Message) value); + if (isMessageSet + && field.isExtension() + && field.getType() == Descriptors.FieldDescriptor.Type.MESSAGE + && !field.isRepeated()) { + size += + CodedOutputStream.computeMessageSetExtensionSize(field.getNumber(), (Message) value); } else { size += FieldSet.computeFieldSize(field, value); } @@ -126,9 +123,7 @@ class MessageReflection { @SuppressWarnings("unchecked") static boolean isInitialized(MessageOrBuilder message) { // Check that all required fields are present. - for (final Descriptors.FieldDescriptor field : message - .getDescriptorForType() - .getFields()) { + for (final Descriptors.FieldDescriptor field : message.getDescriptorForType().getFields()) { if (field.isRequired()) { if (!message.hasField(field)) { return false; @@ -142,8 +137,7 @@ class MessageReflection { final Descriptors.FieldDescriptor field = entry.getKey(); if (field.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { if (field.isRepeated()) { - for (final Message element - : (List) entry.getValue()) { + for (final Message element : (List) entry.getValue()) { if (!element.isInitialized()) { return false; } @@ -159,31 +153,24 @@ class MessageReflection { return true; } - private static String subMessagePrefix(final String prefix, - final Descriptors.FieldDescriptor field, - final int index) { + private static String subMessagePrefix( + final String prefix, final Descriptors.FieldDescriptor field, final int index) { final StringBuilder result = new StringBuilder(prefix); if (field.isExtension()) { - result.append('(') - .append(field.getFullName()) - .append(')'); + result.append('(').append(field.getFullName()).append(')'); } else { result.append(field.getName()); } if (index != -1) { - result.append('[') - .append(index) - .append(']'); + result.append('[').append(index).append(']'); } result.append('.'); return result.toString(); } - private static void findMissingFields(final MessageOrBuilder message, - final String prefix, - final List results) { - for (final Descriptors.FieldDescriptor field : - message.getDescriptorForType().getFields()) { + private static void findMissingFields( + final MessageOrBuilder message, final String prefix, final List results) { + for (final Descriptors.FieldDescriptor field : message.getDescriptorForType().getFields()) { if (field.isRequired() && !message.hasField(field)) { results.add(prefix + field.getName()); } @@ -198,15 +185,13 @@ class MessageReflection { if (field.isRepeated()) { int i = 0; for (final Object element : (List) value) { - findMissingFields((MessageOrBuilder) element, - subMessagePrefix(prefix, field, i++), - results); + findMissingFields( + (MessageOrBuilder) element, subMessagePrefix(prefix, field, i++), results); } } else { if (message.hasField(field)) { - findMissingFields((MessageOrBuilder) value, - subMessagePrefix(prefix, field, -1), - results); + findMissingFields( + (MessageOrBuilder) value, subMessagePrefix(prefix, field, -1), results); } } } @@ -214,11 +199,10 @@ class MessageReflection { } /** - * Populates {@code this.missingFields} with the full "path" of each missing - * required field in the given message. + * Populates {@code this.missingFields} with the full "path" of each missing required field in the + * given message. */ - static List findMissingFields( - final MessageOrBuilder message) { + static List findMissingFields(final MessageOrBuilder message) { final List results = new ArrayList(); findMissingFields(message, "", results); return results; @@ -226,12 +210,11 @@ class MessageReflection { static interface MergeTarget { enum ContainerType { - MESSAGE, EXTENSION_SET + MESSAGE, + EXTENSION_SET } - /** - * Returns the descriptor for the target. - */ + /** Returns the descriptor for the target. */ public Descriptors.Descriptor getDescriptorForType(); public ContainerType getContainerType(); @@ -240,21 +223,19 @@ class MessageReflection { ExtensionRegistry registry, String name); public ExtensionRegistry.ExtensionInfo findExtensionByNumber( - ExtensionRegistry registry, Descriptors.Descriptor containingType, - int fieldNumber); + ExtensionRegistry registry, Descriptors.Descriptor containingType, int fieldNumber); /** - * 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 + * 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. */ public Object getField(Descriptors.FieldDescriptor field); /** - * Returns true if the given field is set. This is exactly equivalent to - * calling the generated "has" accessor method corresponding to the field. + * Returns true if the given field is set. This is exactly equivalent to calling the generated + * "has" accessor method corresponding to the field. * * @throws IllegalArgumentException The field is a repeated field, or {@code * field.getContainingType() != getDescriptorForType()}. @@ -262,106 +243,98 @@ class MessageReflection { boolean hasField(Descriptors.FieldDescriptor field); /** - * Sets a field to the given value. The value must be of the correct type - * for this field, i.e. the same type that - * {@link Message#getField(Descriptors.FieldDescriptor)} - * would return. + * Sets a field to the given value. The value must be of the correct type for this field, i.e. + * the same type that {@link Message#getField(Descriptors.FieldDescriptor)} would return. */ MergeTarget setField(Descriptors.FieldDescriptor field, Object value); /** - * Clears the field. This is exactly equivalent to calling the generated - * "clear" accessor method corresponding to the field. + * Clears the field. This is exactly equivalent to calling the generated "clear" accessor method + * corresponding to the field. */ MergeTarget clearField(Descriptors.FieldDescriptor field); /** - * Sets an element of a repeated field to the given value. The value must - * be of the correct type for this field, i.e. the same type that {@link + * Sets an element of a repeated field to the given value. The value must be of the correct type + * for this field, i.e. the same type that {@link * Message#getRepeatedField(Descriptors.FieldDescriptor, int)} would return. * - * @throws IllegalArgumentException The field is not a repeated field, or - * {@code field.getContainingType() != - * getDescriptorForType()}. + * @throws IllegalArgumentException The field is not a repeated field, or {@code + * field.getContainingType() != getDescriptorForType()}. */ - MergeTarget setRepeatedField(Descriptors.FieldDescriptor field, - int index, Object value); + MergeTarget setRepeatedField(Descriptors.FieldDescriptor field, int index, Object value); /** * Like {@code setRepeatedField}, but appends the value as a new element. * - * @throws IllegalArgumentException The field is not a repeated field, or - * {@code field.getContainingType() != - * getDescriptorForType()}. + * @throws IllegalArgumentException The field is not a repeated field, or {@code + * field.getContainingType() != getDescriptorForType()}. */ - MergeTarget addRepeatedField(Descriptors.FieldDescriptor field, - Object value); + MergeTarget addRepeatedField(Descriptors.FieldDescriptor field, Object value); /** * Returns true if the given oneof is set. * - * @throws IllegalArgumentException if - * {@code oneof.getContainingType() != getDescriptorForType()}. + * @throws IllegalArgumentException if {@code oneof.getContainingType() != + * getDescriptorForType()}. */ boolean hasOneof(Descriptors.OneofDescriptor oneof); /** - * Clears the oneof. This is exactly equivalent to calling the generated - * "clear" accessor method corresponding to the oneof. + * Clears the oneof. This is exactly equivalent to calling the generated "clear" accessor method + * corresponding to the oneof. */ MergeTarget clearOneof(Descriptors.OneofDescriptor oneof); - /** - * Obtains the FieldDescriptor if the given oneof is set. Returns null - * if no field is set. - */ + /** Obtains the FieldDescriptor if the given oneof is set. Returns null if no field is set. */ Descriptors.FieldDescriptor getOneofFieldDescriptor(Descriptors.OneofDescriptor oneof); /** - * Parse the input stream into a sub field group defined based on either - * FieldDescriptor or the default instance. + * Parse the input stream into a sub field group defined based on either FieldDescriptor or the + * default instance. */ - Object parseGroup(CodedInputStream input, ExtensionRegistryLite registry, - Descriptors.FieldDescriptor descriptor, Message defaultInstance) + Object parseGroup( + CodedInputStream input, + ExtensionRegistryLite registry, + Descriptors.FieldDescriptor descriptor, + Message defaultInstance) throws IOException; /** - * Parse the input stream into a sub field message defined based on either - * FieldDescriptor or the default instance. + * Parse the input stream into a sub field message defined based on either FieldDescriptor or + * the default instance. */ - Object parseMessage(CodedInputStream input, ExtensionRegistryLite registry, - Descriptors.FieldDescriptor descriptor, Message defaultInstance) + Object parseMessage( + CodedInputStream input, + ExtensionRegistryLite registry, + Descriptors.FieldDescriptor descriptor, + Message defaultInstance) throws IOException; /** - * Parse from a ByteString into a sub field message defined based on either - * FieldDescriptor or the default instance. There isn't a varint indicating - * the length of the message at the beginning of the input ByteString. + * Parse from a ByteString into a sub field message defined based on either FieldDescriptor or + * the default instance. There isn't a varint indicating the length of the message at the + * beginning of the input ByteString. */ Object parseMessageFromBytes( - ByteString bytes, ExtensionRegistryLite registry, - Descriptors.FieldDescriptor descriptor, Message defaultInstance) + ByteString bytes, + ExtensionRegistryLite registry, + Descriptors.FieldDescriptor descriptor, + Message defaultInstance) throws IOException; - /** - * Returns the UTF8 validation level for the field. - */ - WireFormat.Utf8Validation getUtf8Validation(Descriptors.FieldDescriptor - descriptor); + /** Returns the UTF8 validation level for the field. */ + WireFormat.Utf8Validation getUtf8Validation(Descriptors.FieldDescriptor descriptor); /** - * Returns a new merge target for a sub-field. When defaultInstance is - * provided, it indicates the descriptor is for an extension type, and - * implementations should create a new instance from the defaultInstance - * prototype directly. + * Returns a new merge target for a sub-field. When defaultInstance is provided, it indicates + * the descriptor is for an extension type, and implementations should create a new instance + * from the defaultInstance prototype directly. */ MergeTarget newMergeTargetForField( - Descriptors.FieldDescriptor descriptor, - Message defaultInstance); + Descriptors.FieldDescriptor descriptor, Message defaultInstance); - /** - * Finishes the merge and returns the underlying object. - */ + /** Finishes the merge and returns the underlying object. */ Object finish(); } @@ -443,8 +416,7 @@ class MessageReflection { @Override public ExtensionRegistry.ExtensionInfo findExtensionByNumber( ExtensionRegistry registry, Descriptors.Descriptor containingType, int fieldNumber) { - return registry.findImmutableExtensionByNumber(containingType, - fieldNumber); + return registry.findImmutableExtensionByNumber(containingType, fieldNumber); } @Override @@ -523,8 +495,7 @@ class MessageReflection { public MergeTarget newMergeTargetForField( Descriptors.FieldDescriptor field, Message defaultInstance) { if (defaultInstance != null) { - return new BuilderAdapter( - defaultInstance.newBuilderForType()); + return new BuilderAdapter(defaultInstance.newBuilderForType()); } else { return new BuilderAdapter(builder.newBuilderForField(field)); } @@ -536,8 +507,7 @@ class MessageReflection { return WireFormat.Utf8Validation.STRICT; } // TODO(liujisi): support lazy strings for repeated fields. - if (!descriptor.isRepeated() - && builder instanceof GeneratedMessage.Builder) { + if (!descriptor.isRepeated() && builder instanceof GeneratedMessage.Builder) { return WireFormat.Utf8Validation.LAZY; } return WireFormat.Utf8Validation.LOOSE; @@ -560,8 +530,7 @@ class MessageReflection { @Override public Descriptors.Descriptor getDescriptorForType() { - throw new UnsupportedOperationException( - "getDescriptorForType() called on FieldSet object"); + throw new UnsupportedOperationException("getDescriptorForType() called on FieldSet object"); } @Override @@ -629,8 +598,7 @@ class MessageReflection { @Override public ExtensionRegistry.ExtensionInfo findExtensionByNumber( ExtensionRegistry registry, Descriptors.Descriptor containingType, int fieldNumber) { - return registry.findImmutableExtensionByNumber(containingType, - fieldNumber); + return registry.findImmutableExtensionByNumber(containingType, fieldNumber); } @Override @@ -640,8 +608,7 @@ class MessageReflection { Descriptors.FieldDescriptor field, Message defaultInstance) throws IOException { - Message.Builder subBuilder = - defaultInstance.newBuilderForType(); + Message.Builder subBuilder = defaultInstance.newBuilderForType(); if (!field.isRepeated()) { Message originalMessage = (Message) getField(field); if (originalMessage != null) { @@ -659,8 +626,7 @@ class MessageReflection { Descriptors.FieldDescriptor field, Message defaultInstance) throws IOException { - Message.Builder subBuilder = - defaultInstance.newBuilderForType(); + Message.Builder subBuilder = defaultInstance.newBuilderForType(); if (!field.isRepeated()) { Message originalMessage = (Message) getField(field); if (originalMessage != null) { @@ -678,7 +644,7 @@ class MessageReflection { Descriptors.FieldDescriptor field, Message defaultInstance) throws IOException { - Message.Builder subBuilder = defaultInstance.newBuilderForType(); + Message.Builder subBuilder = defaultInstance.newBuilderForType(); if (!field.isRepeated()) { Message originalMessage = (Message) getField(field); if (originalMessage != null) { @@ -692,8 +658,7 @@ class MessageReflection { @Override public MergeTarget newMergeTargetForField( Descriptors.FieldDescriptor descriptor, Message defaultInstance) { - throw new UnsupportedOperationException( - "newMergeTargetForField() called on FieldSet object"); + throw new UnsupportedOperationException("newMergeTargetForField() called on FieldSet object"); } @Override @@ -707,8 +672,7 @@ class MessageReflection { @Override public Object finish() { - throw new UnsupportedOperationException( - "finish() called on FieldSet object"); + throw new UnsupportedOperationException("finish() called on FieldSet object"); } } @@ -731,8 +695,7 @@ class MessageReflection { MergeTarget target, int tag) throws IOException { - if (type.getOptions().getMessageSetWireFormat() && - tag == WireFormat.MESSAGE_SET_ITEM_TAG) { + if (type.getOptions().getMessageSetWireFormat() && tag == WireFormat.MESSAGE_SET_ITEM_TAG) { mergeMessageSetExtensionFromCodedStream( input, unknownFields, extensionRegistry, type, target); return true; @@ -752,19 +715,16 @@ class MessageReflection { // were empty. if (extensionRegistry instanceof ExtensionRegistry) { final ExtensionRegistry.ExtensionInfo extension = - target.findExtensionByNumber((ExtensionRegistry) extensionRegistry, - type, fieldNumber); + target.findExtensionByNumber((ExtensionRegistry) extensionRegistry, type, fieldNumber); if (extension == null) { field = null; } else { field = extension.descriptor; defaultInstance = extension.defaultInstance; - if (defaultInstance == null && - field.getJavaType() - == Descriptors.FieldDescriptor.JavaType.MESSAGE) { + if (defaultInstance == null + && field.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { throw new IllegalStateException( - "Message-typed extension lacked default instance: " + - field.getFullName()); + "Message-typed extension lacked default instance: " + field.getFullName()); } } } else { @@ -779,21 +739,19 @@ class MessageReflection { boolean unknown = false; boolean packed = false; if (field == null) { - unknown = true; // Unknown field. - } else if (wireType == FieldSet.getWireFormatForFieldType( - field.getLiteType(), - false /* isPacked */)) { + unknown = true; // Unknown field. + } else if (wireType + == FieldSet.getWireFormatForFieldType(field.getLiteType(), /* isPacked= */ false)) { packed = false; - } else if (field.isPackable() && - wireType == FieldSet.getWireFormatForFieldType( - field.getLiteType(), - true /* isPacked */)) { + } else if (field.isPackable() + && wireType + == FieldSet.getWireFormatForFieldType(field.getLiteType(), /* isPacked= */ true)) { packed = true; } else { - unknown = true; // Unknown wire type. + unknown = true; // Unknown wire type. } - if (unknown) { // Unknown field or wrong wire type. Skip. + if (unknown) { // Unknown field or wrong wire type. Skip. if (unknownFields != null) { return unknownFields.mergeFieldFrom(tag, input); } else { @@ -808,8 +766,8 @@ class MessageReflection { while (input.getBytesUntilLimit() > 0) { final int rawValue = input.readEnum(); if (field.getFile().supportsUnknownEnumValue()) { - target.addRepeatedField(field, - field.getEnumType().findValueByNumberCreatingIfUnknown(rawValue)); + target.addRepeatedField( + field, field.getEnumType().findValueByNumberCreatingIfUnknown(rawValue)); } else { final Object value = field.getEnumType().findValueByNumber(rawValue); if (value == null) { @@ -822,8 +780,9 @@ class MessageReflection { } } else { while (input.getBytesUntilLimit() > 0) { - final Object value = WireFormat.readPrimitiveField( - input, field.getLiteType(), target.getUtf8Validation(field)); + final Object value = + WireFormat.readPrimitiveField( + input, field.getLiteType(), target.getUtf8Validation(field)); target.addRepeatedField(field, value); } } @@ -831,16 +790,16 @@ class MessageReflection { } else { final Object value; switch (field.getType()) { - case GROUP: { - value = target - .parseGroup(input, extensionRegistry, field, defaultInstance); - break; - } - case MESSAGE: { - value = target - .parseMessage(input, extensionRegistry, field, defaultInstance); - break; - } + case GROUP: + { + value = target.parseGroup(input, extensionRegistry, field, defaultInstance); + break; + } + case MESSAGE: + { + value = target.parseMessage(input, extensionRegistry, field, defaultInstance); + break; + } case ENUM: final int rawValue = input.readEnum(); if (field.getFile().supportsUnknownEnumValue()) { @@ -858,8 +817,9 @@ class MessageReflection { } break; default: - value = WireFormat.readPrimitiveField( - input, field.getLiteType(), target.getUtf8Validation(field)); + value = + WireFormat.readPrimitiveField( + input, field.getLiteType(), target.getUtf8Validation(field)); break; } @@ -873,16 +833,14 @@ class MessageReflection { return true; } - /** - * Called by {@code #mergeFieldFrom()} to parse a MessageSet extension into - * MergeTarget. - */ + /** Called by {@code #mergeFieldFrom()} to parse a MessageSet extension into MergeTarget. */ private static void mergeMessageSetExtensionFromCodedStream( CodedInputStream input, UnknownFieldSet.Builder unknownFields, ExtensionRegistryLite extensionRegistry, Descriptors.Descriptor type, - MergeTarget target) throws IOException { + MergeTarget target) + throws IOException { // The wire format for MessageSet is: // message MessageSet { @@ -921,19 +879,17 @@ class MessageReflection { // extensions of it. Otherwise we will treat the registry as if it // were empty. if (extensionRegistry instanceof ExtensionRegistry) { - extension = target.findExtensionByNumber( - (ExtensionRegistry) extensionRegistry, type, typeId); + extension = + target.findExtensionByNumber((ExtensionRegistry) extensionRegistry, type, typeId); } } } else if (tag == WireFormat.MESSAGE_SET_MESSAGE_TAG) { if (typeId != 0) { - if (extension != null && - ExtensionRegistryLite.isEagerlyParseMessageSets()) { + if (extension != null && ExtensionRegistryLite.isEagerlyParseMessageSets()) { // We already know the type, so we can parse directly from the // input with no copying. Hooray! - eagerlyMergeMessageSetExtension( - input, extension, extensionRegistry, target); + eagerlyMergeMessageSetExtension(input, extension, extensionRegistry, target); rawBytes = null; continue; } @@ -952,12 +908,11 @@ class MessageReflection { // Process the raw bytes. if (rawBytes != null && typeId != 0) { // Zero is not a valid type ID. if (extension != null) { // We known the type - mergeMessageSetExtensionFromBytes( - rawBytes, extension, extensionRegistry, target); + mergeMessageSetExtensionFromBytes(rawBytes, extension, extensionRegistry, target); } else { // We don't know how to parse this. Ignore it. if (rawBytes != null && unknownFields != null) { - unknownFields.mergeField(typeId, UnknownFieldSet.Field.newBuilder() - .addLengthDelimited(rawBytes).build()); + unknownFields.mergeField( + typeId, UnknownFieldSet.Field.newBuilder().addLengthDelimited(rawBytes).build()); } } } @@ -967,20 +922,21 @@ class MessageReflection { ByteString rawBytes, ExtensionRegistry.ExtensionInfo extension, ExtensionRegistryLite extensionRegistry, - MergeTarget target) throws IOException { + MergeTarget target) + throws IOException { Descriptors.FieldDescriptor field = extension.descriptor; boolean hasOriginalValue = target.hasField(field); if (hasOriginalValue || ExtensionRegistryLite.isEagerlyParseMessageSets()) { // If the field already exists, we just parse the field. - Object value = target.parseMessageFromBytes( - rawBytes, extensionRegistry,field, extension.defaultInstance); + Object value = + target.parseMessageFromBytes( + rawBytes, extensionRegistry, field, extension.defaultInstance); target.setField(field, value); } else { // Use LazyField to load MessageSet lazily. - LazyField lazyField = new LazyField( - extension.defaultInstance, extensionRegistry, rawBytes); + LazyField lazyField = new LazyField(extension.defaultInstance, extensionRegistry, rawBytes); target.setField(field, lazyField); } } @@ -989,10 +945,10 @@ class MessageReflection { CodedInputStream input, ExtensionRegistry.ExtensionInfo extension, ExtensionRegistryLite extensionRegistry, - MergeTarget target) throws IOException { + MergeTarget target) + throws IOException { Descriptors.FieldDescriptor field = extension.descriptor; - Object value = target.parseMessage(input, extensionRegistry, field, - extension.defaultInstance); + Object value = target.parseMessage(input, extensionRegistry, field, extension.defaultInstance); target.setField(field, value); } } diff --git a/java/core/src/main/java/com/google/protobuf/MutabilityOracle.java b/java/core/src/main/java/com/google/protobuf/MutabilityOracle.java index 82b723c95d..7c2f157567 100644 --- a/java/core/src/main/java/com/google/protobuf/MutabilityOracle.java +++ b/java/core/src/main/java/com/google/protobuf/MutabilityOracle.java @@ -30,19 +30,16 @@ package com.google.protobuf; -/** - * Verifies that an object is mutable, throwing if not. - */ +/** Verifies that an object is mutable, throwing if not. */ interface MutabilityOracle { - static final MutabilityOracle IMMUTABLE = new MutabilityOracle() { - @Override - public void ensureMutable() { - throw new UnsupportedOperationException(); - } - }; + static final MutabilityOracle IMMUTABLE = + new MutabilityOracle() { + @Override + public void ensureMutable() { + throw new UnsupportedOperationException(); + } + }; - /** - * Throws an {@link UnsupportedOperationException} if not mutable. - */ + /** Throws an {@link UnsupportedOperationException} if not mutable. */ void ensureMutable(); } diff --git a/java/core/src/main/java/com/google/protobuf/NioByteString.java b/java/core/src/main/java/com/google/protobuf/NioByteString.java index 76594809e8..64de6b1b0a 100644 --- a/java/core/src/main/java/com/google/protobuf/NioByteString.java +++ b/java/core/src/main/java/com/google/protobuf/NioByteString.java @@ -44,9 +44,7 @@ import java.nio.charset.Charset; import java.util.Collections; import java.util.List; -/** - * A {@link ByteString} that wraps around a {@link ByteBuffer}. - */ +/** A {@link ByteString} that wraps around a {@link ByteBuffer}. */ final class NioByteString extends ByteString.LeafByteString { private final ByteBuffer buffer; @@ -60,16 +58,12 @@ final class NioByteString extends ByteString.LeafByteString { // ================================================================= // Serializable - /** - * Magic method that lets us override serialization behavior. - */ + /** Magic method that lets us override serialization behavior. */ private Object writeReplace() { return ByteString.copyFrom(buffer.slice()); } - /** - * Magic method that lets us override deserialization behavior. - */ + /** Magic method that lets us override deserialization behavior. */ private void readObject(@SuppressWarnings("unused") ObjectInputStream in) throws IOException { throw new InvalidObjectException("NioByteString instances are not to be serialized directly"); } diff --git a/java/core/src/main/java/com/google/protobuf/Parser.java b/java/core/src/main/java/com/google/protobuf/Parser.java index e07c68959a..259b5a68df 100644 --- a/java/core/src/main/java/com/google/protobuf/Parser.java +++ b/java/core/src/main/java/com/google/protobuf/Parser.java @@ -36,7 +36,7 @@ import java.nio.ByteBuffer; /** * Abstract interface for parsing Protocol Messages. * - * The implementation should be stateless and thread-safe. + *

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

All methods may throw {@link InvalidProtocolBufferException}. In the event of invalid data, * like an encoding error, the cause of the thrown exception will be {@code null}. However, if an @@ -55,39 +55,31 @@ public interface Parser { /** * Parses a message of {@code MessageType} from the input. * - *

Note: The caller should call - * {@link CodedInputStream#checkLastTagWas(int)} after calling this to - * verify that the last tag seen was the appropriate end-group tag, - * or zero for EOF. + *

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

- * Despite usually reading the entire input, this does not close the stream. + * Parse a message of {@code MessageType} from {@code input}. This is just a small wrapper around + * {@link #parseFrom(CodedInputStream)}. Note that this method always reads the entire + * input (unless it throws an exception). If you want it to stop earlier, you will need to wrap + * your input in some wrapper stream that limits reading. Or, use {@link + * MessageLite#writeDelimitedTo(java.io.OutputStream)} to write your message and {@link + * #parseDelimitedFrom(InputStream)} to read it. + * + *

Despite usually reading the entire input, this does not close the stream. */ - public MessageType parseFrom(InputStream input) - throws InvalidProtocolBufferException; + public MessageType parseFrom(InputStream input) throws InvalidProtocolBufferException; /** - * Parses a message of {@code MessageType} from {@code input}. - * This is just a small wrapper around + * Parses a message of {@code MessageType} from {@code input}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}. */ - public MessageType parseFrom(InputStream input, - ExtensionRegistryLite extensionRegistry) + public MessageType parseFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** - * Like {@link #parseFrom(InputStream)}, but does not throw an - * exception if the message is missing required fields. Instead, a partial - * message is returned. + * Like {@link #parseFrom(InputStream)}, but does not throw an exception if the message is missing + * required fields. Instead, a partial message is returned. */ - public MessageType parsePartialFrom(InputStream input) - throws InvalidProtocolBufferException; + public MessageType parsePartialFrom(InputStream input) throws InvalidProtocolBufferException; /** - * Like {@link #parseFrom(InputStream, ExtensionRegistryLite)}, - * but does not throw an exception if the message is missing required fields. - * Instead, a partial message is returned. + * Like {@link #parseFrom(InputStream, ExtensionRegistryLite)}, but does not throw an exception if + * the message is missing required fields. Instead, a partial message is returned. */ - public MessageType parsePartialFrom(InputStream input, - ExtensionRegistryLite extensionRegistry) + public MessageType parsePartialFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** - * Like {@link #parseFrom(InputStream)}, but does not read util EOF. - * Instead, the size of message (encoded as a varint) is read first, - * then the message data. Use - * {@link MessageLite#writeDelimitedTo(java.io.OutputStream)} to write - * messages in this format. + * Like {@link #parseFrom(InputStream)}, but does not read util EOF. Instead, the size of message + * (encoded as a varint) is read first, then the message data. Use {@link + * MessageLite#writeDelimitedTo(java.io.OutputStream)} to write messages in this format. * - * @return Parsed message if successful, or null if the stream is at EOF when - * the method starts. Any other error (including reaching EOF during - * parsing) will cause an exception to be thrown. + * @return Parsed message if successful, or null if the stream is at EOF when the method starts. + * Any other error (including reaching EOF during parsing) will cause an exception to be + * thrown. */ - public MessageType parseDelimitedFrom(InputStream input) - throws InvalidProtocolBufferException; + public MessageType parseDelimitedFrom(InputStream input) throws InvalidProtocolBufferException; - /** - * Like {@link #parseDelimitedFrom(InputStream)} but supporting extensions. - */ - public MessageType parseDelimitedFrom(InputStream input, - ExtensionRegistryLite extensionRegistry) + /** Like {@link #parseDelimitedFrom(InputStream)} but supporting extensions. */ + public MessageType parseDelimitedFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** - * Like {@link #parseDelimitedFrom(InputStream)}, but does not throw an - * exception if the message is missing required fields. Instead, a partial - * message is returned. + * Like {@link #parseDelimitedFrom(InputStream)}, but does not throw an exception if the message + * is missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialDelimitedFrom(InputStream input) throws InvalidProtocolBufferException; /** - * Like {@link #parseDelimitedFrom(InputStream, ExtensionRegistryLite)}, - * but does not throw an exception if the message is missing required fields. - * Instead, a partial message is returned. + * Like {@link #parseDelimitedFrom(InputStream, ExtensionRegistryLite)}, but does not throw an + * exception if the message is missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialDelimitedFrom( - InputStream input, - ExtensionRegistryLite extensionRegistry) + InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; } diff --git a/java/core/src/main/java/com/google/protobuf/ProtobufArrayList.java b/java/core/src/main/java/com/google/protobuf/ProtobufArrayList.java index 81255ec291..9834161382 100644 --- a/java/core/src/main/java/com/google/protobuf/ProtobufArrayList.java +++ b/java/core/src/main/java/com/google/protobuf/ProtobufArrayList.java @@ -31,31 +31,29 @@ package com.google.protobuf; import com.google.protobuf.Internal.ProtobufList; - import java.util.ArrayList; import java.util.List; -/** - * Implements {@link ProtobufList} for non-primitive and {@link String} types. - */ +/** Implements {@link ProtobufList} for non-primitive and {@link String} types. */ final class ProtobufArrayList extends AbstractProtobufList { private static final ProtobufArrayList EMPTY_LIST = new ProtobufArrayList(); + static { EMPTY_LIST.makeImmutable(); } - + @SuppressWarnings("unchecked") // Guaranteed safe by runtime. public static ProtobufArrayList emptyList() { return (ProtobufArrayList) EMPTY_LIST; } - + private final List list; ProtobufArrayList() { this(new ArrayList(DEFAULT_CAPACITY)); } - + private ProtobufArrayList(List list) { this.list = list; } @@ -69,7 +67,7 @@ final class ProtobufArrayList extends AbstractProtobufList { newList.addAll(list); return new ProtobufArrayList(newList); } - + @Override public void add(int index, E element) { ensureIsMutable(); @@ -81,7 +79,7 @@ final class ProtobufArrayList extends AbstractProtobufList { public E get(int index) { return list.get(index); } - + @Override public E remove(int index) { ensureIsMutable(); @@ -89,7 +87,7 @@ final class ProtobufArrayList extends AbstractProtobufList { modCount++; return toReturn; } - + @Override public E set(int index, E element) { ensureIsMutable(); diff --git a/java/core/src/main/java/com/google/protobuf/ProtocolMessageEnum.java b/java/core/src/main/java/com/google/protobuf/ProtocolMessageEnum.java index a596d30190..5d6f5ac442 100644 --- a/java/core/src/main/java/com/google/protobuf/ProtocolMessageEnum.java +++ b/java/core/src/main/java/com/google/protobuf/ProtocolMessageEnum.java @@ -33,27 +33,20 @@ package com.google.protobuf; import com.google.protobuf.Descriptors.EnumDescriptor; import com.google.protobuf.Descriptors.EnumValueDescriptor; -/** - * Interface of useful methods added to all enums generated by the protocol - * compiler. - */ +/** Interface of useful methods added to all enums generated by the protocol compiler. */ public interface ProtocolMessageEnum extends Internal.EnumLite { - /** - * Return the value's numeric value as defined in the .proto file. - */ + /** Return the value's numeric value as defined in the .proto file. */ @Override int getNumber(); /** - * Return the value's descriptor, which contains information such as - * value name, number, and type. + * Return the value's descriptor, which contains information such as value name, number, and type. */ EnumValueDescriptor getValueDescriptor(); /** - * Return the enum type's descriptor, which contains information - * about each defined value, etc. + * Return the enum type's descriptor, which contains information about each defined value, etc. */ EnumDescriptor getDescriptorForType(); } diff --git a/java/core/src/main/java/com/google/protobuf/ProtocolStringList.java b/java/core/src/main/java/com/google/protobuf/ProtocolStringList.java index d553b41e52..5df3dbdbda 100644 --- a/java/core/src/main/java/com/google/protobuf/ProtocolStringList.java +++ b/java/core/src/main/java/com/google/protobuf/ProtocolStringList.java @@ -33,16 +33,14 @@ package com.google.protobuf; import java.util.List; /** - * An interface extending {@code List} used for repeated string fields - * to provide optional access to the data as a list of ByteStrings. The - * underlying implementation stores values as either ByteStrings or Strings - * (see {@link LazyStringArrayList}) depending on how the value was initialized - * or last read, and it is often more efficient to deal with lists of - * ByteStrings when handling protos that have been deserialized from bytes. + * An interface extending {@code List} used for repeated string fields to provide optional + * access to the data as a list of ByteStrings. The underlying implementation stores values as + * either ByteStrings or Strings (see {@link LazyStringArrayList}) depending on how the value was + * initialized or last read, and it is often more efficient to deal with lists of ByteStrings when + * handling protos that have been deserialized from bytes. */ public interface ProtocolStringList extends List { /** Returns a view of the data as a list of ByteStrings. */ List asByteStringList(); - } diff --git a/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilder.java b/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilder.java index b593b56653..f3b09fbacc 100644 --- a/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilder.java +++ b/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilder.java @@ -39,36 +39,29 @@ import java.util.Collections; import java.util.List; /** - * {@code RepeatedFieldBuilder} implements a structure that a protocol - * message uses to hold a repeated field of other protocol messages. It supports - * the classical use case of adding immutable {@link Message}'s to the - * repeated field and is highly optimized around this (no extra memory - * allocations and sharing of immutable arrays). - *
- * It also supports the additional use case of adding a {@link Message.Builder} - * to the repeated field and deferring conversion of that {@code Builder} - * to an immutable {@code Message}. In this way, it's possible to maintain - * a tree of {@code Builder}'s that acts as a fully read/write data - * structure. - *
- * Logically, one can think of a tree of builders as converting the entire tree - * to messages when build is called on the root or when any method is called - * that desires a Message instead of a Builder. In terms of the implementation, - * the {@code SingleFieldBuilder} and {@code RepeatedFieldBuilder} - * classes cache messages that were created so that messages only need to be - * created when some change occurred in its builder or a builder for one of its - * descendants. + * {@code RepeatedFieldBuilder} implements a structure that a protocol message uses to hold a + * repeated field of other protocol messages. It supports the classical use case of adding immutable + * {@link Message}'s to the repeated field and is highly optimized around this (no extra memory + * allocations and sharing of immutable arrays).
+ * It also supports the additional use case of adding a {@link Message.Builder} to the repeated + * field and deferring conversion of that {@code Builder} to an immutable {@code Message}. In this + * way, it's possible to maintain a tree of {@code Builder}'s that acts as a fully read/write data + * structure.
+ * Logically, one can think of a tree of builders as converting the entire tree to messages when + * build is called on the root or when any method is called that desires a Message instead of a + * Builder. In terms of the implementation, the {@code SingleFieldBuilder} and {@code + * RepeatedFieldBuilder} classes cache messages that were created so that messages only need to be + * created when some change occurred in its builder or a builder for one of its descendants. * * @param the type of message for the field * @param the type of builder for the field * @param the common interface for the message and the builder - * * @author jonp@google.com (Jon Perlow) */ -public class RepeatedFieldBuilder - +public class RepeatedFieldBuilder< + MType extends GeneratedMessage, + BType extends GeneratedMessage.Builder, + IType extends MessageOrBuilder> implements GeneratedMessage.BuilderParent { // Parent to send changes to. @@ -120,8 +113,7 @@ public class RepeatedFieldBuilder // is fully backed by this object and all changes are reflected in it. // Access to any item returns either a builder or message depending on // what is most efficient. - private MessageOrBuilderExternalList - externalMessageOrBuilderList; + private MessageOrBuilderExternalList externalMessageOrBuilderList; /** * Constructs a new builder with an empty list of messages. @@ -148,8 +140,8 @@ public class RepeatedFieldBuilder } /** - * Ensures that the list of messages is mutable so it can be updated. If it's - * immutable, a copy is made. + * Ensures that the list of messages is mutable so it can be updated. If it's immutable, a copy is + * made. */ private void ensureMutableMessageList() { if (!isMessagesListMutable) { @@ -159,15 +151,12 @@ public class RepeatedFieldBuilder } /** - * Ensures that the list of builders is not null. If it's null, the list is - * created and initialized to be the same size as the messages list with - * null entries. + * Ensures that the list of builders is not null. If it's null, the list is created and + * initialized to be the same size as the messages list with null entries. */ private void ensureBuilders() { if (this.builders == null) { - this.builders = - new ArrayList>( - messages.size()); + this.builders = new ArrayList>(messages.size()); for (int i = 0; i < messages.size(); i++) { builders.add(null); } @@ -193,9 +182,9 @@ public class RepeatedFieldBuilder } /** - * Get the message at the specified index. If the message is currently stored - * as a {@code Builder}, it is converted to a {@code Message} by - * calling {@link Message.Builder#buildPartial} on it. + * Get the message at the specified index. If the message is currently stored as a {@code + * Builder}, it is converted to a {@code Message} by calling {@link Message.Builder#buildPartial} + * on it. * * @param index the index of the message to get * @return the message for the specified index @@ -205,13 +194,13 @@ public class RepeatedFieldBuilder } /** - * Get the message at the specified index. If the message is currently stored - * as a {@code Builder}, it is converted to a {@code Message} by - * calling {@link Message.Builder#buildPartial} on it. + * Get the message at the specified index. If the message is currently stored as a {@code + * Builder}, it is converted to a {@code Message} by calling {@link Message.Builder#buildPartial} + * on it. * * @param index the index of the message to get - * @param forBuild this is being called for build so we want to make sure - * we SingleFieldBuilder.build to send dirty invalidations + * @param forBuild this is being called for build so we want to make sure we + * SingleFieldBuilder.build to send dirty invalidations * @return the message for the specified index */ private MType getMessage(int index, boolean forBuild) { @@ -235,9 +224,8 @@ public class RepeatedFieldBuilder } /** - * Gets a builder for the specified index. If no builder has been created for - * that index, a builder is created on demand by calling - * {@link Message#toBuilder}. + * Gets a builder for the specified index. If no builder has been created for that index, a + * builder is created on demand by calling {@link Message#toBuilder}. * * @param index the index of the message to get * @return The builder for that index @@ -247,16 +235,15 @@ public class RepeatedFieldBuilder SingleFieldBuilder builder = builders.get(index); if (builder == null) { MType message = messages.get(index); - builder = new SingleFieldBuilder( - message, this, isClean); + builder = new SingleFieldBuilder(message, this, isClean); builders.set(index, builder); } return builder.getBuilder(); } /** - * Gets the base class interface for the specified index. This may either be - * a builder or a message. It will return whatever is more efficient. + * Gets the base class interface for the specified index. This may either be a builder or a + * message. It will return whatever is more efficient. * * @param index the index of the message to get * @return the message or builder for the index as the base class interface @@ -283,21 +270,18 @@ public class RepeatedFieldBuilder } /** - * Sets a message at the specified index replacing the existing item at - * that index. + * Sets a message at the specified index replacing the existing item at that index. * * @param index the index to set. * @param message the message to set * @return the builder */ - public RepeatedFieldBuilder setMessage( - int index, MType message) { + public RepeatedFieldBuilder setMessage(int index, MType message) { checkNotNull(message); ensureMutableMessageList(); messages.set(index, message); if (builders != null) { - SingleFieldBuilder entry = - builders.set(index, null); + SingleFieldBuilder entry = builders.set(index, null); if (entry != null) { entry.dispose(); } @@ -313,8 +297,7 @@ public class RepeatedFieldBuilder * @param message the message to add * @return the builder */ - public RepeatedFieldBuilder addMessage( - MType message) { + public RepeatedFieldBuilder addMessage(MType message) { checkNotNull(message); ensureMutableMessageList(); messages.add(message); @@ -327,16 +310,15 @@ public class RepeatedFieldBuilder } /** - * Inserts the specified message at the specified position in this list. - * Shifts the element currently at that position (if any) and any subsequent - * elements to the right (adds one to their indices). + * Inserts the specified message at the specified position in this list. Shifts the element + * currently at that position (if any) and any subsequent elements to the right (adds one to their + * indices). * * @param index the index at which to insert the message * @param message the message to add * @return the builder */ - public RepeatedFieldBuilder addMessage( - int index, MType message) { + public RepeatedFieldBuilder addMessage(int index, MType message) { checkNotNull(message); ensureMutableMessageList(); messages.add(index, message); @@ -349,9 +331,8 @@ public class RepeatedFieldBuilder } /** - * Appends all of the messages in the specified collection to the end of - * this list, in the order that they are returned by the specified - * collection's iterator. + * Appends all of the messages in the specified collection to the end of this list, in the order + * that they are returned by the specified collection's iterator. * * @param values the messages to add * @return the builder @@ -365,8 +346,8 @@ public class RepeatedFieldBuilder // If we can inspect the size, we can more efficiently add messages. int size = -1; if (values instanceof Collection) { - @SuppressWarnings("unchecked") final - Collection collection = (Collection) values; + @SuppressWarnings("unchecked") + final Collection collection = (Collection) values; if (collection.size() == 0) { return this; } @@ -375,8 +356,7 @@ public class RepeatedFieldBuilder ensureMutableMessageList(); if (size >= 0 && messages instanceof ArrayList) { - ((ArrayList) messages) - .ensureCapacity(messages.size() + size); + ((ArrayList) messages).ensureCapacity(messages.size() + size); } for (MType value : values) { @@ -398,8 +378,7 @@ public class RepeatedFieldBuilder ensureMutableMessageList(); ensureBuilders(); SingleFieldBuilder builder = - new SingleFieldBuilder( - message, this, isClean); + new SingleFieldBuilder(message, this, isClean); messages.add(null); builders.add(builder); onChanged(); @@ -408,9 +387,8 @@ public class RepeatedFieldBuilder } /** - * Inserts a new builder at the specified position in this list. - * Shifts the element currently at that position (if any) and any subsequent - * elements to the right (adds one to their indices). + * Inserts a new builder at the specified position in this list. Shifts the element currently at + * that position (if any) and any subsequent elements to the right (adds one to their indices). * * @param index the index at which to insert the builder * @param message the message to add which is the basis of the builder @@ -420,8 +398,7 @@ public class RepeatedFieldBuilder ensureMutableMessageList(); ensureBuilders(); SingleFieldBuilder builder = - new SingleFieldBuilder( - message, this, isClean); + new SingleFieldBuilder(message, this, isClean); messages.add(index, null); builders.add(index, builder); onChanged(); @@ -430,9 +407,9 @@ public class RepeatedFieldBuilder } /** - * Removes the element at the specified position in this list. Shifts any - * subsequent elements to the left (subtracts one from their indices). - * Returns the element that was removed from the list. + * Removes the element at the specified position in this list. Shifts any subsequent elements to + * the left (subtracts one from their indices). Returns the element that was removed from the + * list. * * @param index the index at which to remove the message */ @@ -440,8 +417,7 @@ public class RepeatedFieldBuilder ensureMutableMessageList(); messages.remove(index); if (builders != null) { - SingleFieldBuilder entry = - builders.remove(index); + SingleFieldBuilder entry = builders.remove(index); if (entry != null) { entry.dispose(); } @@ -450,16 +426,12 @@ public class RepeatedFieldBuilder incrementModCounts(); } - /** - * Removes all of the elements from this list. - * The list will be empty after this call returns. - */ + /** Removes all of the elements from this list. The list will be empty after this call returns. */ public void clear() { messages = Collections.emptyList(); isMessagesListMutable = false; if (builders != null) { - for (SingleFieldBuilder entry : - builders) { + for (SingleFieldBuilder entry : builders) { if (entry != null) { entry.dispose(); } @@ -519,50 +491,47 @@ public class RepeatedFieldBuilder } /** - * Gets a view of the builder as a list of messages. The returned list is live - * and will reflect any changes to the underlying builder. + * Gets a view of the builder as a list of messages. The returned list is live and will reflect + * any changes to the underlying builder. * * @return the messages in the list */ public List getMessageList() { if (externalMessageList == null) { - externalMessageList = - new MessageExternalList(this); + externalMessageList = new MessageExternalList(this); } return externalMessageList; } /** - * Gets a view of the builder as a list of builders. This returned list is - * live and will reflect any changes to the underlying builder. + * Gets a view of the builder as a list of builders. This returned list is live and will reflect + * any changes to the underlying builder. * * @return the builders in the list */ public List getBuilderList() { if (externalBuilderList == null) { - externalBuilderList = - new BuilderExternalList(this); + externalBuilderList = new BuilderExternalList(this); } return externalBuilderList; } /** - * Gets a view of the builder as a list of MessageOrBuilders. This returned - * list is live and will reflect any changes to the underlying builder. + * Gets a view of the builder as a list of MessageOrBuilders. This returned list is live and will + * reflect any changes to the underlying builder. * * @return the builders in the list */ public List getMessageOrBuilderList() { if (externalMessageOrBuilderList == null) { - externalMessageOrBuilderList = - new MessageOrBuilderExternalList(this); + externalMessageOrBuilderList = new MessageOrBuilderExternalList(this); } return externalMessageOrBuilderList; } /** - * 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. */ private void onChanged() { if (isClean && parent != null) { @@ -579,9 +548,8 @@ public class RepeatedFieldBuilder } /** - * Increments the mod counts so that an ConcurrentModificationException can - * be thrown if calling code tries to modify the builder while its iterating - * the list. + * Increments the mod counts so that an ConcurrentModificationException can be thrown if calling + * code tries to modify the builder while its iterating the list. */ private void incrementModCounts() { if (externalMessageList != null) { @@ -603,15 +571,14 @@ public class RepeatedFieldBuilder * @param the common interface for the message and the builder */ private static class MessageExternalList< - MType extends GeneratedMessage, - BType extends GeneratedMessage.Builder, - IType extends MessageOrBuilder> + MType extends GeneratedMessage, + BType extends GeneratedMessage.Builder, + IType extends MessageOrBuilder> extends AbstractList implements List { RepeatedFieldBuilder builder; - MessageExternalList( - RepeatedFieldBuilder builder) { + MessageExternalList(RepeatedFieldBuilder builder) { this.builder = builder; } @@ -638,15 +605,14 @@ public class RepeatedFieldBuilder * @param the common interface for the message and the builder */ private static class BuilderExternalList< - MType extends GeneratedMessage, - BType extends GeneratedMessage.Builder, - IType extends MessageOrBuilder> + MType extends GeneratedMessage, + BType extends GeneratedMessage.Builder, + IType extends MessageOrBuilder> extends AbstractList implements List { RepeatedFieldBuilder builder; - BuilderExternalList( - RepeatedFieldBuilder builder) { + BuilderExternalList(RepeatedFieldBuilder builder) { this.builder = builder; } @@ -673,15 +639,14 @@ public class RepeatedFieldBuilder * @param the common interface for the message and the builder */ private static class MessageOrBuilderExternalList< - MType extends GeneratedMessage, - BType extends GeneratedMessage.Builder, - IType extends MessageOrBuilder> + MType extends GeneratedMessage, + BType extends GeneratedMessage.Builder, + IType extends MessageOrBuilder> extends AbstractList implements List { RepeatedFieldBuilder builder; - MessageOrBuilderExternalList( - RepeatedFieldBuilder builder) { + MessageOrBuilderExternalList(RepeatedFieldBuilder builder) { this.builder = builder; } diff --git a/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java b/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java index 30c991d40b..fb1667c4c6 100644 --- a/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java +++ b/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java @@ -39,36 +39,29 @@ import java.util.Collections; import java.util.List; /** - * {@code RepeatedFieldBuilderV3} implements a structure that a protocol - * message uses to hold a repeated field of other protocol messages. It supports - * the classical use case of adding immutable {@link Message}'s to the - * repeated field and is highly optimized around this (no extra memory - * allocations and sharing of immutable arrays). - *
- * It also supports the additional use case of adding a {@link Message.Builder} - * to the repeated field and deferring conversion of that {@code Builder} - * to an immutable {@code Message}. In this way, it's possible to maintain - * a tree of {@code Builder}'s that acts as a fully read/write data - * structure. - *
- * Logically, one can think of a tree of builders as converting the entire tree - * to messages when build is called on the root or when any method is called - * that desires a Message instead of a Builder. In terms of the implementation, - * the {@code SingleFieldBuilderV3} and {@code RepeatedFieldBuilderV3} - * classes cache messages that were created so that messages only need to be - * created when some change occurred in its builder or a builder for one of its - * descendants. + * {@code RepeatedFieldBuilderV3} implements a structure that a protocol message uses to hold a + * repeated field of other protocol messages. It supports the classical use case of adding immutable + * {@link Message}'s to the repeated field and is highly optimized around this (no extra memory + * allocations and sharing of immutable arrays).
+ * It also supports the additional use case of adding a {@link Message.Builder} to the repeated + * field and deferring conversion of that {@code Builder} to an immutable {@code Message}. In this + * way, it's possible to maintain a tree of {@code Builder}'s that acts as a fully read/write data + * structure.
+ * Logically, one can think of a tree of builders as converting the entire tree to messages when + * build is called on the root or when any method is called that desires a Message instead of a + * Builder. In terms of the implementation, the {@code SingleFieldBuilderV3} and {@code + * RepeatedFieldBuilderV3} classes cache messages that were created so that messages only need to be + * created when some change occurred in its builder or a builder for one of its descendants. * * @param the type of message for the field * @param the type of builder for the field * @param the common interface for the message and the builder - * * @author jonp@google.com (Jon Perlow) */ -public class RepeatedFieldBuilderV3 - +public class RepeatedFieldBuilderV3< + MType extends AbstractMessage, + BType extends AbstractMessage.Builder, + IType extends MessageOrBuilder> implements AbstractMessage.BuilderParent { // Parent to send changes to. @@ -120,8 +113,7 @@ public class RepeatedFieldBuilderV3 // is fully backed by this object and all changes are reflected in it. // Access to any item returns either a builder or message depending on // what is most efficient. - private MessageOrBuilderExternalList - externalMessageOrBuilderList; + private MessageOrBuilderExternalList externalMessageOrBuilderList; /** * Constructs a new builder with an empty list of messages. @@ -148,8 +140,8 @@ public class RepeatedFieldBuilderV3 } /** - * Ensures that the list of messages is mutable so it can be updated. If it's - * immutable, a copy is made. + * Ensures that the list of messages is mutable so it can be updated. If it's immutable, a copy is + * made. */ private void ensureMutableMessageList() { if (!isMessagesListMutable) { @@ -159,15 +151,12 @@ public class RepeatedFieldBuilderV3 } /** - * Ensures that the list of builders is not null. If it's null, the list is - * created and initialized to be the same size as the messages list with - * null entries. + * Ensures that the list of builders is not null. If it's null, the list is created and + * initialized to be the same size as the messages list with null entries. */ private void ensureBuilders() { if (this.builders == null) { - this.builders = - new ArrayList>( - messages.size()); + this.builders = new ArrayList>(messages.size()); for (int i = 0; i < messages.size(); i++) { builders.add(null); } @@ -193,9 +182,9 @@ public class RepeatedFieldBuilderV3 } /** - * Get the message at the specified index. If the message is currently stored - * as a {@code Builder}, it is converted to a {@code Message} by - * calling {@link Message.Builder#buildPartial} on it. + * Get the message at the specified index. If the message is currently stored as a {@code + * Builder}, it is converted to a {@code Message} by calling {@link Message.Builder#buildPartial} + * on it. * * @param index the index of the message to get * @return the message for the specified index @@ -205,13 +194,13 @@ public class RepeatedFieldBuilderV3 } /** - * Get the message at the specified index. If the message is currently stored - * as a {@code Builder}, it is converted to a {@code Message} by - * calling {@link Message.Builder#buildPartial} on it. + * Get the message at the specified index. If the message is currently stored as a {@code + * Builder}, it is converted to a {@code Message} by calling {@link Message.Builder#buildPartial} + * on it. * * @param index the index of the message to get - * @param forBuild this is being called for build so we want to make sure - * we SingleFieldBuilderV3.build to send dirty invalidations + * @param forBuild this is being called for build so we want to make sure we + * SingleFieldBuilderV3.build to send dirty invalidations * @return the message for the specified index */ private MType getMessage(int index, boolean forBuild) { @@ -235,9 +224,8 @@ public class RepeatedFieldBuilderV3 } /** - * Gets a builder for the specified index. If no builder has been created for - * that index, a builder is created on demand by calling - * {@link Message#toBuilder}. + * Gets a builder for the specified index. If no builder has been created for that index, a + * builder is created on demand by calling {@link Message#toBuilder}. * * @param index the index of the message to get * @return The builder for that index @@ -247,16 +235,15 @@ public class RepeatedFieldBuilderV3 SingleFieldBuilderV3 builder = builders.get(index); if (builder == null) { MType message = messages.get(index); - builder = new SingleFieldBuilderV3( - message, this, isClean); + builder = new SingleFieldBuilderV3(message, this, isClean); builders.set(index, builder); } return builder.getBuilder(); } /** - * Gets the base class interface for the specified index. This may either be - * a builder or a message. It will return whatever is more efficient. + * Gets the base class interface for the specified index. This may either be a builder or a + * message. It will return whatever is more efficient. * * @param index the index of the message to get * @return the message or builder for the index as the base class interface @@ -283,21 +270,18 @@ public class RepeatedFieldBuilderV3 } /** - * Sets a message at the specified index replacing the existing item at - * that index. + * Sets a message at the specified index replacing the existing item at that index. * * @param index the index to set. * @param message the message to set * @return the builder */ - public RepeatedFieldBuilderV3 setMessage( - int index, MType message) { + public RepeatedFieldBuilderV3 setMessage(int index, MType message) { checkNotNull(message); ensureMutableMessageList(); messages.set(index, message); if (builders != null) { - SingleFieldBuilderV3 entry = - builders.set(index, null); + SingleFieldBuilderV3 entry = builders.set(index, null); if (entry != null) { entry.dispose(); } @@ -313,8 +297,7 @@ public class RepeatedFieldBuilderV3 * @param message the message to add * @return the builder */ - public RepeatedFieldBuilderV3 addMessage( - MType message) { + public RepeatedFieldBuilderV3 addMessage(MType message) { checkNotNull(message); ensureMutableMessageList(); messages.add(message); @@ -327,16 +310,15 @@ public class RepeatedFieldBuilderV3 } /** - * Inserts the specified message at the specified position in this list. - * Shifts the element currently at that position (if any) and any subsequent - * elements to the right (adds one to their indices). + * Inserts the specified message at the specified position in this list. Shifts the element + * currently at that position (if any) and any subsequent elements to the right (adds one to their + * indices). * * @param index the index at which to insert the message * @param message the message to add * @return the builder */ - public RepeatedFieldBuilderV3 addMessage( - int index, MType message) { + public RepeatedFieldBuilderV3 addMessage(int index, MType message) { checkNotNull(message); ensureMutableMessageList(); messages.add(index, message); @@ -349,9 +331,8 @@ public class RepeatedFieldBuilderV3 } /** - * Appends all of the messages in the specified collection to the end of - * this list, in the order that they are returned by the specified - * collection's iterator. + * Appends all of the messages in the specified collection to the end of this list, in the order + * that they are returned by the specified collection's iterator. * * @param values the messages to add * @return the builder @@ -365,8 +346,8 @@ public class RepeatedFieldBuilderV3 // If we can inspect the size, we can more efficiently add messages. int size = -1; if (values instanceof Collection) { - @SuppressWarnings("unchecked") final - Collection collection = (Collection) values; + @SuppressWarnings("unchecked") + final Collection collection = (Collection) values; if (collection.size() == 0) { return this; } @@ -375,8 +356,7 @@ public class RepeatedFieldBuilderV3 ensureMutableMessageList(); if (size >= 0 && messages instanceof ArrayList) { - ((ArrayList) messages) - .ensureCapacity(messages.size() + size); + ((ArrayList) messages).ensureCapacity(messages.size() + size); } for (MType value : values) { @@ -398,8 +378,7 @@ public class RepeatedFieldBuilderV3 ensureMutableMessageList(); ensureBuilders(); SingleFieldBuilderV3 builder = - new SingleFieldBuilderV3( - message, this, isClean); + new SingleFieldBuilderV3(message, this, isClean); messages.add(null); builders.add(builder); onChanged(); @@ -408,9 +387,8 @@ public class RepeatedFieldBuilderV3 } /** - * Inserts a new builder at the specified position in this list. - * Shifts the element currently at that position (if any) and any subsequent - * elements to the right (adds one to their indices). + * Inserts a new builder at the specified position in this list. Shifts the element currently at + * that position (if any) and any subsequent elements to the right (adds one to their indices). * * @param index the index at which to insert the builder * @param message the message to add which is the basis of the builder @@ -420,8 +398,7 @@ public class RepeatedFieldBuilderV3 ensureMutableMessageList(); ensureBuilders(); SingleFieldBuilderV3 builder = - new SingleFieldBuilderV3( - message, this, isClean); + new SingleFieldBuilderV3(message, this, isClean); messages.add(index, null); builders.add(index, builder); onChanged(); @@ -430,9 +407,9 @@ public class RepeatedFieldBuilderV3 } /** - * Removes the element at the specified position in this list. Shifts any - * subsequent elements to the left (subtracts one from their indices). - * Returns the element that was removed from the list. + * Removes the element at the specified position in this list. Shifts any subsequent elements to + * the left (subtracts one from their indices). Returns the element that was removed from the + * list. * * @param index the index at which to remove the message */ @@ -440,8 +417,7 @@ public class RepeatedFieldBuilderV3 ensureMutableMessageList(); messages.remove(index); if (builders != null) { - SingleFieldBuilderV3 entry = - builders.remove(index); + SingleFieldBuilderV3 entry = builders.remove(index); if (entry != null) { entry.dispose(); } @@ -450,16 +426,12 @@ public class RepeatedFieldBuilderV3 incrementModCounts(); } - /** - * Removes all of the elements from this list. - * The list will be empty after this call returns. - */ + /** Removes all of the elements from this list. The list will be empty after this call returns. */ public void clear() { messages = Collections.emptyList(); isMessagesListMutable = false; if (builders != null) { - for (SingleFieldBuilderV3 entry : - builders) { + for (SingleFieldBuilderV3 entry : builders) { if (entry != null) { entry.dispose(); } @@ -519,50 +491,47 @@ public class RepeatedFieldBuilderV3 } /** - * Gets a view of the builder as a list of messages. The returned list is live - * and will reflect any changes to the underlying builder. + * Gets a view of the builder as a list of messages. The returned list is live and will reflect + * any changes to the underlying builder. * * @return the messages in the list */ public List getMessageList() { if (externalMessageList == null) { - externalMessageList = - new MessageExternalList(this); + externalMessageList = new MessageExternalList(this); } return externalMessageList; } /** - * Gets a view of the builder as a list of builders. This returned list is - * live and will reflect any changes to the underlying builder. + * Gets a view of the builder as a list of builders. This returned list is live and will reflect + * any changes to the underlying builder. * * @return the builders in the list */ public List getBuilderList() { if (externalBuilderList == null) { - externalBuilderList = - new BuilderExternalList(this); + externalBuilderList = new BuilderExternalList(this); } return externalBuilderList; } /** - * Gets a view of the builder as a list of MessageOrBuilders. This returned - * list is live and will reflect any changes to the underlying builder. + * Gets a view of the builder as a list of MessageOrBuilders. This returned list is live and will + * reflect any changes to the underlying builder. * * @return the builders in the list */ public List getMessageOrBuilderList() { if (externalMessageOrBuilderList == null) { - externalMessageOrBuilderList = - new MessageOrBuilderExternalList(this); + externalMessageOrBuilderList = new MessageOrBuilderExternalList(this); } return externalMessageOrBuilderList; } /** - * 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. */ private void onChanged() { if (isClean && parent != null) { @@ -579,9 +548,8 @@ public class RepeatedFieldBuilderV3 } /** - * Increments the mod counts so that an ConcurrentModificationException can - * be thrown if calling code tries to modify the builder while its iterating - * the list. + * Increments the mod counts so that an ConcurrentModificationException can be thrown if calling + * code tries to modify the builder while its iterating the list. */ private void incrementModCounts() { if (externalMessageList != null) { @@ -603,15 +571,14 @@ public class RepeatedFieldBuilderV3 * @param the common interface for the message and the builder */ private static class MessageExternalList< - MType extends AbstractMessage, - BType extends AbstractMessage.Builder, - IType extends MessageOrBuilder> + MType extends AbstractMessage, + BType extends AbstractMessage.Builder, + IType extends MessageOrBuilder> extends AbstractList implements List { RepeatedFieldBuilderV3 builder; - MessageExternalList( - RepeatedFieldBuilderV3 builder) { + MessageExternalList(RepeatedFieldBuilderV3 builder) { this.builder = builder; } @@ -638,15 +605,14 @@ public class RepeatedFieldBuilderV3 * @param the common interface for the message and the builder */ private static class BuilderExternalList< - MType extends AbstractMessage, - BType extends AbstractMessage.Builder, - IType extends MessageOrBuilder> + MType extends AbstractMessage, + BType extends AbstractMessage.Builder, + IType extends MessageOrBuilder> extends AbstractList implements List { RepeatedFieldBuilderV3 builder; - BuilderExternalList( - RepeatedFieldBuilderV3 builder) { + BuilderExternalList(RepeatedFieldBuilderV3 builder) { this.builder = builder; } @@ -673,15 +639,14 @@ public class RepeatedFieldBuilderV3 * @param the common interface for the message and the builder */ private static class MessageOrBuilderExternalList< - MType extends AbstractMessage, - BType extends AbstractMessage.Builder, - IType extends MessageOrBuilder> + MType extends AbstractMessage, + BType extends AbstractMessage.Builder, + IType extends MessageOrBuilder> extends AbstractList implements List { RepeatedFieldBuilderV3 builder; - MessageOrBuilderExternalList( - RepeatedFieldBuilderV3 builder) { + MessageOrBuilderExternalList(RepeatedFieldBuilderV3 builder) { this.builder = builder; } diff --git a/java/core/src/main/java/com/google/protobuf/RopeByteString.java b/java/core/src/main/java/com/google/protobuf/RopeByteString.java index 6fa555df15..154fd5da0d 100644 --- a/java/core/src/main/java/com/google/protobuf/RopeByteString.java +++ b/java/core/src/main/java/com/google/protobuf/RopeByteString.java @@ -46,41 +46,35 @@ import java.util.NoSuchElementException; import java.util.Stack; /** - * Class to represent {@code ByteStrings} formed by concatenation of other - * ByteStrings, without copying the data in the pieces. The concatenation is - * represented as a tree whose leaf nodes are each a - * {@link com.google.protobuf.ByteString.LeafByteString}. + * Class to represent {@code ByteStrings} formed by concatenation of other ByteStrings, without + * copying the data in the pieces. The concatenation is represented as a tree whose leaf nodes are + * each a {@link com.google.protobuf.ByteString.LeafByteString}. * *

Most of the operation here is inspired by the now-famous paper - * BAP95 Ropes: an Alternative to Strings hans-j. boehm, russ atkinson and - * michael plass + * BAP95 Ropes: an Alternative to Strings hans-j. boehm, russ atkinson and michael plass * - *

The algorithms described in the paper have been implemented for character - * strings in {@code com.google.common.string.Rope} and in the c++ class {@code - * cord.cc}. + *

The algorithms described in the paper have been implemented for character strings in {@code + * com.google.common.string.Rope} and in the c++ class {@code cord.cc}. * - *

Fundamentally the Rope algorithm represents the collection of pieces as a - * binary tree. BAP95 uses a Fibonacci bound relating depth to a minimum - * sequence length, sequences that are too short relative to their depth cause a - * tree rebalance. More precisely, a tree of depth d is "balanced" in the - * terminology of BAP95 if its length is at least F(d+2), where F(n) is the - * n-the Fibonacci number. Thus for depths 0, 1, 2, 3, 4, 5,... we have minimum - * lengths 1, 2, 3, 5, 8, 13,... + *

Fundamentally the Rope algorithm represents the collection of pieces as a binary tree. BAP95 + * uses a Fibonacci bound relating depth to a minimum sequence length, sequences that are too short + * relative to their depth cause a tree rebalance. More precisely, a tree of depth d is "balanced" + * in the terminology of BAP95 if its length is at least F(d+2), where F(n) is the n-the Fibonacci + * number. Thus for depths 0, 1, 2, 3, 4, 5,... we have minimum lengths 1, 2, 3, 5, 8, 13,... * * @author carlanton@google.com (Carl Haverl) */ final class RopeByteString extends ByteString { /** - * BAP95. Let Fn be the nth Fibonacci number. A {@link RopeByteString} of - * depth n is "balanced", i.e flat enough, if its length is at least Fn+2, - * e.g. a "balanced" {@link RopeByteString} of depth 1 must have length at - * least 2, of depth 4 must have length >= 8, etc. + * BAP95. Let Fn be the nth Fibonacci number. A {@link RopeByteString} of depth n is "balanced", + * i.e flat enough, if its length is at least Fn+2, e.g. a "balanced" {@link RopeByteString} of + * depth 1 must have length at least 2, of depth 4 must have length >= 8, etc. * - *

There's nothing special about using the Fibonacci numbers for this, but - * they are a reasonable sequence for encapsulating the idea that we are OK - * with longer strings being encoded in deeper binary trees. + *

There's nothing special about using the Fibonacci numbers for this, but they are a + * reasonable sequence for encapsulating the idea that we are OK with longer strings being encoded + * in deeper binary trees. * *

For 32-bit integers, this array has length 46. */ @@ -121,13 +115,11 @@ final class RopeByteString extends ByteString { private final int treeDepth; /** - * Create a new RopeByteString, which can be thought of as a new tree node, by - * recording references to the two given strings. + * Create a new RopeByteString, which can be thought of as a new tree node, by recording + * references to the two given strings. * - * @param left string on the left of this node, should have {@code size() > - * 0} - * @param right string on the right of this node, should have {@code size() > - * 0} + * @param left string on the left of this node, should have {@code size() > 0} + * @param right string on the right of this node, should have {@code size() > 0} */ private RopeByteString(ByteString left, ByteString right) { this.left = left; @@ -138,17 +130,15 @@ final class RopeByteString extends ByteString { } /** - * Concatenate the given strings while performing various optimizations to - * slow the growth rate of tree depth and tree node count. The result is - * either a {@link com.google.protobuf.ByteString.LeafByteString} or a - * {@link RopeByteString} depending on which optimizations, if any, were - * applied. + * Concatenate the given strings while performing various optimizations to slow the growth rate of + * tree depth and tree node count. The result is either a {@link + * com.google.protobuf.ByteString.LeafByteString} or a {@link RopeByteString} depending on which + * optimizations, if any, were applied. * - *

Small pieces of length less than {@link - * ByteString#CONCATENATE_BY_COPY_SIZE} may be copied by value here, as in - * BAP95. Large pieces are referenced without copy. + *

Small pieces of length less than {@link ByteString#CONCATENATE_BY_COPY_SIZE} may be copied + * by value here, as in BAP95. Large pieces are referenced without copy. * - * @param left string on the left + * @param left string on the left * @param right string on the right * @return concatenation representing the same sequence as the given strings */ @@ -208,31 +198,29 @@ final class RopeByteString extends ByteString { } /** - * Concatenates two strings by copying data values. This is called in a few - * cases in order to reduce the growth of the number of tree nodes. + * Concatenates two strings by copying data values. This is called in a few cases in order to + * reduce the growth of the number of tree nodes. * - * @param left string on the left + * @param left string on the left * @param right string on the right * @return string formed by copying data bytes */ - private static ByteString concatenateBytes(ByteString left, - ByteString right) { + private static ByteString concatenateBytes(ByteString left, ByteString right) { int leftSize = left.size(); int rightSize = right.size(); byte[] bytes = new byte[leftSize + rightSize]; left.copyTo(bytes, 0, 0, leftSize); right.copyTo(bytes, 0, leftSize, rightSize); - return ByteString.wrap(bytes); // Constructor wraps bytes + return ByteString.wrap(bytes); // Constructor wraps bytes } /** - * Create a new RopeByteString for testing only while bypassing all the - * defenses of {@link #concatenate(ByteString, ByteString)}. This allows - * testing trees of specific structure. We are also able to insert empty - * leaves, though these are dis-allowed, so that we can make sure the + * Create a new RopeByteString for testing only while bypassing all the defenses of {@link + * #concatenate(ByteString, ByteString)}. This allows testing trees of specific structure. We are + * also able to insert empty leaves, though these are dis-allowed, so that we can make sure the * implementation can withstand their presence. * - * @param left string on the left of this node + * @param left string on the left of this node * @param right string on the right of this node * @return an unsafe instance for testing only */ @@ -241,9 +229,8 @@ final class RopeByteString extends ByteString { } /** - * Gets the byte at the given index. - * Throws {@link ArrayIndexOutOfBoundsException} for backwards-compatibility - * reasons although it would more properly be {@link + * Gets the byte at the given index. Throws {@link ArrayIndexOutOfBoundsException} for + * backwards-compatibility reasons although it would more properly be {@link * IndexOutOfBoundsException}. * * @param index index of byte @@ -276,10 +263,9 @@ final class RopeByteString extends ByteString { } /** - * Determines if the tree is balanced according to BAP95, which means the tree - * is flat-enough with respect to the bounds. Note that this definition of - * balanced is one where sub-trees of balanced trees are not necessarily - * balanced. + * Determines if the tree is balanced according to BAP95, which means the tree is flat-enough with + * respect to the bounds. Note that this definition of balanced is one where sub-trees of balanced + * trees are not necessarily balanced. * * @return true if the tree is balanced */ @@ -289,17 +275,16 @@ final class RopeByteString extends ByteString { } /** - * Takes a substring of this one. This involves recursive descent along the - * left and right edges of the substring, and referencing any wholly contained - * segments in between. Any leaf nodes entirely uninvolved in the substring - * will not be referenced by the substring. + * Takes a substring of this one. This involves recursive descent along the left and right edges + * of the substring, and referencing any wholly contained segments in between. Any leaf nodes + * entirely uninvolved in the substring will not be referenced by the substring. * - *

Substrings of {@code length < 2} should result in at most a single - * recursive call chain, terminating at a leaf node. Thus the result will be a - * {@link com.google.protobuf.ByteString.LeafByteString}. + *

Substrings of {@code length < 2} should result in at most a single recursive call chain, + * terminating at a leaf node. Thus the result will be a {@link + * com.google.protobuf.ByteString.LeafByteString}. * * @param beginIndex start at this index - * @param endIndex the last character is the one before this index + * @param endIndex the last character is the one before this index * @return substring leaf node or tree */ @Override @@ -340,18 +325,16 @@ final class RopeByteString extends ByteString { // ByteString -> byte[] @Override - protected void copyToInternal(byte[] target, int sourceOffset, - int targetOffset, int numberToCopy) { - if (sourceOffset + numberToCopy <= leftLength) { + protected void copyToInternal( + byte[] target, int sourceOffset, int targetOffset, int numberToCopy) { + if (sourceOffset + numberToCopy <= leftLength) { left.copyToInternal(target, sourceOffset, targetOffset, numberToCopy); } else if (sourceOffset >= leftLength) { - right.copyToInternal(target, sourceOffset - leftLength, targetOffset, - numberToCopy); + right.copyToInternal(target, sourceOffset - leftLength, targetOffset, numberToCopy); } else { int leftLength = this.leftLength - sourceOffset; left.copyToInternal(target, sourceOffset, targetOffset, leftLength); - right.copyToInternal(target, 0, targetOffset + leftLength, - numberToCopy - leftLength); + right.copyToInternal(target, 0, targetOffset + leftLength, numberToCopy - leftLength); } } @@ -387,8 +370,7 @@ final class RopeByteString extends ByteString { } @Override - void writeToInternal(OutputStream out, int sourceOffset, - int numberToWrite) throws IOException { + void writeToInternal(OutputStream out, int sourceOffset, int numberToWrite) throws IOException { if (sourceOffset + numberToWrite <= leftLength) { left.writeToInternal(out, sourceOffset, numberToWrite); } else if (sourceOffset >= leftLength) { @@ -471,13 +453,11 @@ final class RopeByteString extends ByteString { } /** - * Determines if this string is equal to another of the same length by - * iterating over the leaf nodes. On each step of the iteration, the - * overlapping segments of the leaves are compared. + * Determines if this string is equal to another of the same length by iterating over the leaf + * nodes. On each step of the iteration, the overlapping segments of the leaves are compared. * * @param other string of the same length as this one - * @return true if the values of this string equals the value of the given - * one + * @return true if the values of this string equals the value of the given one */ private boolean equalsFragments(ByteString other) { int thisOffset = 0; @@ -495,9 +475,10 @@ final class RopeByteString extends ByteString { int bytesToCompare = Math.min(thisRemaining, thatRemaining); // At least one of the offsets will be zero - boolean stillEqual = (thisOffset == 0) - ? thisString.equalsRange(thatString, thatOffset, bytesToCompare) - : thatString.equalsRange(thisString, thisOffset, bytesToCompare); + boolean stillEqual = + (thisOffset == 0) + ? thisString.equalsRange(thatString, thatOffset, bytesToCompare) + : thatString.equalsRange(thisString, thisOffset, bytesToCompare); if (!stillEqual) { return false; } @@ -553,14 +534,13 @@ final class RopeByteString extends ByteString { } /** - * This class implements the balancing algorithm of BAP95. In the paper the - * authors use an array to keep track of pieces, while here we use a stack. - * The tree is balanced by traversing subtrees in left to right order, and the - * stack always contains the part of the string we've traversed so far. + * This class implements the balancing algorithm of BAP95. In the paper the authors use an array + * to keep track of pieces, while here we use a stack. The tree is balanced by traversing subtrees + * in left to right order, and the stack always contains the part of the string we've traversed so + * far. * - *

One surprising aspect of the algorithm is the result of balancing is not - * necessarily balanced, though it is nearly balanced. For details, see - * BAP95. + *

One surprising aspect of the algorithm is the result of balancing is not necessarily + * balanced, though it is nearly balanced. For details, see BAP95. */ private static class Balancer { // Stack containing the part of the string, starting from the left, that @@ -596,21 +576,18 @@ final class RopeByteString extends ByteString { doBalance(rbs.right); } else { throw new IllegalArgumentException( - "Has a new type of ByteString been created? Found " + - root.getClass()); + "Has a new type of ByteString been created? Found " + root.getClass()); } } /** - * Push a string on the balance stack (BAP95). BAP95 uses an array and - * calls the elements in the array 'bins'. We instead use a stack, so the - * 'bins' of lengths are represented by differences between the elements of - * minLengthByDepth. + * Push a string on the balance stack (BAP95). BAP95 uses an array and calls the elements in the + * array 'bins'. We instead use a stack, so the 'bins' of lengths are represented by differences + * between the elements of minLengthByDepth. * - *

If the length bin for our string, and all shorter length bins, are - * empty, we just push it on the stack. Otherwise, we need to start - * concatenating, putting the given string in the "middle" and continuing - * until we land in an empty length bin that matches the length of our + *

If the length bin for our string, and all shorter length bins, are empty, we just push it + * on the stack. Otherwise, we need to start concatenating, putting the given string in the + * "middle" and continuing until we land in an empty length bin that matches the length of our * concatenation. * * @param byteString string to place on the balance stack @@ -630,8 +607,7 @@ final class RopeByteString extends ByteString { // Concatenate the subtrees of shorter length ByteString newTree = prefixesStack.pop(); - while (!prefixesStack.isEmpty() - && prefixesStack.peek().size() < binStart) { + while (!prefixesStack.isEmpty() && prefixesStack.peek().size() < binStart) { ByteString left = prefixesStack.pop(); newTree = new RopeByteString(left, newTree); } @@ -668,18 +644,15 @@ final class RopeByteString extends ByteString { } /** - * This class is a continuable tree traversal, which keeps the state - * information which would exist on the stack in a recursive traversal instead - * on a stack of "Bread Crumbs". The maximum depth of the stack in this - * iterator is the same as the depth of the tree being traversed. + * This class is a continuable tree traversal, which keeps the state information which would exist + * on the stack in a recursive traversal instead on a stack of "Bread Crumbs". The maximum depth + * of the stack in this iterator is the same as the depth of the tree being traversed. * - *

This iterator is used to implement - * {@link RopeByteString#equalsFragments(ByteString)}. + *

This iterator is used to implement {@link RopeByteString#equalsFragments(ByteString)}. */ private static class PieceIterator implements Iterator { - private final Stack breadCrumbs = - new Stack(); + private final Stack breadCrumbs = new Stack(); private LeafByteString next; private PieceIterator(ByteString root) { @@ -717,8 +690,7 @@ final class RopeByteString extends ByteString { } /** - * Returns the next item and advances one - * {@link com.google.protobuf.ByteString.LeafByteString}. + * Returns the next item and advances one {@link com.google.protobuf.ByteString.LeafByteString}. * * @return next non-empty LeafByteString or {@code null} */ @@ -748,14 +720,10 @@ final class RopeByteString extends ByteString { } private void readObject(@SuppressWarnings("unused") ObjectInputStream in) throws IOException { - throw new InvalidObjectException( - "RopeByteStream instances are not to be serialized directly"); + throw new InvalidObjectException("RopeByteStream instances are not to be serialized directly"); } - /** - * This class is the {@link RopeByteString} equivalent for - * {@link ByteArrayInputStream}. - */ + /** This class is the {@link RopeByteString} equivalent for {@link ByteArrayInputStream}. */ private class RopeInputStream extends InputStream { // Iterates through the pieces of the rope private PieceIterator pieceIterator; @@ -775,7 +743,7 @@ final class RopeByteString extends ByteString { } @Override - public int read(byte b[], int offset, int length) { + public int read(byte[] b, int offset, int length) { if (b == null) { throw new NullPointerException(); } else if (offset < 0 || length < 0 || length > b.length - offset) { @@ -795,24 +763,23 @@ final class RopeByteString extends ByteString { } /** - * Internal implementation of read and skip. If b != null, then read the - * next {@code length} bytes into the buffer {@code b} at - * offset {@code offset}. If b == null, then skip the next {@code length} - * bytes. - *

- * This method assumes that all error checking has already happened. - *

- * Returns the actual number of bytes read or skipped. + * Internal implementation of read and skip. If b != null, then read the next {@code length} + * bytes into the buffer {@code b} at offset {@code offset}. If b == null, then skip the next + * {@code length} bytes. + * + *

This method assumes that all error checking has already happened. + * + *

Returns the actual number of bytes read or skipped. */ - private int readSkipInternal(byte b[], int offset, int length) { + private int readSkipInternal(byte[] b, int offset, int length) { int bytesRemaining = length; while (bytesRemaining > 0) { advanceIfCurrentPieceFullyRead(); if (currentPiece == null) { if (bytesRemaining == length) { - // We didn't manage to read anything - return -1; - } + // We didn't manage to read anything + return -1; + } break; } else { // Copy the bytes from this piece. @@ -826,7 +793,7 @@ final class RopeByteString extends ByteString { bytesRemaining -= count; } } - // Return the number of bytes read. + // Return the number of bytes read. return length - bytesRemaining; } @@ -874,9 +841,8 @@ final class RopeByteString extends ByteString { } /** - * Skips to the next piece if we have read all the data in the current - * piece. Sets currentPiece to null if we have reached the end of the - * input. + * Skips to the next piece if we have read all the data in the current piece. Sets currentPiece + * to null if we have reached the end of the input. */ private void advanceIfCurrentPieceFullyRead() { if (currentPiece != null && currentPieceIndex == currentPieceSize) { diff --git a/java/core/src/main/java/com/google/protobuf/RpcCallback.java b/java/core/src/main/java/com/google/protobuf/RpcCallback.java index 10752968e2..51a34b63d4 100644 --- a/java/core/src/main/java/com/google/protobuf/RpcCallback.java +++ b/java/core/src/main/java/com/google/protobuf/RpcCallback.java @@ -31,14 +31,13 @@ package com.google.protobuf; /** - * Interface for an RPC callback, normally called when an RPC completes. - * {@code ParameterType} is normally the method's response message type. + * Interface for an RPC callback, normally called when an RPC completes. {@code ParameterType} is + * normally the method's response message type. * - *

Starting with version 2.3.0, RPC implementations should not try to build - * on this, but should instead provide code generator plugins which generate - * code specific to the particular RPC implementation. This way the generated - * code can be more appropriate for the implementation in use and can avoid - * unnecessary layers of indirection. + *

Starting with version 2.3.0, RPC implementations should not try to build on this, but should + * instead provide code generator plugins which generate code specific to the particular RPC + * implementation. This way the generated code can be more appropriate for the implementation in use + * and can avoid unnecessary layers of indirection. * * @author kenton@google.com Kenton Varda */ diff --git a/java/core/src/main/java/com/google/protobuf/RpcChannel.java b/java/core/src/main/java/com/google/protobuf/RpcChannel.java index f272f4ad72..13b5ec165e 100644 --- a/java/core/src/main/java/com/google/protobuf/RpcChannel.java +++ b/java/core/src/main/java/com/google/protobuf/RpcChannel.java @@ -31,11 +31,10 @@ package com.google.protobuf; /** - *

Abstract interface for an RPC channel. An {@code RpcChannel} represents a - * communication line to a {@link Service} which can be used to call that - * {@link Service}'s methods. The {@link Service} may be running on another - * machine. Normally, you should not call an {@code RpcChannel} directly, but - * instead construct a stub {@link Service} wrapping it. Example: + * Abstract interface for an RPC channel. An {@code RpcChannel} represents a communication line to a + * {@link Service} which can be used to call that {@link Service}'s methods. The {@link Service} may + * be running on another machine. Normally, you should not call an {@code RpcChannel} directly, but + * instead construct a stub {@link Service} wrapping it. Example: * *

  *   RpcChannel channel = rpcImpl.newChannel("remotehost.example.com:1234");
@@ -44,28 +43,26 @@ package com.google.protobuf;
  *   service.myMethod(controller, request, callback);
  * 
* - *

Starting with version 2.3.0, RPC implementations should not try to build - * on this, but should instead provide code generator plugins which generate - * code specific to the particular RPC implementation. This way the generated - * code can be more appropriate for the implementation in use and can avoid - * unnecessary layers of indirection. + *

Starting with version 2.3.0, RPC implementations should not try to build on this, but should + * instead provide code generator plugins which generate code specific to the particular RPC + * implementation. This way the generated code can be more appropriate for the implementation in use + * and can avoid unnecessary layers of indirection. * * @author kenton@google.com Kenton Varda */ public interface RpcChannel { /** - * Call the given method of the remote service. This method is similar to - * {@code Service.callMethod()} with one important difference: the caller - * decides the types of the {@code Message} objects, not the callee. The - * request may be of any type as long as - * {@code request.getDescriptor() == method.getInputType()}. - * The response passed to the callback will be of the same type as - * {@code responsePrototype} (which must have - * {@code getDescriptor() == method.getOutputType()}). + * Call the given method of the remote service. This method is similar to {@code + * Service.callMethod()} with one important difference: the caller decides the types of the {@code + * Message} objects, not the callee. The request may be of any type as long as {@code + * request.getDescriptor() == method.getInputType()}. The response passed to the callback will be + * of the same type as {@code responsePrototype} (which must have {@code getDescriptor() == + * method.getOutputType()}). */ - void callMethod(Descriptors.MethodDescriptor method, - RpcController controller, - Message request, - Message responsePrototype, - RpcCallback done); + void callMethod( + Descriptors.MethodDescriptor method, + RpcController controller, + Message request, + Message responsePrototype, + RpcCallback done); } diff --git a/java/core/src/main/java/com/google/protobuf/RpcController.java b/java/core/src/main/java/com/google/protobuf/RpcController.java index a92dd7be6d..073f27a2aa 100644 --- a/java/core/src/main/java/com/google/protobuf/RpcController.java +++ b/java/core/src/main/java/com/google/protobuf/RpcController.java @@ -31,20 +31,18 @@ package com.google.protobuf; /** - *

An {@code RpcController} mediates a single method call. The primary - * purpose of the controller is to provide a way to manipulate settings - * specific to the RPC implementation and to find out about RPC-level errors. + * An {@code RpcController} mediates a single method call. The primary purpose of the controller is + * to provide a way to manipulate settings specific to the RPC implementation and to find out about + * RPC-level errors. * - *

Starting with version 2.3.0, RPC implementations should not try to build - * on this, but should instead provide code generator plugins which generate - * code specific to the particular RPC implementation. This way the generated - * code can be more appropriate for the implementation in use and can avoid - * unnecessary layers of indirection. + *

Starting with version 2.3.0, RPC implementations should not try to build on this, but should + * instead provide code generator plugins which generate code specific to the particular RPC + * implementation. This way the generated code can be more appropriate for the implementation in use + * and can avoid unnecessary layers of indirection. * - *

The methods provided by the {@code RpcController} interface are intended - * to be a "least common denominator" set of features which we expect all - * implementations to support. Specific implementations may provide more - * advanced features (e.g. deadline propagation). + *

The methods provided by the {@code RpcController} interface are intended to be a "least common + * denominator" set of features which we expect all implementations to support. Specific + * implementations may provide more advanced features (e.g. deadline propagation). * * @author kenton@google.com Kenton Varda */ @@ -54,31 +52,25 @@ public interface RpcController { // are undefined on the server side (may throw RuntimeExceptions). /** - * Resets the RpcController to its initial state so that it may be reused in - * a new call. This can be called from the client side only. It must not - * be called while an RPC is in progress. + * Resets the RpcController to its initial state so that it may be reused in a new call. This can + * be called from the client side only. It must not be called while an RPC is in progress. */ void reset(); /** - * After a call has finished, returns true if the call failed. The possible - * reasons for failure depend on the RPC implementation. {@code failed()} - * most only be called on the client side, and must not be called before a - * call has finished. + * After a call has finished, returns true if the call failed. The possible reasons for failure + * depend on the RPC implementation. {@code failed()} most only be called on the client side, and + * must not be called before a call has finished. */ boolean failed(); - /** - * If {@code failed()} is {@code true}, returns a human-readable description - * of the error. - */ + /** If {@code failed()} is {@code true}, returns a human-readable description of the error. */ String errorText(); /** - * Advises the RPC system that the caller desires that the RPC call be - * canceled. The RPC system may cancel it immediately, may wait awhile and - * then cancel it, or may not even cancel the call at all. If the call is - * canceled, the "done" callback will still be called and the RpcController + * Advises the RPC system that the caller desires that the RPC call be canceled. The RPC system + * may cancel it immediately, may wait awhile and then cancel it, or may not even cancel the call + * at all. If the call is canceled, the "done" callback will still be called and the RpcController * will indicate that the call failed at that time. */ void startCancel(); @@ -88,31 +80,29 @@ public interface RpcController { // are undefined on the client side (may throw RuntimeExceptions). /** - * Causes {@code failed()} to return true on the client side. {@code reason} - * will be incorporated into the message returned by {@code errorText()}. - * If you find you need to return machine-readable information about - * failures, you should incorporate it into your response protocol buffer - * and should NOT call {@code setFailed()}. + * Causes {@code failed()} to return true on the client side. {@code reason} will be incorporated + * into the message returned by {@code errorText()}. If you find you need to return + * machine-readable information about failures, you should incorporate it into your response + * protocol buffer and should NOT call {@code setFailed()}. */ void setFailed(String reason); /** - * If {@code true}, indicates that the client canceled the RPC, so the server - * may as well give up on replying to it. This method must be called on the - * server side only. The server should still call the final "done" callback. + * If {@code true}, indicates that the client canceled the RPC, so the server may as well give up + * on replying to it. This method must be called on the server side only. The server should still + * call the final "done" callback. */ boolean isCanceled(); /** - * Asks that the given callback be called when the RPC is canceled. The - * parameter passed to the callback will always be {@code null}. The - * callback will always be called exactly once. If the RPC completes without - * being canceled, the callback will be called after completion. If the RPC - * has already been canceled when NotifyOnCancel() is called, the callback - * will be called immediately. + * Asks that the given callback be called when the RPC is canceled. The parameter passed to the + * callback will always be {@code null}. The callback will always be called exactly once. If the + * RPC completes without being canceled, the callback will be called after completion. If the RPC + * has already been canceled when NotifyOnCancel() is called, the callback will be called + * immediately. * - *

{@code notifyOnCancel()} must be called no more than once per request. - * It must be called on the server side only. + *

{@code notifyOnCancel()} must be called no more than once per request. It must be called on + * the server side only. */ void notifyOnCancel(RpcCallback callback); } diff --git a/java/core/src/main/java/com/google/protobuf/RpcUtil.java b/java/core/src/main/java/com/google/protobuf/RpcUtil.java index f7d555ae15..7bd056a532 100644 --- a/java/core/src/main/java/com/google/protobuf/RpcUtil.java +++ b/java/core/src/main/java/com/google/protobuf/RpcUtil.java @@ -39,14 +39,13 @@ public final class RpcUtil { private RpcUtil() {} /** - * Take an {@code RpcCallback} and convert it to an - * {@code RpcCallback} accepting a specific message type. This is always - * type-safe (parameter type contravariance). + * Take an {@code RpcCallback} and convert it to an {@code RpcCallback} accepting a + * specific message type. This is always type-safe (parameter type contravariance). */ @SuppressWarnings("unchecked") - public static RpcCallback - specializeCallback(final RpcCallback originalCallback) { - return (RpcCallback)originalCallback; + public static RpcCallback specializeCallback( + final RpcCallback originalCallback) { + return (RpcCallback) originalCallback; // The above cast works, but only due to technical details of the Java // implementation. A more theoretically correct -- but less efficient -- // implementation would be as follows: @@ -58,15 +57,13 @@ public final class RpcUtil { } /** - * Take an {@code RpcCallback} accepting a specific message type and convert - * it to an {@code RpcCallback}. The generalized callback will - * accept any message object which has the same descriptor, and will convert - * it to the correct class before calling the original callback. However, - * if the generalized callback is given a message with a different descriptor, - * an exception will be thrown. + * Take an {@code RpcCallback} accepting a specific message type and convert it to an {@code + * RpcCallback}. The generalized callback will accept any message object which has the + * same descriptor, and will convert it to the correct class before calling the original callback. + * However, if the generalized callback is given a message with a different descriptor, an + * exception will be thrown. */ - public static - RpcCallback generalizeCallback( + public static RpcCallback generalizeCallback( final RpcCallback originalCallback, final Class originalClass, final Type defaultInstance) { @@ -85,25 +82,21 @@ public final class RpcUtil { } /** - * Creates a new message of type "Type" which is a copy of "source". "source" - * must have the same descriptor but may be a different class (e.g. - * DynamicMessage). + * Creates a new message of type "Type" which is a copy of "source". "source" must have the same + * descriptor but may be a different class (e.g. DynamicMessage). */ @SuppressWarnings("unchecked") private static Type copyAsType( final Type typeDefaultInstance, final Message source) { - return (Type) typeDefaultInstance - .newBuilderForType().mergeFrom(source).build(); + return (Type) typeDefaultInstance.newBuilderForType().mergeFrom(source).build(); } /** - * Creates a callback which can only be called once. This may be useful for - * security, when passing a callback to untrusted code: most callbacks do - * not expect to be called more than once, so doing so may expose bugs if it - * is not prevented. + * Creates a callback which can only be called once. This may be useful for security, when passing + * a callback to untrusted code: most callbacks do not expect to be called more than once, so + * doing so may expose bugs if it is not prevented. */ - public static - RpcCallback newOneTimeCallback( + public static RpcCallback newOneTimeCallback( final RpcCallback originalCallback) { return new RpcCallback() { private boolean alreadyCalled = false; @@ -122,15 +115,12 @@ public final class RpcUtil { }; } - /** - * Exception thrown when a one-time callback is called more than once. - */ + /** Exception thrown when a one-time callback is called more than once. */ public static final class AlreadyCalledException extends RuntimeException { private static final long serialVersionUID = 5469741279507848266L; public AlreadyCalledException() { - super("This RpcCallback was already called and cannot be called " + - "multiple times."); + super("This RpcCallback was already called and cannot be called multiple times."); } } } diff --git a/java/core/src/main/java/com/google/protobuf/Service.java b/java/core/src/main/java/com/google/protobuf/Service.java index ba7b033ed4..d45cdaec9a 100644 --- a/java/core/src/main/java/com/google/protobuf/Service.java +++ b/java/core/src/main/java/com/google/protobuf/Service.java @@ -31,70 +31,63 @@ package com.google.protobuf; /** - * Abstract base interface for protocol-buffer-based RPC services. Services - * themselves are abstract classes (implemented either by servers or as - * stubs), but they subclass this base interface. The methods of this - * interface can be used to call the methods of the service without knowing - * its exact type at compile time (analogous to the Message interface). + * Abstract base interface for protocol-buffer-based RPC services. Services themselves are abstract + * classes (implemented either by servers or as stubs), but they subclass this base interface. The + * methods of this interface can be used to call the methods of the service without knowing its + * exact type at compile time (analogous to the Message interface). * - *

Starting with version 2.3.0, RPC implementations should not try to build - * on this, but should instead provide code generator plugins which generate - * code specific to the particular RPC implementation. This way the generated - * code can be more appropriate for the implementation in use and can avoid - * unnecessary layers of indirection. + *

Starting with version 2.3.0, RPC implementations should not try to build on this, but should + * instead provide code generator plugins which generate code specific to the particular RPC + * implementation. This way the generated code can be more appropriate for the implementation in use + * and can avoid unnecessary layers of indirection. * * @author kenton@google.com Kenton Varda */ public interface Service { - /** - * Get the {@code ServiceDescriptor} describing this service and its methods. - */ + /** Get the {@code ServiceDescriptor} describing this service and its methods. */ Descriptors.ServiceDescriptor getDescriptorForType(); /** - *

Call a method of the service specified by MethodDescriptor. This is - * normally implemented as a simple {@code switch()} that calls the standard - * definitions of the service's methods. + * Call a method of the service specified by MethodDescriptor. This is normally implemented as a + * simple {@code switch()} that calls the standard definitions of the service's methods. * *

Preconditions: + * *

    *
  • {@code method.getService() == getDescriptorForType()} - *
  • {@code request} is of the exact same class as the object returned by - * {@code getRequestPrototype(method)}. - *
  • {@code controller} is of the correct type for the RPC implementation - * being used by this Service. For stubs, the "correct type" depends - * on the RpcChannel which the stub is using. Server-side Service - * implementations are expected to accept whatever type of - * {@code RpcController} the server-side RPC implementation uses. + *
  • {@code request} is of the exact same class as the object returned by {@code + * getRequestPrototype(method)}. + *
  • {@code controller} is of the correct type for the RPC implementation being used by this + * Service. For stubs, the "correct type" depends on the RpcChannel which the stub is using. + * Server-side Service implementations are expected to accept whatever type of {@code + * RpcController} the server-side RPC implementation uses. *
* *

Postconditions: + * *

    - *
  • {@code done} will be called when the method is complete. This may be - * before {@code callMethod()} returns or it may be at some point in - * the future. - *
  • The parameter to {@code done} is the response. It must be of the - * exact same type as would be returned by - * {@code getResponsePrototype(method)}. - *
  • If the RPC failed, the parameter to {@code done} will be - * {@code null}. Further details about the failure can be found by - * querying {@code controller}. + *
  • {@code done} will be called when the method is complete. This may be before {@code + * callMethod()} returns or it may be at some point in the future. + *
  • The parameter to {@code done} is the response. It must be of the exact same type as would + * be returned by {@code getResponsePrototype(method)}. + *
  • If the RPC failed, the parameter to {@code done} will be {@code null}. Further details + * about the failure can be found by querying {@code controller}. *
*/ - void callMethod(Descriptors.MethodDescriptor method, - RpcController controller, - Message request, - RpcCallback done); + void callMethod( + Descriptors.MethodDescriptor method, + RpcController controller, + Message request, + RpcCallback done); /** - *

{@code callMethod()} requires that the request passed in is of a - * particular subclass of {@code Message}. {@code getRequestPrototype()} - * gets the default instances of this type for a given method. You can then - * call {@code Message.newBuilderForType()} on this instance to - * construct a builder to build an object which you can then pass to - * {@code callMethod()}. + * {@code callMethod()} requires that the request passed in is of a particular subclass of {@code + * Message}. {@code getRequestPrototype()} gets the default instances of this type for a given + * method. You can then call {@code Message.newBuilderForType()} on this instance to construct a + * builder to build an object which you can then pass to {@code callMethod()}. * *

Example: + * *

    *   MethodDescriptor method =
    *     service.getDescriptorForType().findMethodByName("Foo");
@@ -107,11 +100,10 @@ public interface Service {
   Message getRequestPrototype(Descriptors.MethodDescriptor method);
 
   /**
-   * Like {@code getRequestPrototype()}, but gets a prototype of the response
-   * message.  {@code getResponsePrototype()} is generally not needed because
-   * the {@code Service} implementation constructs the response message itself,
-   * but it may be useful in some cases to know ahead of time what type of
-   * object will be returned.
+   * Like {@code getRequestPrototype()}, but gets a prototype of the response message. {@code
+   * getResponsePrototype()} is generally not needed because the {@code Service} implementation
+   * constructs the response message itself, but it may be useful in some cases to know ahead of
+   * time what type of object will be returned.
    */
   Message getResponsePrototype(Descriptors.MethodDescriptor method);
 }
diff --git a/java/core/src/main/java/com/google/protobuf/SingleFieldBuilder.java b/java/core/src/main/java/com/google/protobuf/SingleFieldBuilder.java
index 1f5ec8a2d7..acdc1de183 100644
--- a/java/core/src/main/java/com/google/protobuf/SingleFieldBuilder.java
+++ b/java/core/src/main/java/com/google/protobuf/SingleFieldBuilder.java
@@ -33,35 +33,29 @@ package com.google.protobuf;
 import static com.google.protobuf.Internal.checkNotNull;
 
 /**
- * {@code SingleFieldBuilder} implements a structure that a protocol
- * message uses to hold a single field of another protocol message. It supports
- * the classical use case of setting an immutable {@link Message} as the value
- * of the field and is highly optimized around this.
- * 
- * It also supports the additional use case of setting a {@link Message.Builder} - * as the field and deferring conversion of that {@code Builder} - * to an immutable {@code Message}. In this way, it's possible to maintain - * a tree of {@code Builder}'s that acts as a fully read/write data - * structure. + * {@code SingleFieldBuilder} implements a structure that a protocol message uses to hold a single + * field of another protocol message. It supports the classical use case of setting an immutable + * {@link Message} as the value of the field and is highly optimized around this. + * + *

It also supports the additional use case of setting a {@link Message.Builder} as the field and + * deferring conversion of that {@code Builder} to an immutable {@code Message}. In this way, it's + * possible to maintain a tree of {@code Builder}'s that acts as a fully read/write data structure. *
- * Logically, one can think of a tree of builders as converting the entire tree - * to messages when build is called on the root or when any method is called - * that desires a Message instead of a Builder. In terms of the implementation, - * the {@code SingleFieldBuilder} and {@code RepeatedFieldBuilder} - * classes cache messages that were created so that messages only need to be - * created when some change occurred in its builder or a builder for one of its - * descendants. + * Logically, one can think of a tree of builders as converting the entire tree to messages when + * build is called on the root or when any method is called that desires a Message instead of a + * Builder. In terms of the implementation, the {@code SingleFieldBuilder} and {@code + * RepeatedFieldBuilder} classes cache messages that were created so that messages only need to be + * created when some change occurred in its builder or a builder for one of its descendants. * * @param the type of message for the field * @param the type of builder for the field * @param the common interface for the message and the builder - * * @author jonp@google.com (Jon Perlow) */ -public class SingleFieldBuilder - +public class SingleFieldBuilder< + MType extends GeneratedMessage, + BType extends GeneratedMessage.Builder, + IType extends MessageOrBuilder> implements GeneratedMessage.BuilderParent { // Parent to send changes to. @@ -82,10 +76,7 @@ public class SingleFieldBuilder // to dispatch dirty invalidations. See GeneratedMessage.BuilderListener. private boolean isClean; - public SingleFieldBuilder( - MType message, - GeneratedMessage.BuilderParent parent, - boolean isClean) { + public SingleFieldBuilder(MType message, GeneratedMessage.BuilderParent parent, boolean isClean) { this.message = checkNotNull(message); this.parent = parent; this.isClean = isClean; @@ -97,10 +88,9 @@ public class SingleFieldBuilder } /** - * Get the message for the field. If the message is currently stored - * as a {@code Builder}, it is converted to a {@code Message} by - * calling {@link Message.Builder#buildPartial} on it. If no message has - * been set, returns the default instance of the message. + * Get the message for the field. If the message is currently stored as a {@code Builder}, it is + * converted to a {@code Message} by calling {@link Message.Builder#buildPartial} on it. If no + * message has been set, returns the default instance of the message. * * @return the message for the field */ @@ -126,8 +116,8 @@ public class SingleFieldBuilder } /** - * Gets a builder for the field. If no builder has been created yet, a - * builder is created on demand by calling {@link Message#toBuilder}. + * Gets a builder for the field. If no builder has been created yet, a builder is created on + * demand by calling {@link Message#toBuilder}. * * @return The builder for the field */ @@ -146,28 +136,27 @@ public class SingleFieldBuilder } /** - * Gets the base class interface for the field. This may either be a builder - * or a message. It will return whatever is more efficient. + * Gets the base class interface for the field. This may either be a builder or a message. It will + * return whatever is more efficient. * * @return the message or builder for the field as the base class interface */ @SuppressWarnings("unchecked") public IType getMessageOrBuilder() { if (builder != null) { - return (IType) builder; + return (IType) builder; } else { return (IType) message; } } /** - * Sets a message for the field replacing any existing value. + * Sets a message for the field replacing any existing value. * * @param message the message to set * @return the builder */ - public SingleFieldBuilder setMessage( - MType message) { + public SingleFieldBuilder setMessage(MType message) { this.message = checkNotNull(message); if (builder != null) { builder.dispose(); @@ -183,8 +172,7 @@ public class SingleFieldBuilder * @param value the value to merge from * @return the builder */ - public SingleFieldBuilder mergeFrom( - MType value) { + public SingleFieldBuilder mergeFrom(MType value) { if (builder == null && message == message.getDefaultInstanceForType()) { message = value; } else { @@ -201,9 +189,11 @@ public class SingleFieldBuilder */ @SuppressWarnings("unchecked") public SingleFieldBuilder clear() { - message = (MType) (message != null ? - message.getDefaultInstanceForType() : - builder.getDefaultInstanceForType()); + message = + (MType) + (message != null + ? message.getDefaultInstanceForType() + : builder.getDefaultInstanceForType()); if (builder != null) { builder.dispose(); builder = null; @@ -213,8 +203,8 @@ public class SingleFieldBuilder } /** - * 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. */ private void onChanged() { // If builder is null, this is the case where onChanged is being called diff --git a/java/core/src/main/java/com/google/protobuf/SingleFieldBuilderV3.java b/java/core/src/main/java/com/google/protobuf/SingleFieldBuilderV3.java index 8ab0f26d90..78a4a21664 100644 --- a/java/core/src/main/java/com/google/protobuf/SingleFieldBuilderV3.java +++ b/java/core/src/main/java/com/google/protobuf/SingleFieldBuilderV3.java @@ -33,35 +33,29 @@ package com.google.protobuf; import static com.google.protobuf.Internal.checkNotNull; /** - * {@code SingleFieldBuilderV3} implements a structure that a protocol - * message uses to hold a single field of another protocol message. It supports - * the classical use case of setting an immutable {@link Message} as the value - * of the field and is highly optimized around this. - *
- * It also supports the additional use case of setting a {@link Message.Builder} - * as the field and deferring conversion of that {@code Builder} - * to an immutable {@code Message}. In this way, it's possible to maintain - * a tree of {@code Builder}'s that acts as a fully read/write data - * structure. + * {@code SingleFieldBuilderV3} implements a structure that a protocol message uses to hold a single + * field of another protocol message. It supports the classical use case of setting an immutable + * {@link Message} as the value of the field and is highly optimized around this. + * + *

It also supports the additional use case of setting a {@link Message.Builder} as the field and + * deferring conversion of that {@code Builder} to an immutable {@code Message}. In this way, it's + * possible to maintain a tree of {@code Builder}'s that acts as a fully read/write data structure. *
- * Logically, one can think of a tree of builders as converting the entire tree - * to messages when build is called on the root or when any method is called - * that desires a Message instead of a Builder. In terms of the implementation, - * the {@code SingleFieldBuilderV3} and {@code RepeatedFieldBuilderV3} - * classes cache messages that were created so that messages only need to be - * created when some change occurred in its builder or a builder for one of its - * descendants. + * Logically, one can think of a tree of builders as converting the entire tree to messages when + * build is called on the root or when any method is called that desires a Message instead of a + * Builder. In terms of the implementation, the {@code SingleFieldBuilderV3} and {@code + * RepeatedFieldBuilderV3} classes cache messages that were created so that messages only need to be + * created when some change occurred in its builder or a builder for one of its descendants. * * @param the type of message for the field * @param the type of builder for the field * @param the common interface for the message and the builder - * * @author jonp@google.com (Jon Perlow) */ -public class SingleFieldBuilderV3 - +public class SingleFieldBuilderV3< + MType extends AbstractMessage, + BType extends AbstractMessage.Builder, + IType extends MessageOrBuilder> implements AbstractMessage.BuilderParent { // Parent to send changes to. @@ -82,10 +76,7 @@ public class SingleFieldBuilderV3 // to dispatch dirty invalidations. See AbstractMessage.BuilderListener. private boolean isClean; - public SingleFieldBuilderV3( - MType message, - AbstractMessage.BuilderParent parent, - boolean isClean) { + public SingleFieldBuilderV3(MType message, AbstractMessage.BuilderParent parent, boolean isClean) { this.message = checkNotNull(message); this.parent = parent; this.isClean = isClean; @@ -97,10 +88,9 @@ public class SingleFieldBuilderV3 } /** - * Get the message for the field. If the message is currently stored - * as a {@code Builder}, it is converted to a {@code Message} by - * calling {@link Message.Builder#buildPartial} on it. If no message has - * been set, returns the default instance of the message. + * Get the message for the field. If the message is currently stored as a {@code Builder}, it is + * converted to a {@code Message} by calling {@link Message.Builder#buildPartial} on it. If no + * message has been set, returns the default instance of the message. * * @return the message for the field */ @@ -126,8 +116,8 @@ public class SingleFieldBuilderV3 } /** - * Gets a builder for the field. If no builder has been created yet, a - * builder is created on demand by calling {@link Message#toBuilder}. + * Gets a builder for the field. If no builder has been created yet, a builder is created on + * demand by calling {@link Message#toBuilder}. * * @return The builder for the field */ @@ -146,28 +136,27 @@ public class SingleFieldBuilderV3 } /** - * Gets the base class interface for the field. This may either be a builder - * or a message. It will return whatever is more efficient. + * Gets the base class interface for the field. This may either be a builder or a message. It will + * return whatever is more efficient. * * @return the message or builder for the field as the base class interface */ @SuppressWarnings("unchecked") public IType getMessageOrBuilder() { if (builder != null) { - return (IType) builder; + return (IType) builder; } else { return (IType) message; } } /** - * Sets a message for the field replacing any existing value. + * Sets a message for the field replacing any existing value. * * @param message the message to set * @return the builder */ - public SingleFieldBuilderV3 setMessage( - MType message) { + public SingleFieldBuilderV3 setMessage(MType message) { this.message = checkNotNull(message); if (builder != null) { builder.dispose(); @@ -183,8 +172,7 @@ public class SingleFieldBuilderV3 * @param value the value to merge from * @return the builder */ - public SingleFieldBuilderV3 mergeFrom( - MType value) { + public SingleFieldBuilderV3 mergeFrom(MType value) { if (builder == null && message == message.getDefaultInstanceForType()) { message = value; } else { @@ -201,9 +189,11 @@ public class SingleFieldBuilderV3 */ @SuppressWarnings("unchecked") public SingleFieldBuilderV3 clear() { - message = (MType) (message != null ? - message.getDefaultInstanceForType() : - builder.getDefaultInstanceForType()); + message = + (MType) + (message != null + ? message.getDefaultInstanceForType() + : builder.getDefaultInstanceForType()); if (builder != null) { builder.dispose(); builder = null; @@ -213,8 +203,8 @@ public class SingleFieldBuilderV3 } /** - * 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. */ private void onChanged() { // If builder is null, this is the case where onChanged is being called diff --git a/java/core/src/main/java/com/google/protobuf/SmallSortedMap.java b/java/core/src/main/java/com/google/protobuf/SmallSortedMap.java index 279edc4de1..6bd65d6f4e 100644 --- a/java/core/src/main/java/com/google/protobuf/SmallSortedMap.java +++ b/java/core/src/main/java/com/google/protobuf/SmallSortedMap.java @@ -43,15 +43,14 @@ import java.util.SortedMap; import java.util.TreeMap; /** - * A custom map implementation from FieldDescriptor to Object optimized to - * minimize the number of memory allocations for instances with a small number - * of mappings. The implementation stores the first {@code k} mappings in an - * array for a configurable value of {@code k}, allowing direct access to the - * corresponding {@code Entry}s without the need to create an Iterator. The - * remaining entries are stored in an overflow map. Iteration over the entries - * in the map should be done as follows: + * A custom map implementation from FieldDescriptor to Object optimized to minimize the number of + * memory allocations for instances with a small number of mappings. The implementation stores the + * first {@code k} mappings in an array for a configurable value of {@code k}, allowing direct + * access to the corresponding {@code Entry}s without the need to create an Iterator. The remaining + * entries are stored in an overflow map. Iteration over the entries in the map should be done as + * follows: * - *

   {@code
+ * 
{@code
  * for (int i = 0; i < fieldMap.getNumArrayEntries(); i++) {
  *   process(fieldMap.getArrayEntryAt(i));
  * }
@@ -60,24 +59,21 @@ import java.util.TreeMap;
  * }
  * }
* - * The resulting iteration is in order of ascending field tag number. The - * object returned by {@link #entrySet()} adheres to the same contract but is - * less efficient as it necessarily involves creating an object for iteration. - *

- * The tradeoff for this memory efficiency is that the worst case running time - * of the {@code put()} operation is {@code O(k + lg n)}, which happens when - * entries are added in descending order. {@code k} should be chosen such that - * it covers enough common cases without adversely affecting larger maps. In - * practice, the worst case scenario does not happen for extensions because - * extension fields are serialized and deserialized in order of ascending tag - * number, but the worst case scenario can happen for DynamicMessages. - *

- * The running time for all other operations is similar to that of - * {@code TreeMap}. - *

- * Instances are not thread-safe until {@link #makeImmutable()} is called, - * after which any modifying operation will result in an - * {@link UnsupportedOperationException}. + * The resulting iteration is in order of ascending field tag number. The object returned by {@link + * #entrySet()} adheres to the same contract but is less efficient as it necessarily involves + * creating an object for iteration. + * + *

The tradeoff for this memory efficiency is that the worst case running time of the {@code + * put()} operation is {@code O(k + lg n)}, which happens when entries are added in descending + * order. {@code k} should be chosen such that it covers enough common cases without adversely + * affecting larger maps. In practice, the worst case scenario does not happen for extensions + * because extension fields are serialized and deserialized in order of ascending tag number, but + * the worst case scenario can happen for DynamicMessages. + * + *

The running time for all other operations is similar to that of {@code TreeMap}. + * + *

Instances are not thread-safe until {@link #makeImmutable()} is called, after which any + * modifying operation will result in an {@link UnsupportedOperationException}. * * @author darick@google.com Darick Tong */ @@ -87,15 +83,14 @@ import java.util.TreeMap; class SmallSortedMap, V> extends AbstractMap { /** - * Creates a new instance for mapping FieldDescriptors to their values. - * The {@link #makeImmutable()} implementation will convert the List values - * of any repeated fields to unmodifiable lists. + * Creates a new instance for mapping FieldDescriptors to their values. The {@link + * #makeImmutable()} implementation will convert the List values of any repeated fields to + * unmodifiable lists. * - * @param arraySize The size of the entry array containing the - * lexicographically smallest mappings. + * @param arraySize The size of the entry array containing the lexicographically smallest + * mappings. */ - static > + static > SmallSortedMap newFieldMap(int arraySize) { return new SmallSortedMap(arraySize) { @Override @@ -103,15 +98,13 @@ class SmallSortedMap, V> extends AbstractMap { public void makeImmutable() { if (!isImmutable()) { for (int i = 0; i < getNumArrayEntries(); i++) { - final Map.Entry entry = - getArrayEntryAt(i); + final Map.Entry entry = getArrayEntryAt(i); if (entry.getKey().isRepeated()) { final List value = (List) entry.getValue(); entry.setValue(Collections.unmodifiableList(value)); } } - for (Map.Entry entry : - getOverflowEntries()) { + for (Map.Entry entry : getOverflowEntries()) { if (entry.getKey().isRepeated()) { final List value = (List) entry.getValue(); entry.setValue(Collections.unmodifiableList(value)); @@ -126,11 +119,10 @@ class SmallSortedMap, V> extends AbstractMap { /** * Creates a new instance for testing. * - * @param arraySize The size of the entry array containing the - * lexicographically smallest mappings. + * @param arraySize The size of the entry array containing the lexicographically smallest + * mappings. */ - static , V> SmallSortedMap newInstanceForTest( - int arraySize) { + static , V> SmallSortedMap newInstanceForTest(int arraySize) { return new SmallSortedMap(arraySize); } @@ -146,9 +138,8 @@ class SmallSortedMap, V> extends AbstractMap { private volatile EntrySet lazyEntrySet; /** - * @code arraySize Size of the array in which the lexicographically smallest - * mappings are stored. (i.e. the {@code k} referred to in the class - * documentation). + * @code arraySize Size of the array in which the lexicographically smallest mappings are stored. + * (i.e. the {@code k} referred to in the class documentation). */ private SmallSortedMap(int arraySize) { this.maxArraySize = arraySize; @@ -163,9 +154,10 @@ class SmallSortedMap, V> extends AbstractMap { // because none of the list's accessors are exposed. The iterator() of // overflowEntries, on the other hand, is exposed so it must be made // unmodifiable. - overflowEntries = overflowEntries.isEmpty() ? - Collections.emptyMap() : - Collections.unmodifiableMap(overflowEntries); + overflowEntries = + overflowEntries.isEmpty() + ? Collections.emptyMap() + : Collections.unmodifiableMap(overflowEntries); isImmutable = true; } } @@ -192,9 +184,9 @@ class SmallSortedMap, V> extends AbstractMap { /** @return An iterable over the overflow entries. */ public Iterable> getOverflowEntries() { - return overflowEntries.isEmpty() ? - EmptySet.>iterable() : - overflowEntries.entrySet(); + return overflowEntries.isEmpty() + ? EmptySet.>iterable() + : overflowEntries.entrySet(); } @@ -204,10 +196,9 @@ class SmallSortedMap, V> extends AbstractMap { } /** - * The implementation throws a {@code ClassCastException} if o is not an - * object of type {@code K}. + * The implementation throws a {@code ClassCastException} if o is not an object of type {@code K}. * - * {@inheritDoc} + *

{@inheritDoc} */ @Override public boolean containsKey(Object o) { @@ -217,10 +208,9 @@ class SmallSortedMap, V> extends AbstractMap { } /** - * The implementation throws a {@code ClassCastException} if o is not an - * object of type {@code K}. + * The implementation throws a {@code ClassCastException} if o is not an object of type {@code K}. * - * {@inheritDoc} + *

{@inheritDoc} */ @Override public V get(Object o) { @@ -251,8 +241,7 @@ class SmallSortedMap, V> extends AbstractMap { if (entryList.size() == maxArraySize) { // Shift the last array entry into overflow. final Entry lastEntryInArray = entryList.remove(maxArraySize - 1); - getOverflowEntriesMutable().put(lastEntryInArray.getKey(), - lastEntryInArray.getValue()); + getOverflowEntriesMutable().put(lastEntryInArray.getKey(), lastEntryInArray.getValue()); } entryList.add(insertionPoint, new Entry(key, value)); return null; @@ -270,10 +259,9 @@ class SmallSortedMap, V> extends AbstractMap { } /** - * The implementation throws a {@code ClassCastException} if o is not an - * object of type {@code K}. + * The implementation throws a {@code ClassCastException} if o is not an object of type {@code K}. * - * {@inheritDoc} + *

{@inheritDoc} */ @Override public V remove(Object o) { @@ -299,8 +287,7 @@ class SmallSortedMap, V> extends AbstractMap { if (!overflowEntries.isEmpty()) { // Shift the first entry in the overflow to be the last entry in the // array. - final Iterator> iterator = - getOverflowEntriesMutable().entrySet().iterator(); + final Iterator> iterator = getOverflowEntriesMutable().entrySet().iterator(); entryList.add(new Entry(iterator.next())); iterator.remove(); } @@ -309,8 +296,8 @@ class SmallSortedMap, V> extends AbstractMap { /** * @param key The key to find in the entry array. - * @return The returned integer position follows the same semantics as the - * value returned by {@link java.util.Arrays#binarySearch()}. + * @return The returned integer position follows the same semantics as the value returned by + * {@link java.util.Arrays#binarySearch()}. */ private int binarySearchInArray(K key) { int left = 0; @@ -322,7 +309,7 @@ class SmallSortedMap, V> extends AbstractMap { if (right >= 0) { int cmp = key.compareTo(entryList.get(right).getKey()); if (cmp > 0) { - return -(right + 2); // Insert point is after "right". + return -(right + 2); // Insert point is after "right". } else if (cmp == 0) { return right; } @@ -343,11 +330,11 @@ class SmallSortedMap, V> extends AbstractMap { } /** - * Similar to the AbstractMap implementation of {@code keySet()} and - * {@code values()}, the entry set is created the first time this method is - * called, and returned in response to all subsequent calls. + * Similar to the AbstractMap implementation of {@code keySet()} and {@code values()}, the entry + * set is created the first time this method is called, and returned in response to all subsequent + * calls. * - * {@inheritDoc} + *

{@inheritDoc} */ @Override public Set> entrySet() { @@ -358,10 +345,7 @@ class SmallSortedMap, V> extends AbstractMap { } - /** - * @throws UnsupportedOperationException if {@link #makeImmutable()} has - * has been called. - */ + /** @throws UnsupportedOperationException if {@link #makeImmutable()} has has been called. */ private void checkMutable() { if (isImmutable) { throw new UnsupportedOperationException(); @@ -369,10 +353,8 @@ class SmallSortedMap, V> extends AbstractMap { } /** - * @return a {@link SortedMap} to which overflow entries mappings can be - * added or removed. - * @throws UnsupportedOperationException if {@link #makeImmutable()} has been - * called. + * @return a {@link SortedMap} to which overflow entries mappings can be added or removed. + * @throws UnsupportedOperationException if {@link #makeImmutable()} has been called. */ @SuppressWarnings("unchecked") private SortedMap getOverflowEntriesMutable() { @@ -383,10 +365,7 @@ class SmallSortedMap, V> extends AbstractMap { return (SortedMap) overflowEntries; } - /** - * Lazily creates the entry list. Any code that adds to the list must first - * call this method. - */ + /** Lazily creates the entry list. Any code that adds to the list must first call this method. */ private void ensureEntryArrayMutable() { checkMutable(); if (entryList.isEmpty() && !(entryList instanceof ArrayList)) { @@ -395,9 +374,8 @@ class SmallSortedMap, V> extends AbstractMap { } /** - * Entry implementation that implements Comparable in order to support - * binary search within the entry array. Also checks mutability in - * {@link #setValue()}. + * Entry implementation that implements Comparable in order to support binary search within the + * entry array. Also checks mutability in {@link #setValue()}. */ private class Entry implements Map.Entry, Comparable { @@ -451,8 +429,7 @@ class SmallSortedMap, V> extends AbstractMap { @Override public int hashCode() { - return (key == null ? 0 : key.hashCode()) ^ - (value == null ? 0 : value.hashCode()); + return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } @Override @@ -466,9 +443,7 @@ class SmallSortedMap, V> extends AbstractMap { } } - /** - * Stateless view of the entries in the field map. - */ + /** Stateless view of the entries in the field map. */ private class EntrySet extends AbstractSet> { @Override @@ -484,7 +459,7 @@ class SmallSortedMap, V> extends AbstractMap { /** * Throws a {@link ClassCastException} if o is not of the expected type. * - * {@inheritDoc} + *

{@inheritDoc} */ @Override public boolean contains(Object o) { @@ -492,8 +467,7 @@ class SmallSortedMap, V> extends AbstractMap { final Map.Entry entry = (Map.Entry) o; final V existing = get(entry.getKey()); final V value = entry.getValue(); - return existing == value || - (existing != null && existing.equals(value)); + return existing == value || (existing != null && existing.equals(value)); } @Override @@ -508,7 +482,7 @@ class SmallSortedMap, V> extends AbstractMap { /** * Throws a {@link ClassCastException} if o is not of the expected type. * - * {@inheritDoc} + *

{@inheritDoc} */ @Override public boolean remove(Object o) { @@ -529,8 +503,8 @@ class SmallSortedMap, V> extends AbstractMap { /** - * Iterator implementation that switches from the entry array to the overflow - * entries appropriately. + * Iterator implementation that switches from the entry array to the overflow entries + * appropriately. */ private class EntryIterator implements Iterator> { @@ -571,10 +545,9 @@ class SmallSortedMap, V> extends AbstractMap { } /** - * It is important to create the overflow iterator only after the array - * entries have been iterated over because the overflow entry set changes - * when the client calls remove() on the array entries, which invalidates - * any existing iterators. + * It is important to create the overflow iterator only after the array entries have been + * iterated over because the overflow entry set changes when the client calls remove() on the + * array entries, which invalidates any existing iterators. */ private Iterator> getOverflowIterator() { if (lazyOverflowIterator == null) { @@ -585,9 +558,9 @@ class SmallSortedMap, V> extends AbstractMap { } /** - * Helper class that holds immutable instances of an Iterable/Iterator that - * we return when the overflow entries is empty. This eliminates the creation - * of an Iterator object when there is nothing to iterate over. + * Helper class that holds immutable instances of an Iterable/Iterator that we return when the + * overflow entries is empty. This eliminates the creation of an Iterator object when there is + * nothing to iterate over. */ private static class EmptySet { @@ -597,10 +570,12 @@ class SmallSortedMap, V> extends AbstractMap { public boolean hasNext() { return false; } + @Override public Object next() { throw new NoSuchElementException(); } + @Override public void remove() { throw new UnsupportedOperationException(); @@ -653,7 +628,6 @@ class SmallSortedMap, V> extends AbstractMap { return overflowEntries.equals(other.overflowEntries); } - return true; } diff --git a/java/core/src/main/java/com/google/protobuf/TextFormat.java b/java/core/src/main/java/com/google/protobuf/TextFormat.java index 79962e0811..f89768a192 100644 --- a/java/core/src/main/java/com/google/protobuf/TextFormat.java +++ b/java/core/src/main/java/com/google/protobuf/TextFormat.java @@ -46,8 +46,8 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; /** - * Provide text parsing and formatting support for proto2 instances. - * The implementation largely follows google/protobuf/text_format.cc. + * Provide text parsing and formatting support for proto2 instances. The implementation largely + * follows google/protobuf/text_format.cc. * * @author wenboz@google.com Wenbo Zhu * @author kenton@google.com Kenton Varda @@ -58,46 +58,36 @@ public final class TextFormat { private static final Logger logger = Logger.getLogger(TextFormat.class.getName()); /** - * Outputs a textual representation of the Protocol Message supplied into - * the parameter output. (This representation is the new version of the - * classic "ProtocolPrinter" output from the original Protocol Buffer system) + * Outputs a textual representation of the Protocol Message supplied into the parameter output. + * (This representation is the new version of the classic "ProtocolPrinter" output from the + * original Protocol Buffer system) */ - public static void print( - final MessageOrBuilder message, final Appendable output) + public static void print(final MessageOrBuilder message, final Appendable output) throws IOException { Printer.DEFAULT.print(message, multiLineOutput(output)); } /** Outputs a textual representation of {@code fields} to {@code output}. */ - public static void print(final UnknownFieldSet fields, - final Appendable output) - throws IOException { + public static void print(final UnknownFieldSet fields, final Appendable output) + throws IOException { Printer.DEFAULT.printUnknownFields(fields, multiLineOutput(output)); } - /** - * Same as {@code print()}, except that non-ASCII characters are not - * escaped. - */ - public static void printUnicode( - final MessageOrBuilder message, final Appendable output) + /** Same as {@code print()}, except that non-ASCII characters are not escaped. */ + public static void printUnicode(final MessageOrBuilder message, final Appendable output) throws IOException { Printer.UNICODE.print(message, multiLineOutput(output)); } - /** - * Same as {@code print()}, except that non-ASCII characters are not - * escaped. - */ - public static void printUnicode(final UnknownFieldSet fields, - final Appendable output) - throws IOException { + /** Same as {@code print()}, except that non-ASCII characters are not escaped. */ + public static void printUnicode(final UnknownFieldSet fields, final Appendable output) + throws IOException { Printer.UNICODE.printUnknownFields(fields, multiLineOutput(output)); } /** - * Generates a human readable form of this message, useful for debugging and - * other purposes, with no newline characters. + * Generates a human readable form of this message, useful for debugging and other purposes, with + * no newline characters. */ public static String shortDebugString(final MessageOrBuilder message) { try { @@ -110,11 +100,10 @@ public final class TextFormat { } /** - * Generates a human readable form of the field, useful for debugging - * and other purposes, with no newline characters. + * Generates a human readable form of the field, useful for debugging and other purposes, with no + * newline characters. */ - public static String shortDebugString(final FieldDescriptor field, - final Object value) { + public static String shortDebugString(final FieldDescriptor field, final Object value) { try { final StringBuilder text = new StringBuilder(); Printer.DEFAULT.printField(field, value, singleLineOutput(text)); @@ -125,8 +114,8 @@ public final class TextFormat { } /** - * Generates a human readable form of the unknown fields, useful for debugging - * and other purposes, with no newline characters. + * Generates a human readable form of the unknown fields, useful for debugging and other purposes, + * with no newline characters. */ public static String shortDebugString(final UnknownFieldSet fields) { try { @@ -138,10 +127,7 @@ public final class TextFormat { } } - /** - * Like {@code print()}, but writes directly to a {@code String} and - * returns it. - */ + /** Like {@code print()}, but writes directly to a {@code String} and returns it. */ public static String printToString(final MessageOrBuilder message) { try { final StringBuilder text = new StringBuilder(); @@ -152,10 +138,7 @@ public final class TextFormat { } } - /** - * Like {@code print()}, but writes directly to a {@code String} and - * returns it. - */ + /** Like {@code print()}, but writes directly to a {@code String} and returns it. */ public static String printToString(final UnknownFieldSet fields) { try { final StringBuilder text = new StringBuilder(); @@ -167,8 +150,8 @@ public final class TextFormat { } /** - * Same as {@code printToString()}, except that non-ASCII characters - * in string type fields are not escaped in backslash+octals. + * Same as {@code printToString()}, except that non-ASCII characters in string type fields are not + * escaped in backslash+octals. */ public static String printToUnicodeString(final MessageOrBuilder message) { try { @@ -181,8 +164,8 @@ public final class TextFormat { } /** - * Same as {@code printToString()}, except that non-ASCII characters - * in string type fields are not escaped in backslash+octals. + * Same as {@code printToString()}, except that non-ASCII characters in string type fields are not + * escaped in backslash+octals. */ public static String printToUnicodeString(final UnknownFieldSet fields) { try { @@ -194,15 +177,12 @@ public final class TextFormat { } } - public static void printField(final FieldDescriptor field, - final Object value, - final Appendable output) - throws IOException { + public static void printField( + final FieldDescriptor field, final Object value, final Appendable output) throws IOException { Printer.DEFAULT.printField(field, value, multiLineOutput(output)); } - public static String printFieldToString(final FieldDescriptor field, - final Object value) { + public static String printFieldToString(final FieldDescriptor field, final Object value) { try { final StringBuilder text = new StringBuilder(); printField(field, value, text); @@ -235,14 +215,11 @@ public final class TextFormat { * @param field the descriptor of the field * @param value the value of the field * @param output the output to which to append the formatted value - * @throws ClassCastException if the value is not appropriate for the - * given field descriptor + * @throws ClassCastException if the value is not appropriate for the given field descriptor * @throws IOException if there is an exception writing to the output */ - public static void printFieldValue(final FieldDescriptor field, - final Object value, - final Appendable output) - throws IOException { + public static void printFieldValue( + final FieldDescriptor field, final Object value, final Appendable output) throws IOException { Printer.DEFAULT.printFieldValue(field, value, multiLineOutput(output)); } @@ -252,28 +229,22 @@ public final class TextFormat { * @param tag the field's tag number * @param value the value of the field * @param output the output to which to append the formatted value - * @throws ClassCastException if the value is not appropriate for the - * given field descriptor + * @throws ClassCastException if the value is not appropriate for the given field descriptor * @throws IOException if there is an exception writing to the output */ - public static void printUnknownFieldValue(final int tag, - final Object value, - final Appendable output) - throws IOException { + public static void printUnknownFieldValue( + final int tag, final Object value, final Appendable output) throws IOException { printUnknownFieldValue(tag, value, multiLineOutput(output)); } - private static void printUnknownFieldValue(final int tag, - final Object value, - final TextGenerator generator) - throws IOException { + private static void printUnknownFieldValue( + final int tag, final Object value, final TextGenerator generator) throws IOException { switch (WireFormat.getTagWireType(tag)) { case WireFormat.WIRETYPE_VARINT: generator.print(unsignedToString((Long) value)); break; case WireFormat.WIRETYPE_FIXED32: - generator.print( - String.format((Locale) null, "0x%08x", (Integer) value)); + generator.print(String.format((Locale) null, "0x%08x", (Integer) value)); break; case WireFormat.WIRETYPE_FIXED64: generator.print(String.format((Locale) null, "0x%016x", (Long) value)); @@ -317,18 +288,17 @@ public final class TextFormat { this.escapeNonAscii = escapeNonAscii; } - private void print( - final MessageOrBuilder message, final TextGenerator generator) + private void print(final MessageOrBuilder message, final TextGenerator generator) throws IOException { - for (Map.Entry field - : message.getAllFields().entrySet()) { + for (Map.Entry field : message.getAllFields().entrySet()) { printField(field.getKey(), field.getValue(), generator); } printUnknownFields(message.getUnknownFields(), generator); } - private void printField(final FieldDescriptor field, final Object value, - final TextGenerator generator) throws IOException { + private void printField( + final FieldDescriptor field, final Object value, final TextGenerator generator) + throws IOException { if (field.isRepeated()) { // Repeated field. Print each element. for (Object element : (List) value) { @@ -339,10 +309,9 @@ public final class TextFormat { } } - private void printSingleField(final FieldDescriptor field, - final Object value, - final TextGenerator generator) - throws IOException { + private void printSingleField( + final FieldDescriptor field, final Object value, final TextGenerator generator) + throws IOException { if (field.isExtension()) { generator.print("["); // We special-case MessageSet elements for compatibility with proto1. @@ -382,10 +351,9 @@ public final class TextFormat { generator.eol(); } - private void printFieldValue(final FieldDescriptor field, - final Object value, - final TextGenerator generator) - throws IOException { + private void printFieldValue( + final FieldDescriptor field, final Object value, final TextGenerator generator) + throws IOException { switch (field.getType()) { case INT32: case SINT32: @@ -423,10 +391,10 @@ public final class TextFormat { case STRING: generator.print("\""); - generator.print(escapeNonAscii - ? TextFormatEscaper.escapeText((String) value) - : escapeDoubleQuotesAndBackslashes((String) value) - .replace("\n", "\\n")); + generator.print( + escapeNonAscii + ? TextFormatEscaper.escapeText((String) value) + : escapeDoubleQuotesAndBackslashes((String) value).replace("\n", "\\n")); generator.print("\""); break; @@ -451,21 +419,19 @@ public final class TextFormat { } } - private void printUnknownFields(final UnknownFieldSet unknownFields, - final TextGenerator generator) - throws IOException { - for (Map.Entry entry : - unknownFields.asMap().entrySet()) { + private void printUnknownFields( + final UnknownFieldSet unknownFields, final TextGenerator generator) throws IOException { + for (Map.Entry entry : unknownFields.asMap().entrySet()) { final int number = entry.getKey(); final UnknownFieldSet.Field field = entry.getValue(); - printUnknownField(number, WireFormat.WIRETYPE_VARINT, - field.getVarintList(), generator); - printUnknownField(number, WireFormat.WIRETYPE_FIXED32, - field.getFixed32List(), generator); - printUnknownField(number, WireFormat.WIRETYPE_FIXED64, - field.getFixed64List(), generator); - printUnknownField(number, WireFormat.WIRETYPE_LENGTH_DELIMITED, - field.getLengthDelimitedList(), generator); + printUnknownField(number, WireFormat.WIRETYPE_VARINT, field.getVarintList(), generator); + printUnknownField(number, WireFormat.WIRETYPE_FIXED32, field.getFixed32List(), generator); + printUnknownField(number, WireFormat.WIRETYPE_FIXED64, field.getFixed64List(), generator); + printUnknownField( + number, + WireFormat.WIRETYPE_LENGTH_DELIMITED, + field.getLengthDelimitedList(), + generator); for (final UnknownFieldSet value : field.getGroupList()) { generator.print(entry.getKey().toString()); generator.print(" {"); @@ -479,11 +445,9 @@ public final class TextFormat { } } - private void printUnknownField(final int number, - final int wireType, - final List values, - final TextGenerator generator) - throws IOException { + private void printUnknownField( + final int number, final int wireType, final List values, final TextGenerator generator) + throws IOException { for (final Object value : values) { generator.print(String.valueOf(number)); generator.print(": "); @@ -509,8 +473,7 @@ public final class TextFormat { } else { // Pull off the most-significant bit so that BigInteger doesn't think // the number is negative, then set it again using setBit(). - return BigInteger.valueOf(value & 0x7FFFFFFFFFFFFFFFL) - .setBit(63).toString(); + return BigInteger.valueOf(value & 0x7FFFFFFFFFFFFFFFL).setBit(63).toString(); } } @@ -522,9 +485,7 @@ public final class TextFormat { return new TextGenerator(output, true); } - /** - * An inner class for writing text to the output stream. - */ + /** An inner class for writing text to the output stream. */ private static final class TextGenerator { private final Appendable output; private final StringBuilder indent = new StringBuilder(); @@ -540,23 +501,19 @@ public final class TextFormat { } /** - * Indent text by two spaces. After calling Indent(), two spaces will be - * inserted at the beginning of each line of text. Indent() may be called - * multiple times to produce deeper indents. + * Indent text by two spaces. After calling Indent(), two spaces will be inserted at the + * beginning of each line of text. Indent() may be called multiple times to produce deeper + * indents. */ public void indent() { indent.append(" "); } - /** - * Reduces the current indent level by two spaces, or crashes if the indent - * level is zero. - */ + /** Reduces the current indent level by two spaces, or crashes if the indent level is zero. */ public void outdent() { final int length = indent.length(); if (length == 0) { - throw new IllegalArgumentException( - " Outdent() without matching Indent()."); + throw new IllegalArgumentException(" Outdent() without matching Indent()."); } indent.setLength(length - 2); } @@ -592,30 +549,26 @@ public final class TextFormat { /** * Represents a stream of tokens parsed from a {@code String}. * - *

The Java standard library provides many classes that you might think - * would be useful for implementing this, but aren't. For example: + *

The Java standard library provides many classes that you might think would be useful for + * implementing this, but aren't. For example: * *

    - *
  • {@code java.io.StreamTokenizer}: This almost does what we want -- or, - * at least, something that would get us close to what we want -- except - * for one fatal flaw: It automatically un-escapes strings using Java - * escape sequences, which do not include all the escape sequences we - * need to support (e.g. '\x'). - *
  • {@code java.util.Scanner}: This seems like a great way at least to - * parse regular expressions out of a stream (so we wouldn't have to load - * the entire input into a single string before parsing). Sadly, - * {@code Scanner} requires that tokens be delimited with some delimiter. - * Thus, although the text "foo:" should parse to two tokens ("foo" and - * ":"), {@code Scanner} would recognize it only as a single token. - * Furthermore, {@code Scanner} provides no way to inspect the contents - * of delimiters, making it impossible to keep track of line and column - * numbers. + *
  • {@code java.io.StreamTokenizer}: This almost does what we want -- or, at least, something + * that would get us close to what we want -- except for one fatal flaw: It automatically + * un-escapes strings using Java escape sequences, which do not include all the escape + * sequences we need to support (e.g. '\x'). + *
  • {@code java.util.Scanner}: This seems like a great way at least to parse regular + * expressions out of a stream (so we wouldn't have to load the entire input into a single + * string before parsing). Sadly, {@code Scanner} requires that tokens be delimited with + * some delimiter. Thus, although the text "foo:" should parse to two tokens ("foo" and + * ":"), {@code Scanner} would recognize it only as a single token. Furthermore, {@code + * Scanner} provides no way to inspect the contents of delimiters, making it impossible to + * keep track of line and column numbers. *
* - *

Luckily, Java's regular expression support does manage to be useful to - * us. (Barely: We need {@code Matcher.usePattern()}, which is new in - * Java 1.5.) So, we can use that, at least. Unfortunately, this implies - * that we need to have the entire input in one contiguous string. + *

Luckily, Java's regular expression support does manage to be useful to us. (Barely: We need + * {@code Matcher.usePattern()}, which is new in Java 1.5.) So, we can use that, at least. + * Unfortunately, this implies that we need to have the entire input in one contiguous string. */ private static final class Tokenizer { private final CharSequence text; @@ -636,24 +589,20 @@ public final class TextFormat { // We use possessive quantifiers (*+ and ++) because otherwise the Java // regex matcher has stack overflows on large inputs. - private static final Pattern WHITESPACE = - Pattern.compile("(\\s|(#.*$))++", Pattern.MULTILINE); - private static final Pattern TOKEN = Pattern.compile( - "[a-zA-Z_][0-9a-zA-Z_+-]*+|" + // an identifier - "[.]?[0-9+-][0-9a-zA-Z_.+-]*+|" + // a number - "\"([^\"\n\\\\]|\\\\.)*+(\"|\\\\?$)|" + // a double-quoted string - "\'([^\'\n\\\\]|\\\\.)*+(\'|\\\\?$)", // a single-quoted string - Pattern.MULTILINE); - - private static final Pattern DOUBLE_INFINITY = Pattern.compile( - "-?inf(inity)?", - Pattern.CASE_INSENSITIVE); - private static final Pattern FLOAT_INFINITY = Pattern.compile( - "-?inf(inity)?f?", - Pattern.CASE_INSENSITIVE); - private static final Pattern FLOAT_NAN = Pattern.compile( - "nanf?", - Pattern.CASE_INSENSITIVE); + private static final Pattern WHITESPACE = Pattern.compile("(\\s|(#.*$))++", Pattern.MULTILINE); + private static final Pattern TOKEN = + Pattern.compile( + "[a-zA-Z_][0-9a-zA-Z_+-]*+|" // an identifier + + "[.]?[0-9+-][0-9a-zA-Z_.+-]*+|" // a number + + "\"([^\"\n\\\\]|\\\\.)*+(\"|\\\\?$)|" // a double-quoted string + + "\'([^\'\n\\\\]|\\\\.)*+(\'|\\\\?$)", // a single-quoted string + Pattern.MULTILINE); + + private static final Pattern DOUBLE_INFINITY = + Pattern.compile("-?inf(inity)?", Pattern.CASE_INSENSITIVE); + private static final Pattern FLOAT_INFINITY = + Pattern.compile("-?inf(inity)?f?", Pattern.CASE_INSENSITIVE); + private static final Pattern FLOAT_NAN = Pattern.compile("nanf?", Pattern.CASE_INSENSITIVE); /** Construct a tokenizer that parses tokens from the given text. */ private Tokenizer(final CharSequence text) { @@ -719,10 +668,7 @@ public final class TextFormat { } } - /** - * Skip over any whitespace so that the matcher region starts at the next - * token. - */ + /** Skip over any whitespace so that the matcher region starts at the next token. */ private void skipWhitespace() { matcher.usePattern(WHITESPACE); if (matcher.lookingAt()) { @@ -731,8 +677,8 @@ public final class TextFormat { } /** - * If the next token exactly matches {@code token}, consume it and return - * {@code true}. Otherwise, return {@code false} without doing anything. + * If the next token exactly matches {@code token}, consume it and return {@code true}. + * Otherwise, return {@code false} without doing anything. */ public boolean tryConsume(final String token) { if (currentToken.equals(token)) { @@ -744,8 +690,8 @@ public final class TextFormat { } /** - * If the next token exactly matches {@code token}, consume it. Otherwise, - * throw a {@link ParseException}. + * If the next token exactly matches {@code token}, consume it. Otherwise, throw a {@link + * ParseException}. */ public void consume(final String token) throws ParseException { if (!tryConsume(token)) { @@ -753,31 +699,24 @@ public final class TextFormat { } } - /** - * Returns {@code true} if the next token is an integer, but does - * not consume it. - */ + /** Returns {@code true} if the next token is an integer, but does not consume it. */ public boolean lookingAtInteger() { if (currentToken.length() == 0) { return false; } final char c = currentToken.charAt(0); - return ('0' <= c && c <= '9') - || c == '-' || c == '+'; + return ('0' <= c && c <= '9') || c == '-' || c == '+'; } - /** - * Returns {@code true} if the current token's text is equal to that - * specified. - */ + /** Returns {@code true} if the current token's text is equal to that specified. */ public boolean lookingAt(String text) { return currentToken.equals(text); } /** - * If the next token is an identifier, consume it and return its value. - * Otherwise, throw a {@link ParseException}. + * If the next token is an identifier, consume it and return its value. Otherwise, throw a + * {@link ParseException}. */ public String consumeIdentifier() throws ParseException { for (int i = 0; i < currentToken.length(); i++) { @@ -785,11 +724,11 @@ public final class TextFormat { if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') - || (c == '_') || (c == '.')) { + || (c == '_') + || (c == '.')) { // OK } else { - throw parseException( - "Expected identifier. Found '" + currentToken + "'"); + throw parseException("Expected identifier. Found '" + currentToken + "'"); } } @@ -799,8 +738,8 @@ public final class TextFormat { } /** - * If the next token is an identifier, consume it and return {@code true}. - * Otherwise, return {@code false} without doing anything. + * If the next token is an identifier, consume it and return {@code true}. Otherwise, return + * {@code false} without doing anything. */ public boolean tryConsumeIdentifier() { try { @@ -812,8 +751,8 @@ public final class TextFormat { } /** - * If the next token is a 32-bit signed integer, consume it and return its - * value. Otherwise, throw a {@link ParseException}. + * If the next token is a 32-bit signed integer, consume it and return its value. Otherwise, + * throw a {@link ParseException}. */ public int consumeInt32() throws ParseException { try { @@ -826,8 +765,8 @@ public final class TextFormat { } /** - * If the next token is a 32-bit unsigned integer, consume it and return its - * value. Otherwise, throw a {@link ParseException}. + * If the next token is a 32-bit unsigned integer, consume it and return its value. Otherwise, + * throw a {@link ParseException}. */ public int consumeUInt32() throws ParseException { try { @@ -840,8 +779,8 @@ public final class TextFormat { } /** - * If the next token is a 64-bit signed integer, consume it and return its - * value. Otherwise, throw a {@link ParseException}. + * If the next token is a 64-bit signed integer, consume it and return its value. Otherwise, + * throw a {@link ParseException}. */ public long consumeInt64() throws ParseException { try { @@ -854,8 +793,8 @@ public final class TextFormat { } /** - * If the next token is a 64-bit signed integer, consume it and return - * {@code true}. Otherwise, return {@code false} without doing anything. + * If the next token is a 64-bit signed integer, consume it and return {@code true}. Otherwise, + * return {@code false} without doing anything. */ public boolean tryConsumeInt64() { try { @@ -867,8 +806,8 @@ public final class TextFormat { } /** - * If the next token is a 64-bit unsigned integer, consume it and return its - * value. Otherwise, throw a {@link ParseException}. + * If the next token is a 64-bit unsigned integer, consume it and return its value. Otherwise, + * throw a {@link ParseException}. */ public long consumeUInt64() throws ParseException { try { @@ -881,8 +820,8 @@ public final class TextFormat { } /** - * If the next token is a 64-bit unsigned integer, consume it and return - * {@code true}. Otherwise, return {@code false} without doing anything. + * If the next token is a 64-bit unsigned integer, consume it and return {@code true}. + * Otherwise, return {@code false} without doing anything. */ public boolean tryConsumeUInt64() { try { @@ -894,8 +833,8 @@ public final class TextFormat { } /** - * If the next token is a double, consume it and return its value. - * Otherwise, throw a {@link ParseException}. + * If the next token is a double, consume it and return its value. Otherwise, throw a {@link + * ParseException}. */ public double consumeDouble() throws ParseException { // We need to parse infinity and nan separately because @@ -919,8 +858,8 @@ public final class TextFormat { } /** - * If the next token is a double, consume it and return {@code true}. - * Otherwise, return {@code false} without doing anything. + * If the next token is a double, consume it and return {@code true}. Otherwise, return {@code + * false} without doing anything. */ public boolean tryConsumeDouble() { try { @@ -932,8 +871,8 @@ public final class TextFormat { } /** - * If the next token is a float, consume it and return its value. - * Otherwise, throw a {@link ParseException}. + * If the next token is a float, consume it and return its value. Otherwise, throw a {@link + * ParseException}. */ public float consumeFloat() throws ParseException { // We need to parse infinity and nan separately because @@ -957,8 +896,8 @@ public final class TextFormat { } /** - * If the next token is a float, consume it and return {@code true}. - * Otherwise, return {@code false} without doing anything. + * If the next token is a float, consume it and return {@code true}. Otherwise, return {@code + * false} without doing anything. */ public boolean tryConsumeFloat() { try { @@ -970,8 +909,8 @@ public final class TextFormat { } /** - * If the next token is a boolean, consume it and return its value. - * Otherwise, throw a {@link ParseException}. + * If the next token is a boolean, consume it and return its value. Otherwise, throw a {@link + * ParseException}. */ public boolean consumeBoolean() throws ParseException { if (currentToken.equals("true") @@ -992,17 +931,14 @@ public final class TextFormat { } /** - * If the next token is a string, consume it and return its (unescaped) - * value. Otherwise, throw a {@link ParseException}. + * If the next token is a string, consume it and return its (unescaped) value. Otherwise, throw + * a {@link ParseException}. */ public String consumeString() throws ParseException { return consumeByteString().toStringUtf8(); } - /** - * If the next token is a string, consume it and return true. Otherwise, - * return false. - */ + /** If the next token is a string, consume it and return true. Otherwise, return false. */ public boolean tryConsumeString() { try { consumeString(); @@ -1013,9 +949,8 @@ public final class TextFormat { } /** - * If the next token is a string, consume it, unescape it as a - * {@link ByteString}, and return it. Otherwise, throw a - * {@link ParseException}. + * If the next token is a string, consume it, unescape it as a {@link ByteString}, and return + * it. Otherwise, throw a {@link ParseException}. */ public ByteString consumeByteString() throws ParseException { List list = new ArrayList(); @@ -1027,28 +962,22 @@ public final class TextFormat { } /** - * Like {@link #consumeByteString()} but adds each token of the string to - * the given list. String literals (whether bytes or text) may come in - * multiple adjacent tokens which are automatically concatenated, like in - * C or Python. + * Like {@link #consumeByteString()} but adds each token of the string to the given list. String + * literals (whether bytes or text) may come in multiple adjacent tokens which are automatically + * concatenated, like in C or Python. */ - private void consumeByteString(List list) - throws ParseException { - final char quote = currentToken.length() > 0 - ? currentToken.charAt(0) - : '\0'; + private void consumeByteString(List list) throws ParseException { + final char quote = currentToken.length() > 0 ? currentToken.charAt(0) : '\0'; if (quote != '\"' && quote != '\'') { throw parseException("Expected string."); } - if (currentToken.length() < 2 - || currentToken.charAt(currentToken.length() - 1) != quote) { + if (currentToken.length() < 2 || currentToken.charAt(currentToken.length() - 1) != quote) { throw parseException("String missing ending quote."); } try { - final String escaped = - currentToken.substring(1, currentToken.length() - 1); + final String escaped = currentToken.substring(1, currentToken.length() - 1); final ByteString result = unescapeBytes(escaped); nextToken(); list.add(result); @@ -1058,53 +987,48 @@ public final class TextFormat { } /** - * Returns a {@link ParseException} with the current line and column - * numbers in the description, suitable for throwing. + * Returns a {@link ParseException} with the current line and column numbers in the description, + * suitable for throwing. */ public ParseException parseException(final String description) { // Note: People generally prefer one-based line and column numbers. - return new ParseException( - line + 1, column + 1, description); + return new ParseException(line + 1, column + 1, description); } /** - * Returns a {@link ParseException} with the line and column numbers of - * the previous token in the description, suitable for throwing. + * Returns a {@link ParseException} with the line and column numbers of the previous token in + * the description, suitable for throwing. */ - public ParseException parseExceptionPreviousToken( - final String description) { + public ParseException parseExceptionPreviousToken(final String description) { // Note: People generally prefer one-based line and column numbers. - return new ParseException( - previousLine + 1, previousColumn + 1, description); + return new ParseException(previousLine + 1, previousColumn + 1, description); } /** - * Constructs an appropriate {@link ParseException} for the given - * {@code NumberFormatException} when trying to parse an integer. + * Constructs an appropriate {@link ParseException} for the given {@code NumberFormatException} + * when trying to parse an integer. */ - private ParseException integerParseException( - final NumberFormatException e) { + private ParseException integerParseException(final NumberFormatException e) { return parseException("Couldn't parse integer: " + e.getMessage()); } /** - * Constructs an appropriate {@link ParseException} for the given - * {@code NumberFormatException} when trying to parse a float or double. + * Constructs an appropriate {@link ParseException} for the given {@code NumberFormatException} + * when trying to parse a float or double. */ private ParseException floatParseException(final NumberFormatException e) { return parseException("Couldn't parse number: " + e.getMessage()); } /** - * Returns a {@link UnknownFieldParseException} with the line and column - * numbers of the previous token in the description, and the unknown field - * name, suitable for throwing. + * Returns a {@link UnknownFieldParseException} with the line and column numbers of the previous + * token in the description, and the unknown field name, suitable for throwing. */ public UnknownFieldParseException unknownFieldParseExceptionPreviousToken( final String unknownField, final String description) { // Note: People generally prefer one-based line and column numbers. return new UnknownFieldParseException( - previousLine + 1, previousColumn + 1, unknownField, description); + previousLine + 1, previousColumn + 1, unknownField, description); } } @@ -1123,47 +1047,39 @@ public final class TextFormat { /** * Create a new instance * - * @param line the line number where the parse error occurred, - * using 1-offset. - * @param column the column number where the parser error occurred, - * using 1-offset. + * @param line the line number where the parse error occurred, using 1-offset. + * @param column the column number where the parser error occurred, using 1-offset. */ - public ParseException(final int line, final int column, - final String message) { + public ParseException(final int line, final int column, final String message) { super(Integer.toString(line) + ":" + column + ": " + message); this.line = line; this.column = column; } /** - * Return the line where the parse exception occurred, or -1 when - * none is provided. The value is specified as 1-offset, so the first - * line is line 1. + * Return the line where the parse exception occurred, or -1 when none is provided. The value is + * specified as 1-offset, so the first line is line 1. */ public int getLine() { return line; } /** - * Return the column where the parse exception occurred, or -1 when - * none is provided. The value is specified as 1-offset, so the first - * line is line 1. + * Return the column where the parse exception occurred, or -1 when none is provided. The value + * is specified as 1-offset, so the first line is line 1. */ public int getColumn() { return column; } } - /** - * Thrown when encountering an unknown field while parsing - * a text format message. - */ + /** Thrown when encountering an unknown field while parsing a text format message. */ public static class UnknownFieldParseException extends ParseException { private final String unknownField; /** - * Create a new instance, with -1 as the line and column numbers, and an - * empty unknown field name. + * Create a new instance, with -1 as the line and column numbers, and an empty unknown field + * name. */ public UnknownFieldParseException(final String message) { this(-1, -1, "", message); @@ -1172,21 +1088,18 @@ public final class TextFormat { /** * Create a new instance * - * @param line the line number where the parse error occurred, - * using 1-offset. - * @param column the column number where the parser error occurred, - * using 1-offset. + * @param line the line number where the parse error occurred, using 1-offset. + * @param column the column number where the parser error occurred, using 1-offset. * @param unknownField the name of the unknown field found while parsing. */ - public UnknownFieldParseException(final int line, final int column, - final String unknownField, final String message) { + public UnknownFieldParseException( + final int line, final int column, final String unknownField, final String message) { super(line, column, message); this.unknownField = unknownField; } /** - * Return the name of the unknown field encountered while parsing the - * protocol buffer string. + * Return the name of the unknown field encountered while parsing the protocol buffer string. */ public String getUnknownField() { return unknownField; @@ -1196,30 +1109,21 @@ public final class TextFormat { private static final Parser PARSER = Parser.newBuilder().build(); /** - * Return a {@link Parser} instance which can parse text-format - * messages. The returned instance is thread-safe. + * Return a {@link Parser} instance which can parse text-format messages. The returned instance is + * thread-safe. */ public static Parser getParser() { return PARSER; } - /** - * Parse a text-format message from {@code input} and merge the contents - * into {@code builder}. - */ - public static void merge(final Readable input, - final Message.Builder builder) - throws IOException { + /** Parse a text-format message from {@code input} and merge the contents into {@code builder}. */ + public static void merge(final Readable input, final Message.Builder builder) throws IOException { PARSER.merge(input, builder); } - /** - * Parse a text-format message from {@code input} and merge the contents - * into {@code builder}. - */ - public static void merge(final CharSequence input, - final Message.Builder builder) - throws ParseException { + /** Parse a text-format message from {@code input} and merge the contents into {@code builder}. */ + public static void merge(final CharSequence input, final Message.Builder builder) + throws ParseException { PARSER.merge(input, builder); } @@ -1228,11 +1132,9 @@ public final class TextFormat { * * @return the parsed message, guaranteed initialized */ - public static T parse(final CharSequence input, - final Class protoClass) - throws ParseException { - Message.Builder builder = - Internal.getDefaultInstance(protoClass).newBuilderForType(); + public static T parse(final CharSequence input, final Class protoClass) + throws ParseException { + Message.Builder builder = Internal.getDefaultInstance(protoClass).newBuilderForType(); merge(input, builder); @SuppressWarnings("unchecked") T output = (T) builder.build(); @@ -1240,33 +1142,33 @@ public final class TextFormat { } /** - * Parse a text-format message from {@code input} and merge the contents - * into {@code builder}. Extensions will be recognized if they are - * registered in {@code extensionRegistry}. + * Parse a text-format message from {@code input} and merge the contents into {@code builder}. + * Extensions will be recognized if they are registered in {@code extensionRegistry}. */ - public static void merge(final Readable input, - final ExtensionRegistry extensionRegistry, - final Message.Builder builder) - throws IOException { + public static void merge( + final Readable input, + final ExtensionRegistry extensionRegistry, + final Message.Builder builder) + throws IOException { PARSER.merge(input, extensionRegistry, builder); } /** - * Parse a text-format message from {@code input} and merge the contents - * into {@code builder}. Extensions will be recognized if they are - * registered in {@code extensionRegistry}. + * Parse a text-format message from {@code input} and merge the contents into {@code builder}. + * Extensions will be recognized if they are registered in {@code extensionRegistry}. */ - public static void merge(final CharSequence input, - final ExtensionRegistry extensionRegistry, - final Message.Builder builder) - throws ParseException { + public static void merge( + final CharSequence input, + final ExtensionRegistry extensionRegistry, + final Message.Builder builder) + throws ParseException { PARSER.merge(input, extensionRegistry, builder); } /** - * Parse a text-format message from {@code input}. Extensions will be - * recognized if they are registered in {@code extensionRegistry}. + * Parse a text-format message from {@code input}. Extensions will be recognized if they are + * registered in {@code extensionRegistry}. * * @return the parsed message, guaranteed initialized */ @@ -1275,8 +1177,7 @@ public final class TextFormat { final ExtensionRegistry extensionRegistry, final Class protoClass) throws ParseException { - Message.Builder builder = - Internal.getDefaultInstance(protoClass).newBuilderForType(); + Message.Builder builder = Internal.getDefaultInstance(protoClass).newBuilderForType(); merge(input, extensionRegistry, builder); @SuppressWarnings("unchecked") T output = (T) builder.build(); @@ -1285,22 +1186,22 @@ public final class TextFormat { /** - * Parser for text-format proto2 instances. This class is thread-safe. - * The implementation largely follows google/protobuf/text_format.cc. + * Parser for text-format proto2 instances. This class is thread-safe. The implementation largely + * follows google/protobuf/text_format.cc. * - *

Use {@link TextFormat#getParser()} to obtain the default parser, or - * {@link Builder} to control the parser behavior. + *

Use {@link TextFormat#getParser()} to obtain the default parser, or {@link Builder} to + * control the parser behavior. */ public static class Parser { /** - * Determines if repeated values for non-repeated fields and - * oneofs are permitted. For example, given required/optional field "foo" - * and a oneof containing "baz" and "qux": + * Determines if repeated values for non-repeated fields and oneofs are permitted. For example, + * given required/optional field "foo" and a oneof containing "baz" and "qux": + * *

    - *
  • "foo: 1 foo: 2" - *
  • "baz: 1 qux: 2" - *
  • merging "foo: 2" into a proto in which foo is already set, or - *
  • merging "qux: 2" into a proto in which baz is already set. + *
  • "foo: 1 foo: 2" + *
  • "baz: 1 qux: 2" + *
  • merging "foo: 2" into a proto in which foo is already set, or + *
  • merging "qux: 2" into a proto in which baz is already set. *
*/ public enum SingularOverwritePolicy { @@ -1326,16 +1227,12 @@ public final class TextFormat { this.parseInfoTreeBuilder = parseInfoTreeBuilder; } - /** - * Returns a new instance of {@link Builder}. - */ + /** Returns a new instance of {@link Builder}. */ public static Builder newBuilder() { return new Builder(); } - /** - * Builder that can be used to obtain new instances of {@link Parser}. - */ + /** Builder that can be used to obtain new instances of {@link Parser}. */ public static class Builder { private boolean allowUnknownFields = false; private boolean allowUnknownEnumValues = false; @@ -1344,16 +1241,13 @@ public final class TextFormat { private TextFormatParseInfoTree.Builder parseInfoTreeBuilder = null; - /** - * Sets parser behavior when a non-repeated field appears more than once. - */ + /** Sets parser behavior when a non-repeated field appears more than once. */ public Builder setSingularOverwritePolicy(SingularOverwritePolicy p) { this.singularOverwritePolicy = p; return this; } - public Builder setParseInfoTreeBuilder( - TextFormatParseInfoTree.Builder parseInfoTreeBuilder) { + public Builder setParseInfoTreeBuilder(TextFormatParseInfoTree.Builder parseInfoTreeBuilder) { this.parseInfoTreeBuilder = parseInfoTreeBuilder; return this; } @@ -1368,34 +1262,29 @@ public final class TextFormat { } /** - * Parse a text-format message from {@code input} and merge the contents - * into {@code builder}. + * Parse a text-format message from {@code input} and merge the contents into {@code builder}. */ - public void merge(final Readable input, - final Message.Builder builder) - throws IOException { + public void merge(final Readable input, final Message.Builder builder) throws IOException { merge(input, ExtensionRegistry.getEmptyRegistry(), builder); } /** - * Parse a text-format message from {@code input} and merge the contents - * into {@code builder}. + * Parse a text-format message from {@code input} and merge the contents into {@code builder}. */ - public void merge(final CharSequence input, - final Message.Builder builder) - throws ParseException { + public void merge(final CharSequence input, final Message.Builder builder) + throws ParseException { merge(input, ExtensionRegistry.getEmptyRegistry(), builder); } /** - * Parse a text-format message from {@code input} and merge the contents - * into {@code builder}. Extensions will be recognized if they are - * registered in {@code extensionRegistry}. + * Parse a text-format message from {@code input} and merge the contents into {@code builder}. + * Extensions will be recognized if they are registered in {@code extensionRegistry}. */ - public void merge(final Readable input, - final ExtensionRegistry extensionRegistry, - final Message.Builder builder) - throws IOException { + public void merge( + final Readable input, + final ExtensionRegistry extensionRegistry, + final Message.Builder builder) + throws IOException { // Read the entire input to a String then parse that. // If StreamTokenizer were not quite so crippled, or if there were a kind @@ -1412,8 +1301,7 @@ public final class TextFormat { // TODO(chrisn): See if working around java.io.Reader#read(CharBuffer) // overhead is worthwhile - private static StringBuilder toStringBuilder(final Readable input) - throws IOException { + private static StringBuilder toStringBuilder(final Readable input) throws IOException { final StringBuilder text = new StringBuilder(); final CharBuffer buffer = CharBuffer.allocate(BUFFER_SIZE); while (true) { @@ -1429,8 +1317,7 @@ public final class TextFormat { // Check both unknown fields and unknown extensions and log warning messages // or throw exceptions according to the flag. - private void checkUnknownFields(final List unknownFields) - throws ParseException { + private void checkUnknownFields(final List unknownFields) throws ParseException { if (unknownFields.isEmpty()) { return; } @@ -1441,7 +1328,7 @@ public final class TextFormat { } if (allowUnknownFields) { - logger.warning(msg.toString()); + logger.warning(msg.toString()); } else { String[] lineColumn = unknownFields.get(0).split(":"); throw new ParseException( @@ -1450,17 +1337,16 @@ public final class TextFormat { } /** - * Parse a text-format message from {@code input} and merge the contents - * into {@code builder}. Extensions will be recognized if they are - * registered in {@code extensionRegistry}. + * Parse a text-format message from {@code input} and merge the contents into {@code builder}. + * Extensions will be recognized if they are registered in {@code extensionRegistry}. */ - public void merge(final CharSequence input, - final ExtensionRegistry extensionRegistry, - final Message.Builder builder) - throws ParseException { + public void merge( + final CharSequence input, + final ExtensionRegistry extensionRegistry, + final Message.Builder builder) + throws ParseException { final Tokenizer tokenizer = new Tokenizer(input); - MessageReflection.BuilderAdapter target = - new MessageReflection.BuilderAdapter(builder); + MessageReflection.BuilderAdapter target = new MessageReflection.BuilderAdapter(builder); List unknownFields = new ArrayList(); @@ -1472,29 +1358,24 @@ public final class TextFormat { } - /** - * Parse a single field from {@code tokenizer} and merge it into - * {@code builder}. - */ - private void mergeField(final Tokenizer tokenizer, - final ExtensionRegistry extensionRegistry, - final MessageReflection.MergeTarget target, - List unknownFields) - throws ParseException { - mergeField(tokenizer, extensionRegistry, target, parseInfoTreeBuilder, - unknownFields); + /** Parse a single field from {@code tokenizer} and merge it into {@code builder}. */ + private void mergeField( + final Tokenizer tokenizer, + final ExtensionRegistry extensionRegistry, + final MessageReflection.MergeTarget target, + List unknownFields) + throws ParseException { + mergeField(tokenizer, extensionRegistry, target, parseInfoTreeBuilder, unknownFields); } - /** - * Parse a single field from {@code tokenizer} and merge it into - * {@code target}. - */ - private void mergeField(final Tokenizer tokenizer, - final ExtensionRegistry extensionRegistry, - final MessageReflection.MergeTarget target, - TextFormatParseInfoTree.Builder parseTreeBuilder, - List unknownFields) - throws ParseException { + /** Parse a single field from {@code tokenizer} and merge it into {@code target}. */ + private void mergeField( + final Tokenizer tokenizer, + final ExtensionRegistry extensionRegistry, + final MessageReflection.MergeTarget target, + TextFormatParseInfoTree.Builder parseTreeBuilder, + List unknownFields) + throws ParseException { FieldDescriptor field = null; int startLine = tokenizer.getLine(); int startColumn = tokenizer.getColumn(); @@ -1503,15 +1384,13 @@ public final class TextFormat { if (tokenizer.tryConsume("[")) { // An extension. - final StringBuilder name = - new StringBuilder(tokenizer.consumeIdentifier()); + final StringBuilder name = new StringBuilder(tokenizer.consumeIdentifier()); while (tokenizer.tryConsume(".")) { name.append('.'); name.append(tokenizer.consumeIdentifier()); } - extension = target.findExtensionByName( - extensionRegistry, name.toString()); + extension = target.findExtensionByName(extensionRegistry, name.toString()); if (extension == null) { unknownFields.add( @@ -1526,8 +1405,11 @@ public final class TextFormat { } else { if (extension.descriptor.getContainingType() != type) { throw tokenizer.parseExceptionPreviousToken( - "Extension \"" + name + "\" does not extend message type \"" - + type.getFullName() + "\"."); + "Extension \"" + + name + + "\" does not extend message type \"" + + type.getFullName() + + "\"."); } field = extension.descriptor; } @@ -1551,7 +1433,8 @@ public final class TextFormat { } } // Again, special-case group names as described above. - if (field != null && field.getType() == FieldDescriptor.Type.GROUP + if (field != null + && field.getType() == FieldDescriptor.Type.GROUP && !field.getMessageType().getName().equals(name)) { field = null; } @@ -1576,9 +1459,7 @@ public final class TextFormat { // start with "{" or "<" which indicates the beginning of a message body. // If there is no ":" or there is a "{" or "<" after ":", this field has // to be a message or the input is ill-formed. - if (tokenizer.tryConsume(":") - && !tokenizer.lookingAt("{") - && !tokenizer.lookingAt("<")) { + if (tokenizer.tryConsume(":") && !tokenizer.lookingAt("{") && !tokenizer.lookingAt("<")) { skipFieldValue(tokenizer); } else { skipFieldMessage(tokenizer); @@ -1588,25 +1469,42 @@ public final class TextFormat { // Handle potential ':'. if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { - tokenizer.tryConsume(":"); // optional + tokenizer.tryConsume(":"); // optional if (parseTreeBuilder != null) { TextFormatParseInfoTree.Builder childParseTreeBuilder = parseTreeBuilder.getBuilderForSubMessageField(field); - consumeFieldValues(tokenizer, extensionRegistry, target, field, extension, - childParseTreeBuilder, unknownFields); + consumeFieldValues( + tokenizer, + extensionRegistry, + target, + field, + extension, + childParseTreeBuilder, + unknownFields); } else { - consumeFieldValues(tokenizer, extensionRegistry, target, field, extension, - parseTreeBuilder, unknownFields); + consumeFieldValues( + tokenizer, + extensionRegistry, + target, + field, + extension, + parseTreeBuilder, + unknownFields); } } else { - tokenizer.consume(":"); // required - consumeFieldValues(tokenizer, extensionRegistry, target, field, - extension, parseTreeBuilder, unknownFields); + tokenizer.consume(":"); // required + consumeFieldValues( + tokenizer, + extensionRegistry, + target, + field, + extension, + parseTreeBuilder, + unknownFields); } if (parseTreeBuilder != null) { - parseTreeBuilder.setLocation( - field, TextFormatParseLocation.create(startLine, startColumn)); + parseTreeBuilder.setLocation(field, TextFormatParseLocation.create(startLine, startColumn)); } // For historical reasons, fields may optionally be separated by commas or @@ -1617,8 +1515,7 @@ public final class TextFormat { } /** - * Parse a one or more field values from {@code tokenizer} and merge it into - * {@code builder}. + * Parse a one or more field values from {@code tokenizer} and merge it into {@code builder}. */ private void consumeFieldValues( final Tokenizer tokenizer, @@ -1632,7 +1529,7 @@ public final class TextFormat { // Support specifying repeated field values as a comma-separated list. // Ex."foo: [1, 2, 3]" if (field.isRepeated() && tokenizer.tryConsume("[")) { - if (!tokenizer.tryConsume("]")) { // Allow "foo: []" to be treated as empty. + if (!tokenizer.tryConsume("]")) { // Allow "foo: []" to be treated as empty. while (true) { consumeFieldValue( tokenizer, @@ -1650,15 +1547,18 @@ public final class TextFormat { } } } else { - consumeFieldValue(tokenizer, extensionRegistry, target, field, - extension, parseTreeBuilder, unknownFields); + consumeFieldValue( + tokenizer, + extensionRegistry, + target, + field, + extension, + parseTreeBuilder, + unknownFields); } } - /** - * Parse a single field value from {@code tokenizer} and merge it into - * {@code builder}. - */ + /** Parse a single field value from {@code tokenizer} and merge it into {@code builder}. */ private void consumeFieldValue( final Tokenizer tokenizer, final ExtensionRegistry extensionRegistry, @@ -1680,16 +1580,15 @@ public final class TextFormat { } final MessageReflection.MergeTarget subField; - subField = target.newMergeTargetForField(field, - (extension == null) ? null : extension.defaultInstance); + subField = + target.newMergeTargetForField( + field, (extension == null) ? null : extension.defaultInstance); while (!tokenizer.tryConsume(endToken)) { if (tokenizer.atEnd()) { - throw tokenizer.parseException( - "Expected \"" + endToken + "\"."); + throw tokenizer.parseException("Expected \"" + endToken + "\"."); } - mergeField(tokenizer, extensionRegistry, subField, parseTreeBuilder, - unknownFields); + mergeField(tokenizer, extensionRegistry, subField, parseTreeBuilder, unknownFields); } value = subField.finish(); @@ -1794,28 +1693,28 @@ public final class TextFormat { // TODO(b/29122459): If field.isMapField() and FORBID_SINGULAR_OVERWRITES mode, // check for duplicate map keys here. target.addRepeatedField(field, value); - } else if ((singularOverwritePolicy - == SingularOverwritePolicy.FORBID_SINGULAR_OVERWRITES) + } else if ((singularOverwritePolicy == SingularOverwritePolicy.FORBID_SINGULAR_OVERWRITES) && target.hasField(field)) { - throw tokenizer.parseExceptionPreviousToken("Non-repeated field \"" - + field.getFullName() + "\" cannot be overwritten."); - } else if ((singularOverwritePolicy - == SingularOverwritePolicy.FORBID_SINGULAR_OVERWRITES) + throw tokenizer.parseExceptionPreviousToken( + "Non-repeated field \"" + field.getFullName() + "\" cannot be overwritten."); + } else if ((singularOverwritePolicy == SingularOverwritePolicy.FORBID_SINGULAR_OVERWRITES) && field.getContainingOneof() != null && target.hasOneof(field.getContainingOneof())) { Descriptors.OneofDescriptor oneof = field.getContainingOneof(); - throw tokenizer.parseExceptionPreviousToken("Field \"" - + field.getFullName() + "\" is specified along with field \"" - + target.getOneofFieldDescriptor(oneof).getFullName() - + "\", another member of oneof \"" + oneof.getName() + "\"."); + throw tokenizer.parseExceptionPreviousToken( + "Field \"" + + field.getFullName() + + "\" is specified along with field \"" + + target.getOneofFieldDescriptor(oneof).getFullName() + + "\", another member of oneof \"" + + oneof.getName() + + "\"."); } else { target.setField(field, value); } } - /** - * Skips the next field including the field's name and value. - */ + /** Skips the next field including the field's name and value. */ private void skipField(Tokenizer tokenizer) throws ParseException { if (tokenizer.tryConsume("[")) { // Extension name. @@ -1833,9 +1732,7 @@ public final class TextFormat { // start with "{" or "<" which indicates the beginning of a message body. // If there is no ":" or there is a "{" or "<" after ":", this field has // to be a message or the input is ill-formed. - if (tokenizer.tryConsume(":") - && !tokenizer.lookingAt("<") - && !tokenizer.lookingAt("{")) { + if (tokenizer.tryConsume(":") && !tokenizer.lookingAt("<") && !tokenizer.lookingAt("{")) { skipFieldValue(tokenizer); } else { skipFieldMessage(tokenizer); @@ -1848,8 +1745,7 @@ public final class TextFormat { } /** - * Skips the whole body of a message including the beginning delimiter and - * the ending delimiter. + * Skips the whole body of a message including the beginning delimiter and the ending delimiter. */ private void skipFieldMessage(Tokenizer tokenizer) throws ParseException { final String delimiter; @@ -1865,21 +1761,18 @@ public final class TextFormat { tokenizer.consume(delimiter); } - /** - * Skips a field value. - */ + /** Skips a field value. */ private void skipFieldValue(Tokenizer tokenizer) throws ParseException { if (tokenizer.tryConsumeString()) { while (tokenizer.tryConsumeString()) {} return; } - if (!tokenizer.tryConsumeIdentifier() // includes enum & boolean - && !tokenizer.tryConsumeInt64() // includes int32 - && !tokenizer.tryConsumeUInt64() // includes uint32 + if (!tokenizer.tryConsumeIdentifier() // includes enum & boolean + && !tokenizer.tryConsumeInt64() // includes int32 + && !tokenizer.tryConsumeUInt64() // includes uint32 && !tokenizer.tryConsumeDouble() && !tokenizer.tryConsumeFloat()) { - throw tokenizer.parseException( - "Invalid field value: " + tokenizer.currentToken); + throw tokenizer.parseException("Invalid field value: " + tokenizer.currentToken); } } } @@ -1891,28 +1784,23 @@ public final class TextFormat { // them. /** - * Escapes bytes in the format used in protocol buffer text format, which - * is the same as the format used for C string literals. All bytes - * that are not printable 7-bit ASCII characters are escaped, as well as - * backslash, single-quote, and double-quote characters. Characters for - * which no defined short-hand escape sequence is defined will be escaped - * using 3-digit octal sequences. + * Escapes bytes in the format used in protocol buffer text format, which is the same as the + * format used for C string literals. All bytes that are not printable 7-bit ASCII characters are + * escaped, as well as backslash, single-quote, and double-quote characters. Characters for which + * no defined short-hand escape sequence is defined will be escaped using 3-digit octal sequences. */ public static String escapeBytes(ByteString input) { return TextFormatEscaper.escapeBytes(input); } - /** - * Like {@link #escapeBytes(ByteString)}, but used for byte array. - */ + /** Like {@link #escapeBytes(ByteString)}, but used for byte array. */ public static String escapeBytes(byte[] input) { return TextFormatEscaper.escapeBytes(input); } /** - * Un-escape a byte sequence as escaped using - * {@link #escapeBytes(ByteString)}. Two-digit hex escapes (starting with - * "\x") are also recognized. + * Un-escape a byte sequence as escaped using {@link #escapeBytes(ByteString)}. Two-digit hex + * escapes (starting with "\x") are also recognized. */ public static ByteString unescapeBytes(final CharSequence charString) throws InvalidEscapeSequenceException { @@ -1948,16 +1836,36 @@ public final class TextFormat { result[pos++] = (byte) code; } else { switch (c) { - case 'a' : result[pos++] = 0x07; break; - case 'b' : result[pos++] = '\b'; break; - case 'f' : result[pos++] = '\f'; break; - case 'n' : result[pos++] = '\n'; break; - case 'r' : result[pos++] = '\r'; break; - case 't' : result[pos++] = '\t'; break; - case 'v' : result[pos++] = 0x0b; break; - case '\\': result[pos++] = '\\'; break; - case '\'': result[pos++] = '\''; break; - case '"' : result[pos++] = '\"'; break; + case 'a': + result[pos++] = 0x07; + break; + case 'b': + result[pos++] = '\b'; + break; + case 'f': + result[pos++] = '\f'; + break; + case 'n': + result[pos++] = '\n'; + break; + case 'r': + result[pos++] = '\r'; + break; + case 't': + result[pos++] = '\t'; + break; + case 'v': + result[pos++] = 0x0b; + break; + case '\\': + result[pos++] = '\\'; + break; + case '\'': + result[pos++] = '\''; + break; + case '"': + result[pos++] = '\"'; + break; case 'x': // hex escape @@ -1991,13 +1899,13 @@ public final class TextFormat { } return result.length == pos - ? ByteString.wrap(result) // This reference has not been out of our control. + ? ByteString.wrap(result) // This reference has not been out of our control. : ByteString.copyFrom(result, 0, pos); } /** - * Thrown by {@link TextFormat#unescapeBytes} and - * {@link TextFormat#unescapeText} when an invalid escape sequence is seen. + * Thrown by {@link TextFormat#unescapeBytes} and {@link TextFormat#unescapeText} when an invalid + * escape sequence is seen. */ public static class InvalidEscapeSequenceException extends IOException { private static final long serialVersionUID = -8164033650142593304L; @@ -2008,27 +1916,24 @@ public final class TextFormat { } /** - * Like {@link #escapeBytes(ByteString)}, but escapes a text string. - * Non-ASCII characters are first encoded as UTF-8, then each byte is escaped - * individually as a 3-digit octal escape. Yes, it's weird. + * Like {@link #escapeBytes(ByteString)}, but escapes a text string. Non-ASCII characters are + * first encoded as UTF-8, then each byte is escaped individually as a 3-digit octal escape. Yes, + * it's weird. */ static String escapeText(final String input) { return escapeBytes(ByteString.copyFromUtf8(input)); } - /** - * Escape double quotes and backslashes in a String for unicode output of a message. - */ + /** Escape double quotes and backslashes in a String for unicode output of a message. */ public static String escapeDoubleQuotesAndBackslashes(final String input) { return TextFormatEscaper.escapeDoubleQuotesAndBackslashes(input); } /** - * Un-escape a text string as escaped using {@link #escapeText(String)}. - * Two-digit hex escapes (starting with "\x") are also recognized. + * Un-escape a text string as escaped using {@link #escapeText(String)}. Two-digit hex escapes + * (starting with "\x") are also recognized. */ - static String unescapeText(final String input) - throws InvalidEscapeSequenceException { + static String unescapeText(final String input) throws InvalidEscapeSequenceException { return unescapeBytes(input).toStringUtf8(); } @@ -2039,15 +1944,12 @@ public final class TextFormat { /** Is this a hex digit? */ private static boolean isHex(final byte c) { - return ('0' <= c && c <= '9') - || ('a' <= c && c <= 'f') - || ('A' <= c && c <= 'F'); + return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F'); } /** - * Interpret a character as a digit (in any base up to 36) and return the - * numeric value. This is like {@code Character.digit()} but we don't accept - * non-ASCII digits. + * Interpret a character as a digit (in any base up to 36) and return the numeric value. This is + * like {@code Character.digit()} but we don't accept non-ASCII digits. */ private static int digitValue(final byte c) { if ('0' <= c && c <= '9') { @@ -2060,49 +1962,45 @@ public final class TextFormat { } /** - * Parse a 32-bit signed integer from the text. Unlike the Java standard - * {@code Integer.parseInt()}, this function recognizes the prefixes "0x" - * and "0" to signify hexadecimal and octal numbers, respectively. + * Parse a 32-bit signed integer from the text. Unlike the Java standard {@code + * Integer.parseInt()}, this function recognizes the prefixes "0x" and "0" to signify hexadecimal + * and octal numbers, respectively. */ static int parseInt32(final String text) throws NumberFormatException { return (int) parseInteger(text, true, false); } /** - * Parse a 32-bit unsigned integer from the text. Unlike the Java standard - * {@code Integer.parseInt()}, this function recognizes the prefixes "0x" - * and "0" to signify hexadecimal and octal numbers, respectively. The - * result is coerced to a (signed) {@code int} when returned since Java has - * no unsigned integer type. + * Parse a 32-bit unsigned integer from the text. Unlike the Java standard {@code + * Integer.parseInt()}, this function recognizes the prefixes "0x" and "0" to signify hexadecimal + * and octal numbers, respectively. The result is coerced to a (signed) {@code int} when returned + * since Java has no unsigned integer type. */ static int parseUInt32(final String text) throws NumberFormatException { return (int) parseInteger(text, false, false); } /** - * Parse a 64-bit signed integer from the text. Unlike the Java standard - * {@code Integer.parseInt()}, this function recognizes the prefixes "0x" - * and "0" to signify hexadecimal and octal numbers, respectively. + * Parse a 64-bit signed integer from the text. Unlike the Java standard {@code + * Integer.parseInt()}, this function recognizes the prefixes "0x" and "0" to signify hexadecimal + * and octal numbers, respectively. */ static long parseInt64(final String text) throws NumberFormatException { return parseInteger(text, true, true); } /** - * Parse a 64-bit unsigned integer from the text. Unlike the Java standard - * {@code Integer.parseInt()}, this function recognizes the prefixes "0x" - * and "0" to signify hexadecimal and octal numbers, respectively. The - * result is coerced to a (signed) {@code long} when returned since Java has - * no unsigned long type. + * Parse a 64-bit unsigned integer from the text. Unlike the Java standard {@code + * Integer.parseInt()}, this function recognizes the prefixes "0x" and "0" to signify hexadecimal + * and octal numbers, respectively. The result is coerced to a (signed) {@code long} when returned + * since Java has no unsigned long type. */ static long parseUInt64(final String text) throws NumberFormatException { return parseInteger(text, false, true); } - private static long parseInteger(final String text, - final boolean isSigned, - final boolean isLong) - throws NumberFormatException { + private static long parseInteger(final String text, final boolean isSigned, final boolean isLong) + throws NumberFormatException { int pos = 0; boolean negative = false; @@ -2139,12 +2037,12 @@ public final class TextFormat { if (isSigned) { if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) { throw new NumberFormatException( - "Number out of range for 32-bit signed integer: " + text); + "Number out of range for 32-bit signed integer: " + text); } } else { if (result >= (1L << 32) || result < 0) { throw new NumberFormatException( - "Number out of range for 32-bit unsigned integer: " + text); + "Number out of range for 32-bit unsigned integer: " + text); } } } @@ -2159,24 +2057,24 @@ public final class TextFormat { if (isSigned) { if (bigValue.bitLength() > 31) { throw new NumberFormatException( - "Number out of range for 32-bit signed integer: " + text); + "Number out of range for 32-bit signed integer: " + text); } } else { if (bigValue.bitLength() > 32) { throw new NumberFormatException( - "Number out of range for 32-bit unsigned integer: " + text); + "Number out of range for 32-bit unsigned integer: " + text); } } } else { if (isSigned) { if (bigValue.bitLength() > 63) { throw new NumberFormatException( - "Number out of range for 64-bit signed integer: " + text); + "Number out of range for 64-bit signed integer: " + text); } } else { if (bigValue.bitLength() > 64) { throw new NumberFormatException( - "Number out of range for 64-bit unsigned integer: " + text); + "Number out of range for 64-bit unsigned integer: " + text); } } } diff --git a/java/core/src/main/java/com/google/protobuf/TextFormatEscaper.java b/java/core/src/main/java/com/google/protobuf/TextFormatEscaper.java index da9ceadd16..2501ec936c 100644 --- a/java/core/src/main/java/com/google/protobuf/TextFormatEscaper.java +++ b/java/core/src/main/java/com/google/protobuf/TextFormatEscaper.java @@ -30,41 +30,58 @@ package com.google.protobuf; -/** - * Provide text format escaping support for proto2 instances. - */ +/** Provide text format escaping support for proto2 instances. */ final class TextFormatEscaper { private TextFormatEscaper() {} private interface ByteSequence { int size(); + byte byteAt(int offset); } /** - * Escapes bytes in the format used in protocol buffer text format, which - * is the same as the format used for C string literals. All bytes - * that are not printable 7-bit ASCII characters are escaped, as well as - * backslash, single-quote, and double-quote characters. Characters for - * which no defined short-hand escape sequence is defined will be escaped - * using 3-digit octal sequences. + * Escapes bytes in the format used in protocol buffer text format, which is the same as the + * format used for C string literals. All bytes that are not printable 7-bit ASCII characters are + * escaped, as well as backslash, single-quote, and double-quote characters. Characters for which + * no defined short-hand escape sequence is defined will be escaped using 3-digit octal sequences. */ static String escapeBytes(final ByteSequence input) { final StringBuilder builder = new StringBuilder(input.size()); for (int i = 0; i < input.size(); i++) { final byte b = input.byteAt(i); switch (b) { - // Java does not recognize \a or \v, apparently. - case 0x07: builder.append("\\a"); break; - case '\b': builder.append("\\b"); break; - case '\f': builder.append("\\f"); break; - case '\n': builder.append("\\n"); break; - case '\r': builder.append("\\r"); break; - case '\t': builder.append("\\t"); break; - case 0x0b: builder.append("\\v"); break; - case '\\': builder.append("\\\\"); break; - case '\'': builder.append("\\\'"); break; - case '"' : builder.append("\\\""); break; + // Java does not recognize \a or \v, apparently. + case 0x07: + builder.append("\\a"); + break; + case '\b': + builder.append("\\b"); + break; + case '\f': + builder.append("\\f"); + break; + case '\n': + builder.append("\\n"); + break; + case '\r': + builder.append("\\r"); + break; + case '\t': + builder.append("\\t"); + break; + case 0x0b: + builder.append("\\v"); + break; + case '\\': + builder.append("\\\\"); + break; + case '\'': + builder.append("\\\'"); + break; + case '"': + builder.append("\\\""); + break; default: // Only ASCII characters between 0x20 (space) and 0x7e (tilde) are // printable. Other byte values must be escaped. @@ -83,54 +100,52 @@ final class TextFormatEscaper { } /** - * Escapes bytes in the format used in protocol buffer text format, which - * is the same as the format used for C string literals. All bytes - * that are not printable 7-bit ASCII characters are escaped, as well as - * backslash, single-quote, and double-quote characters. Characters for - * which no defined short-hand escape sequence is defined will be escaped - * using 3-digit octal sequences. + * Escapes bytes in the format used in protocol buffer text format, which is the same as the + * format used for C string literals. All bytes that are not printable 7-bit ASCII characters are + * escaped, as well as backslash, single-quote, and double-quote characters. Characters for which + * no defined short-hand escape sequence is defined will be escaped using 3-digit octal sequences. */ static String escapeBytes(final ByteString input) { - return escapeBytes(new ByteSequence() { - @Override - public int size() { - return input.size(); - } - @Override - public byte byteAt(int offset) { - return input.byteAt(offset); - } - }); + return escapeBytes( + new ByteSequence() { + @Override + public int size() { + return input.size(); + } + + @Override + public byte byteAt(int offset) { + return input.byteAt(offset); + } + }); } - /** - * Like {@link #escapeBytes(ByteString)}, but used for byte array. - */ + /** Like {@link #escapeBytes(ByteString)}, but used for byte array. */ static String escapeBytes(final byte[] input) { - return escapeBytes(new ByteSequence() { - @Override - public int size() { - return input.length; - } - @Override - public byte byteAt(int offset) { - return input[offset]; - } - }); + return escapeBytes( + new ByteSequence() { + @Override + public int size() { + return input.length; + } + + @Override + public byte byteAt(int offset) { + return input[offset]; + } + }); } /** - * Like {@link #escapeBytes(ByteString)}, but escapes a text string. - * Non-ASCII characters are first encoded as UTF-8, then each byte is escaped - * individually as a 3-digit octal escape. Yes, it's weird. + * Like {@link #escapeBytes(ByteString)}, but escapes a text string. Non-ASCII characters are + * first encoded as UTF-8, then each byte is escaped individually as a 3-digit octal escape. Yes, + * it's weird. */ static String escapeText(final String input) { return escapeBytes(ByteString.copyFromUtf8(input)); } - /** - * Escape double quotes and backslashes in a String for unicode output of a message. - */ + /** Escape double quotes and backslashes in a String for unicode output of a message. */ static String escapeDoubleQuotesAndBackslashes(final String input) { return input.replace("\\", "\\\\").replace("\"", "\\\""); } diff --git a/java/core/src/main/java/com/google/protobuf/TextFormatParseInfoTree.java b/java/core/src/main/java/com/google/protobuf/TextFormatParseInfoTree.java index 0127ce92a3..6ce9f783ac 100644 --- a/java/core/src/main/java/com/google/protobuf/TextFormatParseInfoTree.java +++ b/java/core/src/main/java/com/google/protobuf/TextFormatParseInfoTree.java @@ -31,7 +31,6 @@ package com.google.protobuf; import com.google.protobuf.Descriptors.FieldDescriptor; - import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -39,14 +38,12 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; - /** * Data structure which is populated with the locations of each field value parsed from the text. * - *

The locations of primary fields values are retrieved by {@code getLocation} or - * {@code getLocations}. The locations of sub message values are within nested - * {@code TextFormatParseInfoTree}s and are retrieve by {@code getNestedTree} or - * {@code getNestedTrees}. + *

The locations of primary fields values are retrieved by {@code getLocation} or {@code + * getLocations}. The locations of sub message values are within nested {@code + * TextFormatParseInfoTree}s and are retrieve by {@code getNestedTree} or {@code getNestedTrees}. * *

The {@code TextFormatParseInfoTree} is created by a Builder. */ @@ -90,13 +87,13 @@ public class TextFormatParseInfoTree { this.subtreesFromField = Collections.unmodifiableMap(subs); } - /** - * Retrieve all the locations of a field. - * - * @param fieldDescriptor the the @{link FieldDescriptor} of the desired field - * @return a list of the locations of values of the field. If there are not values - * or the field doesn't exist, an empty list is returned. - */ + /** + * Retrieve all the locations of a field. + * + * @param fieldDescriptor the @{link FieldDescriptor} of the desired field + * @return a list of the locations of values of the field. If there are not values or the field + * doesn't exist, an empty list is returned. + */ public List getLocations(final FieldDescriptor fieldDescriptor) { List result = locationsFromField.get(fieldDescriptor); return (result == null) ? Collections.emptyList() : result; @@ -134,7 +131,7 @@ public class TextFormatParseInfoTree { * @param fieldDescriptor the @{link FieldDescriptor} of the desired sub message * @param index the index of message value. * @return the {@code ParseInfoTree} of the message value. {@code null} is returned if the field - * doesn't exist or the index is out of range. + * doesn't exist or the index is out of range. * @throws IllegalArgumentException if index is out of range */ public TextFormatParseInfoTree getNestedTree(final FieldDescriptor fieldDescriptor, int index) { @@ -151,16 +148,16 @@ public class TextFormatParseInfoTree { } private static T getFromList(List list, int index, FieldDescriptor fieldDescriptor) { - if (index >= list.size() || index < 0) { - throw new IllegalArgumentException(String.format("Illegal index field: %s, index %d", - fieldDescriptor == null ? "" : fieldDescriptor.getName(), index)); + if (index >= list.size() || index < 0) { + throw new IllegalArgumentException( + String.format( + "Illegal index field: %s, index %d", + fieldDescriptor == null ? "" : fieldDescriptor.getName(), index)); } return list.get(index); } - /** - * Builder for a {@link TextFormatParseInfoTree}. - */ + /** Builder for a {@link TextFormatParseInfoTree}. */ public static class Builder { private Map> locationsFromField; @@ -169,9 +166,7 @@ public class TextFormatParseInfoTree { // sub message location information. private Map> subtreeBuildersFromField; - /** - * Create a root level {@ParseInfoTree} builder. - */ + /** Create a root level {@ParseInfoTree} builder. */ private Builder() { locationsFromField = new HashMap>(); subtreeBuildersFromField = new HashMap>(); diff --git a/java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java b/java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java index cce286e10f..eebfb1b545 100644 --- a/java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java +++ b/java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java @@ -39,9 +39,7 @@ import java.util.Arrays; */ public final class TextFormatParseLocation { - /** - * The empty location. - */ + /** The empty location. */ public static final TextFormatParseLocation EMPTY = new TextFormatParseLocation(-1, -1); /** @@ -92,8 +90,7 @@ public final class TextFormatParseLocation { return false; } TextFormatParseLocation that = (TextFormatParseLocation) o; - return (this.line == that.getLine()) - && (this.column == that.getColumn()); + return (this.line == that.getLine()) && (this.column == that.getColumn()); } @Override diff --git a/java/core/src/main/java/com/google/protobuf/UninitializedMessageException.java b/java/core/src/main/java/com/google/protobuf/UninitializedMessageException.java index 5714c063a9..c633a4e890 100644 --- a/java/core/src/main/java/com/google/protobuf/UninitializedMessageException.java +++ b/java/core/src/main/java/com/google/protobuf/UninitializedMessageException.java @@ -34,15 +34,13 @@ import java.util.Collections; import java.util.List; /** - * Thrown when attempting to build a protocol message that is missing required - * fields. This is a {@code RuntimeException} because it normally represents - * a programming error: it happens when some code which constructs a message - * fails to set all the fields. {@code parseFrom()} methods do not - * throw this; they throw an {@link InvalidProtocolBufferException} if - * required fields are missing, because it is not a programming error to - * receive an incomplete message. In other words, - * {@code UninitializedMessageException} should never be thrown by correct - * code, but {@code InvalidProtocolBufferException} might be. + * Thrown when attempting to build a protocol message that is missing required fields. This is a + * {@code RuntimeException} because it normally represents a programming error: it happens when some + * code which constructs a message fails to set all the fields. {@code parseFrom()} methods do + * not throw this; they throw an {@link InvalidProtocolBufferException} if required fields are + * missing, because it is not a programming error to receive an incomplete message. In other words, + * {@code UninitializedMessageException} should never be thrown by correct code, but {@code + * InvalidProtocolBufferException} might be. * * @author kenton@google.com Kenton Varda */ @@ -50,8 +48,9 @@ public class UninitializedMessageException extends RuntimeException { private static final long serialVersionUID = -7466929953374883507L; public UninitializedMessageException(final MessageLite message) { - super("Message was missing required fields. (Lite runtime could not " + - "determine which fields were missing)."); + super( + "Message was missing required fields. (Lite runtime could not " + + "determine which fields were missing)."); missingFields = null; } @@ -63,19 +62,18 @@ public class UninitializedMessageException extends RuntimeException { private final List missingFields; /** - * Get a list of human-readable names of required fields missing from this - * message. Each name is a full path to a field, e.g. "foo.bar[5].baz". - * Returns null if the lite runtime was used, since it lacks the ability to - * find missing fields. + * Get a list of human-readable names of required fields missing from this message. Each name is a + * full path to a field, e.g. "foo.bar[5].baz". Returns null if the lite runtime was used, since + * it lacks the ability to find missing fields. */ public List getMissingFields() { return Collections.unmodifiableList(missingFields); } /** - * Converts this exception to an {@link InvalidProtocolBufferException}. - * When a parsed message is missing required fields, this should be thrown - * instead of {@code UninitializedMessageException}. + * Converts this exception to an {@link InvalidProtocolBufferException}. When a parsed message is + * missing required fields, this should be thrown instead of {@code + * UninitializedMessageException}. */ public InvalidProtocolBufferException asInvalidProtocolBufferException() { return new InvalidProtocolBufferException(getMessage()); @@ -83,8 +81,7 @@ public class UninitializedMessageException extends RuntimeException { /** Construct the description string for this exception. */ private static String buildDescription(final List missingFields) { - final StringBuilder description = - new StringBuilder("Message missing required fields: "); + final StringBuilder description = new StringBuilder("Message missing required fields: "); boolean first = true; for (final String field : missingFields) { if (first) { diff --git a/java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java b/java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java index b3fdebcbb9..39deec0481 100644 --- a/java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java +++ b/java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java @@ -43,14 +43,13 @@ import java.util.Map; import java.util.TreeMap; /** - * {@code UnknownFieldSet} is used to keep track of fields which were seen when - * parsing a protocol message but whose field numbers or types are unrecognized. - * This most frequently occurs when new fields are added to a message type - * and then messages containing those fields are read by old software that was - * compiled before the new types were added. + * {@code UnknownFieldSet} is used to keep track of fields which were seen when parsing a protocol + * message but whose field numbers or types are unrecognized. This most frequently occurs when new + * fields are added to a message type and then messages containing those fields are read by old + * software that was compiled before the new types were added. * - *

Every {@link Message} contains an {@code UnknownFieldSet} (and every - * {@link Message.Builder} contains an {@link Builder}). + *

Every {@link Message} contains an {@code UnknownFieldSet} (and every {@link Message.Builder} + * contains an {@link Builder}). * *

Most users will never need to use this class. * @@ -67,10 +66,7 @@ public final class UnknownFieldSet implements MessageLite { return Builder.create(); } - /** - * Create a new {@link Builder} and initialize it to be a copy - * of {@code copyFrom}. - */ + /** Create a new {@link Builder} and initialize it to be a copy of {@code copyFrom}. */ public static Builder newBuilder(final UnknownFieldSet copyFrom) { return newBuilder().mergeFrom(copyFrom); } @@ -79,22 +75,23 @@ public final class UnknownFieldSet implements MessageLite { public static UnknownFieldSet getDefaultInstance() { return defaultInstance; } + @Override public UnknownFieldSet getDefaultInstanceForType() { return defaultInstance; } + private static final UnknownFieldSet defaultInstance = - new UnknownFieldSet(Collections.emptyMap(), - Collections.emptyMap()); + new UnknownFieldSet( + Collections.emptyMap(), Collections.emptyMap()); /** - * Construct an {@code UnknownFieldSet} around the given map. The map is - * expected to be immutable. + * Construct an {@code UnknownFieldSet} around the given map. The map is expected to be immutable. */ - UnknownFieldSet(final Map fields, - final Map fieldsDescending) { + UnknownFieldSet(final Map fields, final Map fieldsDescending) { this.fields = fields; } + private final Map fields; @@ -103,8 +100,7 @@ public final class UnknownFieldSet implements MessageLite { if (this == other) { return true; } - return (other instanceof UnknownFieldSet) && - fields.equals(((UnknownFieldSet) other).fields); + return (other instanceof UnknownFieldSet) && fields.equals(((UnknownFieldSet) other).fields); } @Override @@ -122,10 +118,7 @@ public final class UnknownFieldSet implements MessageLite { return fields.containsKey(number); } - /** - * Get a field by number. Returns an empty field if not present. Never - * returns {@code null}. - */ + /** Get a field by number. Returns an empty field if not present. Never returns {@code null}. */ public Field getField(final int number) { final Field result = fields.get(number); return (result == null) ? Field.getDefaultInstance() : result; @@ -141,9 +134,8 @@ public final class UnknownFieldSet implements MessageLite { } /** - * Converts the set to a string in protocol buffer text format. This is - * just a trivial wrapper around - * {@link TextFormat#printToString(UnknownFieldSet)}. + * Converts the set to a string in protocol buffer text format. This is just a trivial wrapper + * around {@link TextFormat#printToString(UnknownFieldSet)}. */ @Override public String toString() { @@ -151,26 +143,24 @@ public final class UnknownFieldSet implements MessageLite { } /** - * Serializes the message to a {@code ByteString} and returns it. This is - * just a trivial wrapper around {@link #writeTo(CodedOutputStream)}. + * Serializes the message to a {@code ByteString} and returns it. This is just a trivial wrapper + * around {@link #writeTo(CodedOutputStream)}. */ @Override public ByteString toByteString() { try { - final ByteString.CodedBuilder out = - ByteString.newCodedBuilder(getSerializedSize()); + final ByteString.CodedBuilder out = ByteString.newCodedBuilder(getSerializedSize()); writeTo(out.getCodedOutput()); return out.build(); } catch (final IOException e) { throw new RuntimeException( - "Serializing to a ByteString threw an IOException (should " + - "never happen).", e); + "Serializing to a ByteString threw an IOException (should never happen).", e); } } /** - * Serializes the message to a {@code byte} array and returns it. This is - * just a trivial wrapper around {@link #writeTo(CodedOutputStream)}. + * Serializes the message to a {@code byte} array and returns it. This is just a trivial wrapper + * around {@link #writeTo(CodedOutputStream)}. */ @Override public byte[] toByteArray() { @@ -182,14 +172,13 @@ public final class UnknownFieldSet implements MessageLite { return result; } catch (final IOException e) { throw new RuntimeException( - "Serializing to a byte array threw an IOException " + - "(should never happen).", e); + "Serializing to a byte array threw an IOException (should never happen).", e); } } /** - * Serializes the message and writes it to {@code output}. This is just a - * trivial wrapper around {@link #writeTo(CodedOutputStream)}. + * Serializes the message and writes it to {@code output}. This is just a trivial wrapper around + * {@link #writeTo(CodedOutputStream)}. */ @Override public void writeTo(final OutputStream output) throws IOException { @@ -216,15 +205,10 @@ public final class UnknownFieldSet implements MessageLite { return result; } - /** - * Serializes the set and writes it to {@code output} using - * {@code MessageSet} wire format. - */ - public void writeAsMessageSetTo(final CodedOutputStream output) - throws IOException { + /** Serializes the set and writes it to {@code output} using {@code MessageSet} wire format. */ + public void writeAsMessageSetTo(final CodedOutputStream output) throws IOException { for (final Map.Entry entry : fields.entrySet()) { - entry.getValue().writeAsMessageSetExtensionTo( - entry.getKey(), output); + entry.getValue().writeAsMessageSetExtensionTo(entry.getKey(), output); } } @@ -233,8 +217,7 @@ public final class UnknownFieldSet implements MessageLite { public int getSerializedSizeAsMessageSet() { int result = 0; for (final Map.Entry entry : fields.entrySet()) { - result += entry.getValue().getSerializedSizeAsMessageSetExtension( - entry.getKey()); + result += entry.getValue().getSerializedSizeAsMessageSetExtension(entry.getKey()); } return result; } @@ -247,8 +230,7 @@ public final class UnknownFieldSet implements MessageLite { } /** Parse an {@code UnknownFieldSet} from the given input stream. */ - public static UnknownFieldSet parseFrom(final CodedInputStream input) - throws IOException { + public static UnknownFieldSet parseFrom(final CodedInputStream input) throws IOException { return newBuilder().mergeFrom(input).build(); } @@ -259,14 +241,12 @@ public final class UnknownFieldSet implements MessageLite { } /** Parse {@code data} as an {@code UnknownFieldSet} and return it. */ - public static UnknownFieldSet parseFrom(final byte[] data) - throws InvalidProtocolBufferException { + public static UnknownFieldSet parseFrom(final byte[] data) throws InvalidProtocolBufferException { return newBuilder().mergeFrom(data).build(); } /** Parse an {@code UnknownFieldSet} from {@code input} and return it. */ - public static UnknownFieldSet parseFrom(final InputStream input) - throws IOException { + public static UnknownFieldSet parseFrom(final InputStream input) throws IOException { return newBuilder().mergeFrom(input).build(); } @@ -283,12 +263,11 @@ public final class UnknownFieldSet implements MessageLite { /** * Builder for {@link UnknownFieldSet}s. * - *

Note that this class maintains {@link Field.Builder}s for all fields - * in the set. Thus, adding one element to an existing {@link Field} does not - * require making a copy. This is important for efficient parsing of - * unknown repeated fields. However, it implies that {@link Field}s cannot - * be constructed independently, nor can two {@link UnknownFieldSet}s share - * the same {@code Field} object. + *

Note that this class maintains {@link Field.Builder}s for all fields in the set. Thus, + * adding one element to an existing {@link Field} does not require making a copy. This is + * important for efficient parsing of unknown repeated fields. However, it implies that {@link + * Field}s cannot be constructed independently, nor can two {@link UnknownFieldSet}s share the + * same {@code Field} object. * *

Use {@link UnknownFieldSet#newBuilder()} to construct a {@code Builder}. */ @@ -311,8 +290,7 @@ public final class UnknownFieldSet implements MessageLite { } /** - * Get a field builder for the given field number which includes any - * values that already exist. + * Get a field builder for the given field number which includes any values that already exist. */ private Field.Builder getFieldBuilder(final int number) { if (lastField != null) { @@ -338,10 +316,9 @@ public final class UnknownFieldSet implements MessageLite { /** * Build the {@link UnknownFieldSet} and return it. * - *

Once {@code build()} has been called, the {@code Builder} will no - * longer be usable. Calling any method after {@code build()} will result - * in undefined behavior and can cause a {@code NullPointerException} to be - * thrown. + *

Once {@code build()} has been called, the {@code Builder} will no longer be usable. + * Calling any method after {@code build()} will result in undefined behavior and can cause a + * {@code NullPointerException} to be thrown. */ @Override public UnknownFieldSet build() { @@ -365,10 +342,9 @@ public final class UnknownFieldSet implements MessageLite { @Override public Builder clone() { - getFieldBuilder(0); // Force lastField to be built. + getFieldBuilder(0); // Force lastField to be built. Map descendingFields = null; - return UnknownFieldSet.newBuilder().mergeFrom( - new UnknownFieldSet(fields, descendingFields)); + return UnknownFieldSet.newBuilder().mergeFrom(new UnknownFieldSet(fields, descendingFields)); } @Override @@ -388,7 +364,7 @@ public final class UnknownFieldSet implements MessageLite { reinitialize(); return this; } - + /** Clear fields from the set with a given field number. */ public Builder clearField(final int number) { if (number == 0) { @@ -406,9 +382,8 @@ public final class UnknownFieldSet implements MessageLite { } /** - * Merge the fields from {@code other} into this set. If a field number - * exists in both sets, {@code other}'s values for that field will be - * appended to the values in this set. + * Merge the fields from {@code other} into this set. If a field number exists in both sets, + * {@code other}'s values for that field will be appended to the values in this set. */ public Builder mergeFrom(final UnknownFieldSet other) { if (other != getDefaultInstance()) { @@ -420,8 +395,8 @@ public final class UnknownFieldSet implements MessageLite { } /** - * Add a field to the {@code UnknownFieldSet}. If a field with the same - * number already exists, the two are merged. + * Add a field to the {@code UnknownFieldSet}. If a field with the same number already exists, + * the two are merged. */ public Builder mergeField(final int number, final Field field) { if (number == 0) { @@ -439,9 +414,8 @@ public final class UnknownFieldSet implements MessageLite { } /** - * Convenience method for merging a new field containing a single varint - * value. This is used in particular when an unknown enum value is - * encountered. + * Convenience method for merging a new field containing a single varint value. This is used in + * particular when an unknown enum value is encountered. */ public Builder mergeVarintField(final int number, final int value) { if (number == 0) { @@ -451,14 +425,12 @@ public final class UnknownFieldSet implements MessageLite { return this; } - /** * Convenience method for merging a length-delimited field. * *

For use by generated code only. */ - public Builder mergeLengthDelimitedField( - final int number, final ByteString value) { + public Builder mergeLengthDelimitedField(final int number, final ByteString value) { if (number == 0) { throw new IllegalArgumentException("Zero is not a valid field number."); } @@ -475,8 +447,8 @@ public final class UnknownFieldSet implements MessageLite { } /** - * Add a field to the {@code UnknownFieldSet}. If a field with the same - * number already exists, it is removed. + * Add a field to the {@code UnknownFieldSet}. If a field with the same number already exists, + * it is removed. */ public Builder addField(final int number, final Field field) { if (number == 0) { @@ -488,25 +460,22 @@ public final class UnknownFieldSet implements MessageLite { lastFieldNumber = 0; } if (fields.isEmpty()) { - fields = new TreeMap(); + fields = new TreeMap(); } fields.put(number, field); return this; } /** - * Get all present {@code Field}s as an immutable {@code Map}. If more - * fields are added, the changes may or may not be reflected in this map. + * Get all present {@code Field}s as an immutable {@code Map}. If more fields are added, the + * changes may or may not be reflected in this map. */ public Map asMap() { - getFieldBuilder(0); // Force lastField to be built. + getFieldBuilder(0); // Force lastField to be built. return Collections.unmodifiableMap(fields); } - /** - * Parse an entire message from {@code input} and merge its fields into - * this set. - */ + /** Parse an entire message from {@code input} and merge its fields into this set. */ @Override public Builder mergeFrom(final CodedInputStream input) throws IOException { while (true) { @@ -520,11 +489,11 @@ public final class UnknownFieldSet implements MessageLite { /** * Parse a single field from {@code input} and merge it into this set. + * * @param tag The field's tag number, which was already parsed. * @return {@code false} if the tag is an end group tag. */ - public boolean mergeFieldFrom(final int tag, final CodedInputStream input) - throws IOException { + public boolean mergeFieldFrom(final int tag, final CodedInputStream input) throws IOException { final int number = WireFormat.getTagFieldNumber(tag); switch (WireFormat.getTagWireType(tag)) { case WireFormat.WIRETYPE_VARINT: @@ -538,8 +507,7 @@ public final class UnknownFieldSet implements MessageLite { return true; case WireFormat.WIRETYPE_START_GROUP: final Builder subBuilder = newBuilder(); - input.readGroup(number, subBuilder, - ExtensionRegistry.getEmptyRegistry()); + input.readGroup(number, subBuilder, ExtensionRegistry.getEmptyRegistry()); getFieldBuilder(number).addGroup(subBuilder.build()); return true; case WireFormat.WIRETYPE_END_GROUP: @@ -553,9 +521,8 @@ public final class UnknownFieldSet implements MessageLite { } /** - * Parse {@code data} as an {@code UnknownFieldSet} and merge it with the - * set being built. This is just a small wrapper around - * {@link #mergeFrom(CodedInputStream)}. + * Parse {@code data} as an {@code UnknownFieldSet} and merge it with the set being built. This + * is just a small wrapper around {@link #mergeFrom(CodedInputStream)}. */ @Override public Builder mergeFrom(final ByteString data) throws InvalidProtocolBufferException { @@ -568,15 +535,13 @@ public final class UnknownFieldSet implements MessageLite { throw e; } catch (final IOException e) { throw new RuntimeException( - "Reading from a ByteString threw an IOException (should " + - "never happen).", e); + "Reading from a ByteString threw an IOException (should never happen).", e); } } /** - * Parse {@code data} as an {@code UnknownFieldSet} and merge it with the - * set being built. This is just a small wrapper around - * {@link #mergeFrom(CodedInputStream)}. + * Parse {@code data} as an {@code UnknownFieldSet} and merge it with the set being built. This + * is just a small wrapper around {@link #mergeFrom(CodedInputStream)}. */ @Override public Builder mergeFrom(final byte[] data) throws InvalidProtocolBufferException { @@ -589,15 +554,13 @@ public final class UnknownFieldSet implements MessageLite { throw e; } catch (final IOException e) { throw new RuntimeException( - "Reading from a byte array threw an IOException (should " + - "never happen).", e); + "Reading from a byte array threw an IOException (should never happen).", e); } } /** - * Parse an {@code UnknownFieldSet} from {@code input} and merge it with the - * set being built. This is just a small wrapper around - * {@link #mergeFrom(CodedInputStream)}. + * Parse an {@code UnknownFieldSet} from {@code input} and merge it with the set being built. + * This is just a small wrapper around {@link #mergeFrom(CodedInputStream)}. */ @Override public Builder mergeFrom(final InputStream input) throws IOException { @@ -643,8 +606,7 @@ public final class UnknownFieldSet implements MessageLite { @Override public Builder mergeFrom(byte[] data, int off, int len) throws InvalidProtocolBufferException { try { - final CodedInputStream input = - CodedInputStream.newInstance(data, off, len); + final CodedInputStream input = CodedInputStream.newInstance(data, off, len); mergeFrom(input); input.checkLastTagWas(0); return this; @@ -652,8 +614,7 @@ public final class UnknownFieldSet implements MessageLite { throw e; } catch (IOException e) { throw new RuntimeException( - "Reading from a byte array threw an IOException (should " + - "never happen).", e); + "Reading from a byte array threw an IOException (should never happen).", e); } } @@ -698,19 +659,15 @@ public final class UnknownFieldSet implements MessageLite { /** * Represents a single field in an {@code UnknownFieldSet}. * - *

A {@code Field} consists of five lists of values. The lists correspond - * to the five "wire types" used in the protocol buffer binary format. - * The wire type of each field can be determined from the encoded form alone, - * without knowing the field's declared type. So, we are able to parse - * unknown values at least this far and separate them. Normally, only one - * of the five lists will contain any values, since it is impossible to - * define a valid message type that declares two different types for the - * same field number. However, the code is designed to allow for the case - * where the same unknown field number is encountered using multiple different - * wire types. + *

A {@code Field} consists of five lists of values. The lists correspond to the five "wire + * types" used in the protocol buffer binary format. The wire type of each field can be determined + * from the encoded form alone, without knowing the field's declared type. So, we are able to + * parse unknown values at least this far and separate them. Normally, only one of the five lists + * will contain any values, since it is impossible to define a valid message type that declares + * two different types for the same field number. However, the code is designed to allow for the + * case where the same unknown field number is encountered using multiple different wire types. * - *

{@code Field} is an immutable class. To construct one, you must use a - * {@link Builder}. + *

{@code Field} is an immutable class. To construct one, you must use a {@link Builder}. * * @see UnknownFieldSet */ @@ -722,10 +679,7 @@ public final class UnknownFieldSet implements MessageLite { return Builder.create(); } - /** - * Construct a new {@link Builder} and initialize it to a copy of - * {@code copyFrom}. - */ + /** Construct a new {@link Builder} and initialize it to a copy of {@code copyFrom}. */ public static Builder newBuilder(final Field copyFrom) { return newBuilder().mergeFrom(copyFrom); } @@ -734,26 +688,36 @@ public final class UnknownFieldSet implements MessageLite { public static Field getDefaultInstance() { return fieldDefaultInstance; } + private static final Field fieldDefaultInstance = newBuilder().build(); /** Get the list of varint values for this field. */ - public List getVarintList() { return varint; } + public List getVarintList() { + return varint; + } /** Get the list of fixed32 values for this field. */ - public List getFixed32List() { return fixed32; } + public List getFixed32List() { + return fixed32; + } /** Get the list of fixed64 values for this field. */ - public List getFixed64List() { return fixed64; } + public List getFixed64List() { + return fixed64; + } /** Get the list of length-delimited values for this field. */ - public List getLengthDelimitedList() { return lengthDelimited; } + public List getLengthDelimitedList() { + return lengthDelimited; + } /** - * Get the list of embedded group values for this field. These are - * represented using {@link UnknownFieldSet}s rather than {@link Message}s - * since the group's type is presumably unknown. + * Get the list of embedded group values for this field. These are represented using {@link + * UnknownFieldSet}s rather than {@link Message}s since the group's type is presumably unknown. */ - public List getGroupList() { return group; } + public List getGroupList() { + return group; + } @Override public boolean equals(final Object other) { @@ -763,8 +727,7 @@ public final class UnknownFieldSet implements MessageLite { if (!(other instanceof Field)) { return false; } - return Arrays.equals(getIdentityArray(), - ((Field) other).getIdentityArray()); + return Arrays.equals(getIdentityArray(), ((Field) other).getIdentityArray()); } @Override @@ -772,17 +735,9 @@ public final class UnknownFieldSet implements MessageLite { return Arrays.hashCode(getIdentityArray()); } - /** - * Returns the array of objects to be used to uniquely identify this - * {@link Field} instance. - */ + /** Returns the array of objects to be used to uniquely identify this {@link Field} instance. */ private Object[] getIdentityArray() { - return new Object[] { - varint, - fixed32, - fixed64, - lengthDelimited, - group}; + return new Object[] {varint, fixed32, fixed64, lengthDelimited, group}; } /** @@ -802,12 +757,8 @@ public final class UnknownFieldSet implements MessageLite { } } - /** - * Serializes the field, including field number, and writes it to - * {@code output}. - */ - public void writeTo(final int fieldNumber, final CodedOutputStream output) - throws IOException { + /** Serializes the field, including field number, and writes it to {@code output}. */ + public void writeTo(final int fieldNumber, final CodedOutputStream output) throws IOException { for (final long value : varint) { output.writeUInt64(fieldNumber, value); } @@ -825,10 +776,7 @@ public final class UnknownFieldSet implements MessageLite { } } - /** - * Get the number of bytes required to encode this field, including field - * number. - */ + /** Get the number of bytes required to encode this field, including field number. */ public int getSerializedSize(final int fieldNumber) { int result = 0; for (final long value : varint) { @@ -850,12 +798,10 @@ public final class UnknownFieldSet implements MessageLite { } /** - * Serializes the field, including field number, and writes it to - * {@code output}, using {@code MessageSet} wire format. + * Serializes the field, including field number, and writes it to {@code output}, using {@code + * MessageSet} wire format. */ - public void writeAsMessageSetExtensionTo( - final int fieldNumber, - final CodedOutputStream output) + public void writeAsMessageSetExtensionTo(final int fieldNumber, final CodedOutputStream output) throws IOException { for (final ByteString value : lengthDelimited) { output.writeRawMessageSetExtension(fieldNumber, value); @@ -870,8 +816,7 @@ public final class UnknownFieldSet implements MessageLite { public int getSerializedSizeAsMessageSetExtension(final int fieldNumber) { int result = 0; for (final ByteString value : lengthDelimited) { - result += CodedOutputStream.computeRawMessageSetExtensionSize( - fieldNumber, value); + result += CodedOutputStream.computeRawMessageSetExtensionSize(fieldNumber, value); } return result; } @@ -900,10 +845,9 @@ public final class UnknownFieldSet implements MessageLite { private Field result; /** - * Build the field. After {@code build()} has been called, the - * {@code Builder} is no longer usable. Calling any other method will - * result in undefined behavior and can cause a - * {@code NullPointerException} to be thrown. + * Build the field. After {@code build()} has been called, the {@code Builder} is no longer + * usable. Calling any other method will result in undefined behavior and can cause a {@code + * NullPointerException} to be thrown. */ public Field build() { if (result.varint == null) { @@ -924,8 +868,7 @@ public final class UnknownFieldSet implements MessageLite { if (result.lengthDelimited == null) { result.lengthDelimited = Collections.emptyList(); } else { - result.lengthDelimited = - Collections.unmodifiableList(result.lengthDelimited); + result.lengthDelimited = Collections.unmodifiableList(result.lengthDelimited); } if (result.group == null) { result.group = Collections.emptyList(); @@ -945,9 +888,8 @@ public final class UnknownFieldSet implements MessageLite { } /** - * Merge the values in {@code other} into this field. For each list - * of values, {@code other}'s values are append to the ones in this - * field. + * Merge the values in {@code other} into this field. For each list of values, {@code other}'s + * values are append to the ones in this field. */ public Builder mergeFrom(final Field other) { if (!other.varint.isEmpty()) { @@ -1030,9 +972,7 @@ public final class UnknownFieldSet implements MessageLite { } } - /** - * Parser to implement MessageLite interface. - */ + /** Parser to implement MessageLite interface. */ public static final class Parser extends AbstractParser { @Override public UnknownFieldSet parsePartialFrom( @@ -1044,14 +984,14 @@ public final class UnknownFieldSet implements MessageLite { } catch (InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (IOException e) { - throw new InvalidProtocolBufferException(e) - .setUnfinishedMessage(builder.buildPartial()); + throw new InvalidProtocolBufferException(e).setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } } private static final Parser PARSER = new Parser(); + @Override public final Parser getParserForType() { return PARSER; diff --git a/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java b/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java index f0b919adae..7c5ec6e98c 100644 --- a/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java +++ b/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java @@ -34,24 +34,23 @@ import java.io.IOException; import java.util.Arrays; /** - * {@code UnknownFieldSetLite} is used to keep track of fields which were seen - * when parsing a protocol message but whose field numbers or types are - * unrecognized. This most frequently occurs when new fields are added to a - * message type and then messages containing those fields are read by old - * software that was compiled before the new types were added. + * {@code UnknownFieldSetLite} is used to keep track of fields which were seen when parsing a + * protocol message but whose field numbers or types are unrecognized. This most frequently occurs + * when new fields are added to a message type and then messages containing those fields are read by + * old software that was compiled before the new types were added. * *

For use by generated code only. * * @author dweis@google.com (Daniel Weis) */ public final class UnknownFieldSetLite { - + // Arbitrarily chosen. // TODO(dweis): Tune this number? private static final int MIN_CAPACITY = 8; private static final UnknownFieldSetLite DEFAULT_INSTANCE = - new UnknownFieldSetLite(0, new int[0], new Object[0], false /* isMutable */); + new UnknownFieldSetLite(0, new int[0], new Object[0], /* isMutable= */ false); /** * Get an empty {@code UnknownFieldSetLite}. @@ -61,17 +60,15 @@ public final class UnknownFieldSetLite { public static UnknownFieldSetLite getDefaultInstance() { return DEFAULT_INSTANCE; } - - /** - * Returns a new mutable instance. - */ + + /** Returns a new mutable instance. */ static UnknownFieldSetLite newInstance() { return new UnknownFieldSetLite(); } /** - * Returns a mutable {@code UnknownFieldSetLite} that is the composite of {@code first} and - * {@code second}. + * Returns a mutable {@code UnknownFieldSetLite} that is the composite of {@code first} and {@code + * second}. */ static UnknownFieldSetLite mutableCopyOf(UnknownFieldSetLite first, UnknownFieldSetLite second) { int count = first.count + second.count; @@ -79,66 +76,50 @@ public final class UnknownFieldSetLite { System.arraycopy(second.tags, 0, tags, first.count, second.count); Object[] objects = Arrays.copyOf(first.objects, count); System.arraycopy(second.objects, 0, objects, first.count, second.count); - return new UnknownFieldSetLite(count, tags, objects, true /* isMutable */); + return new UnknownFieldSetLite(count, tags, objects, /* isMutable= */ true); } - /** - * The number of elements in the set. - */ + /** The number of elements in the set. */ private int count; - - /** - * The tag numbers for the elements in the set. - */ + + /** The tag numbers for the elements in the set. */ private int[] tags; - - /** - * The boxed values of the elements in the set. - */ + + /** The boxed values of the elements in the set. */ private Object[] objects; - - /** - * The lazily computed serialized size of the set. - */ + + /** The lazily computed serialized size of the set. */ private int memoizedSerializedSize = -1; - - /** - * Indicates that this object is mutable. - */ + + /** Indicates that this object is mutable. */ private boolean isMutable; - /** - * Constructs a mutable {@code UnknownFieldSetLite}. - */ + /** Constructs a mutable {@code UnknownFieldSetLite}. */ private UnknownFieldSetLite() { - this(0, new int[MIN_CAPACITY], new Object[MIN_CAPACITY], true /* isMutable */); + this(0, new int[MIN_CAPACITY], new Object[MIN_CAPACITY], /* isMutable= */ true); } - - /** - * Constructs the {@code UnknownFieldSetLite}. - */ + + /** Constructs the {@code UnknownFieldSetLite}. */ private UnknownFieldSetLite(int count, int[] tags, Object[] objects, boolean isMutable) { this.count = count; this.tags = tags; this.objects = objects; this.isMutable = isMutable; } - + /** * Marks this object as immutable. - * + * *

Future calls to methods that attempt to modify this object will throw. */ public void makeImmutable() { this.isMutable = false; } - - /** - * Throws an {@link UnsupportedOperationException} if immutable. - */ + + /** Throws an {@link UnsupportedOperationException} if immutable. */ void checkMutable() { if (!isMutable) { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException(); } } @@ -197,17 +178,17 @@ public final class UnknownFieldSetLite { if (size != -1) { return size; } - + size = 0; for (int i = 0; i < count; i++) { int tag = tags[i]; int fieldNumber = WireFormat.getTagFieldNumber(tag); - size += CodedOutputStream.computeRawMessageSetExtensionSize( - fieldNumber, (ByteString) objects[i]); + size += + CodedOutputStream.computeRawMessageSetExtensionSize(fieldNumber, (ByteString) objects[i]); } - + memoizedSerializedSize = size; - + return size; } @@ -221,7 +202,7 @@ public final class UnknownFieldSetLite { if (size != -1) { return size; } - + size = 0; for (int i = 0; i < count; i++) { int tag = tags[i]; @@ -240,19 +221,20 @@ public final class UnknownFieldSetLite { size += CodedOutputStream.computeBytesSize(fieldNumber, (ByteString) objects[i]); break; case WireFormat.WIRETYPE_START_GROUP: - size += CodedOutputStream.computeTagSize(fieldNumber) * 2 - + ((UnknownFieldSetLite) objects[i]).getSerializedSize(); + size += + CodedOutputStream.computeTagSize(fieldNumber) * 2 + + ((UnknownFieldSetLite) objects[i]).getSerializedSize(); break; default: throw new IllegalStateException(InvalidProtocolBufferException.invalidWireType()); } } - + memoizedSerializedSize = size; - + return size; } - + private static boolean equals(int[] tags1, int[] tags2, int count) { for (int i = 0; i < count; ++i) { if (tags1[i] != tags2[i]) { @@ -284,8 +266,8 @@ public final class UnknownFieldSetLite { if (!(obj instanceof UnknownFieldSetLite)) { return false; } - - UnknownFieldSetLite other = (UnknownFieldSetLite) obj; + + UnknownFieldSetLite other = (UnknownFieldSetLite) obj; if (count != other.count || !equals(tags, other.tags, count) || !equals(objects, other.objects, count)) { @@ -341,25 +323,23 @@ public final class UnknownFieldSetLite { void storeField(int tag, Object value) { checkMutable(); ensureCapacity(); - + tags[count] = tag; objects[count] = value; count++; } - - /** - * Ensures that our arrays are long enough to store more metadata. - */ + + /** Ensures that our arrays are long enough to store more metadata. */ private void ensureCapacity() { - if (count == tags.length) { + if (count == tags.length) { int increment = count < (MIN_CAPACITY / 2) ? MIN_CAPACITY : count >> 1; int newLength = count + increment; - + tags = Arrays.copyOf(tags, newLength); objects = Arrays.copyOf(objects, newLength); } } - + /** * Parse a single field from {@code input} and merge it into this set. * @@ -387,8 +367,7 @@ public final class UnknownFieldSetLite { case WireFormat.WIRETYPE_START_GROUP: final UnknownFieldSetLite subFieldSet = new UnknownFieldSetLite(); subFieldSet.mergeFrom(input); - input.checkLastTagWas( - WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP)); + input.checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP)); storeField(tag, subFieldSet); return true; case WireFormat.WIRETYPE_END_GROUP: @@ -399,9 +378,8 @@ public final class UnknownFieldSetLite { } /** - * Convenience method for merging a new field containing a single varint - * value. This is used in particular when an unknown enum value is - * encountered. + * Convenience method for merging a new field containing a single varint value. This is used in + * particular when an unknown enum value is encountered. * *

For use by generated code only. */ @@ -412,7 +390,7 @@ public final class UnknownFieldSetLite { } storeField(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_VARINT), (long) value); - + return this; } @@ -421,21 +399,18 @@ public final class UnknownFieldSetLite { * *

For use by generated code only. */ - UnknownFieldSetLite mergeLengthDelimitedField(final int fieldNumber, final ByteString value) { + UnknownFieldSetLite mergeLengthDelimitedField(final int fieldNumber, final ByteString value) { checkMutable(); if (fieldNumber == 0) { throw new IllegalArgumentException("Zero is not a valid field number."); } storeField(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED), value); - + return this; } - - /** - * Parse an entire message from {@code input} and merge its fields into - * this set. - */ + + /** Parse an entire message from {@code input} and merge its fields into this set. */ private UnknownFieldSetLite mergeFrom(final CodedInputStream input) throws IOException { // Ensures initialization in mergeFieldFrom. while (true) { diff --git a/java/core/src/main/java/com/google/protobuf/UnmodifiableLazyStringList.java b/java/core/src/main/java/com/google/protobuf/UnmodifiableLazyStringList.java index 30e8791178..415b2cde0d 100644 --- a/java/core/src/main/java/com/google/protobuf/UnmodifiableLazyStringList.java +++ b/java/core/src/main/java/com/google/protobuf/UnmodifiableLazyStringList.java @@ -39,8 +39,8 @@ import java.util.ListIterator; import java.util.RandomAccess; /** - * An implementation of {@link LazyStringList} that wraps another - * {@link LazyStringList} such that it cannot be modified via the wrapper. + * An implementation of {@link LazyStringList} that wraps another {@link LazyStringList} such that + * it cannot be modified via the wrapper. * * @author jonp@google.com (Jon Perlow) */ @@ -57,7 +57,7 @@ public class UnmodifiableLazyStringList extends AbstractList public String get(int index) { return list.get(index); } - + @Override public Object getRaw(int index) { return list.getRaw(index); @@ -97,7 +97,7 @@ public class UnmodifiableLazyStringList extends AbstractList public void add(byte[] element) { throw new UnsupportedOperationException(); } - + @Override public void set(int index, byte[] element) { throw new UnsupportedOperationException(); 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 878c775816..bcaf1d2f33 100644 --- a/java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java +++ b/java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java @@ -39,23 +39,24 @@ import java.nio.ByteBuffer; * potentially expose the backing buffer of a {@link ByteString} to the application. * *

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

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

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

    - *
  • serialization may throw - *
  • serialization may succeed but the wrong bytes may be written out - *
  • messages are no longer threadsafe - *
  • hashCode may be incorrect - *
      - *
    • can result in a permanent memory leak when used as a key in a long-lived HashMap - *
    • the semantics of many programs may be violated if this is the case - *
    + *
  • serialization may throw + *
  • serialization may succeed but the wrong bytes may be written out + *
  • messages are no longer threadsafe + *
  • hashCode may be incorrect + *
      + *
    • can result in a permanent memory leak when used as a key in a long-lived HashMap + *
    • the semantics of many programs may be violated if this is the case + *
    *
+ * * Each of these issues will occur in parts of the code base that are entirely distinct from the * parts of the code base modifying the buffer. In fact, both parts of the code base may be correct * - it is the bridging with the unsafe operations that was in error! @@ -99,19 +100,19 @@ public final class UnsafeByteOperations { /** * Writes the given {@link ByteString} to the provided {@link ByteOutput}. Calling this method may - * result in multiple operations on the target {@link ByteOutput} - * (i.e. for roped {@link ByteString}s). + * result in multiple operations on the target {@link ByteOutput} (i.e. for roped {@link + * ByteString}s). * *

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

NOTE: The {@link ByteOutput} MUST NOT modify the provided buffers. Doing - * so may result in corrupted data, which would be difficult to debug. + *

NOTE: The {@link ByteOutput} MUST NOT modify the provided buffers. Doing so + * may result in corrupted data, which would be difficult to debug. * * @param bytes the {@link ByteString} to be written - * @param output the output to receive the bytes - * @throws IOException if an I/O error occurs + * @param output the output to receive the bytes + * @throws IOException if an I/O error occurs */ public static void unsafeWriteTo(ByteString bytes, ByteOutput output) throws IOException { bytes.writeTo(output); diff --git a/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java b/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java index f822ce51f8..50bc911d91 100644 --- a/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java +++ b/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java @@ -226,7 +226,7 @@ final class UnsafeUtil { } static void copyMemory(byte[] src, long srcIndex, byte[] target, long targetIndex, long length) { - System.arraycopy(src, (int) srcIndex, target, (int) targetIndex, (int) length); + System.arraycopy(src, (int) srcIndex, target, (int) targetIndex, (int) length); } static byte getByte(long address) { @@ -253,9 +253,7 @@ final class UnsafeUtil { MEMORY_ACCESSOR.putLong(address, value); } - /** - * Gets the offset of the {@code address} field of the given direct {@link ByteBuffer}. - */ + /** Gets the offset of the {@code address} field of the given direct {@link ByteBuffer}. */ static long addressOffset(ByteBuffer buffer) { return MEMORY_ACCESSOR.getLong(buffer, BUFFER_ADDRESS_OFFSET); } @@ -472,9 +470,9 @@ final class UnsafeUtil { public abstract void putLong(long address, long value); public abstract Object getStaticObject(Field field); - + public abstract void copyMemory(long srcOffset, byte[] target, long targetIndex, long length); - + public abstract void copyMemory(byte[] src, long srcIndex, long targetOffset, long length); } @@ -553,12 +551,12 @@ final class UnsafeUtil { public void putDouble(Object target, long offset, double value) { unsafe.putDouble(target, offset, value); } - - @Override + + @Override public void copyMemory(long srcOffset, byte[] target, long targetIndex, long length) { unsafe.copyMemory(null, srcOffset, target, BYTE_ARRAY_BASE_OFFSET + targetIndex, length); } - + @Override public void copyMemory(byte[] src, long srcIndex, long targetOffset, long length) { unsafe.copyMemory(src, BYTE_ARRAY_BASE_OFFSET + srcIndex, null, targetOffset, length); diff --git a/java/core/src/main/java/com/google/protobuf/Utf8.java b/java/core/src/main/java/com/google/protobuf/Utf8.java index b4a81ca3a2..4512bf9b56 100644 --- a/java/core/src/main/java/com/google/protobuf/Utf8.java +++ b/java/core/src/main/java/com/google/protobuf/Utf8.java @@ -44,36 +44,31 @@ import static java.lang.Character.toCodePoint; import java.nio.ByteBuffer; /** - * A set of low-level, high-performance static utility methods related - * to the UTF-8 character encoding. This class has no dependencies - * outside of the core JDK libraries. + * A set of low-level, high-performance static utility methods related to the UTF-8 character + * encoding. This class has no dependencies outside of the core JDK libraries. * - *

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

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

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

 {@code
+ * 

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

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

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

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

This class supports decoding of partial byte sequences, so that the - * bytes in a complete UTF-8 byte sequences can be stored in multiple - * segments. Methods typically return {@link #MALFORMED} if the partial - * byte sequence is definitely not well-formed, {@link #COMPLETE} if it is - * well-formed in the absence of additional input, or if the byte sequence - * apparently terminated in the middle of a character, an opaque integer - * "state" value containing enough information to decode the character when - * passed to a subsequent invocation of a partial decoding method. + *

This class supports decoding of partial byte sequences, so that the bytes in a complete UTF-8 + * byte sequences can be stored in multiple segments. Methods typically return {@link #MALFORMED} if + * the partial byte sequence is definitely not well-formed, {@link #COMPLETE} if it is well-formed + * in the absence of additional input, or if the byte sequence apparently terminated in the middle + * of a character, an opaque integer "state" value containing enough information to decode the + * character when passed to a subsequent invocation of a partial decoding method. * * @author martinrb@google.com (Martin Buchholz) */ @@ -98,31 +93,28 @@ final class Utf8 { /** * Maximum number of bytes per Java UTF-16 char in UTF-8. + * * @see java.nio.charset.CharsetEncoder#maxBytesPerChar() */ static final int MAX_BYTES_PER_CHAR = 3; /** - * State value indicating that the byte sequence is well-formed and - * complete (no further bytes are needed to complete a character). + * State value indicating that the byte sequence is well-formed and complete (no further bytes are + * needed to complete a character). */ public static final int COMPLETE = 0; - /** - * State value indicating that the byte sequence is definitely not - * well-formed. - */ + /** State value indicating that the byte sequence is definitely not well-formed. */ public static final int MALFORMED = -1; /** * Used by {@code Unsafe} UTF-8 string validation logic to determine the minimum string length * above which to employ an optimized algorithm for counting ASCII characters. The reason for this * threshold is that for small strings, the optimization may not be beneficial or may even - * negatively impact performance since it requires additional logic to avoid unaligned reads - * (when calling {@code Unsafe.getLong}). This threshold guarantees that even if the initial - * offset is unaligned, we're guaranteed to make at least one call to {@code Unsafe.getLong()} - * which provides a performance improvement that entirely subsumes the cost of the additional - * logic. + * negatively impact performance since it requires additional logic to avoid unaligned reads (when + * calling {@code Unsafe.getLong}). This threshold guarantees that even if the initial offset is + * unaligned, we're guaranteed to make at least one call to {@code Unsafe.getLong()} which + * provides a performance improvement that entirely subsumes the cost of the additional logic. */ private static final int UNSAFE_COUNT_ASCII_THRESHOLD = 16; @@ -146,76 +138,69 @@ final class Utf8 { // are valid trailing bytes. /** - * Returns {@code true} if the given byte array is a well-formed - * UTF-8 byte sequence. + * Returns {@code true} if the given byte array is a well-formed UTF-8 byte sequence. * - *

This is a convenience method, equivalent to a call to {@code - * isValidUtf8(bytes, 0, bytes.length)}. + *

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

This is a convenience method, equivalent to {@code - * partialIsValidUtf8(bytes, index, limit) == Utf8.COMPLETE}. + *

This is a convenience method, equivalent to {@code partialIsValidUtf8(bytes, index, limit) + * == Utf8.COMPLETE}. */ public static boolean isValidUtf8(byte[] bytes, int index, int limit) { return processor.isValidUtf8(bytes, index, limit); } /** - * Tells whether the given byte array slice is a well-formed, - * malformed, or incomplete UTF-8 byte sequence. The range of bytes - * to be checked extends from index {@code index}, inclusive, to + * Tells whether the given byte array slice is a well-formed, malformed, or incomplete UTF-8 byte + * sequence. The range of bytes to be checked extends from index {@code index}, inclusive, to * {@code limit}, exclusive. * - * @param state either {@link Utf8#COMPLETE} (if this is the initial decoding - * operation) or the value returned from a call to a partial decoding method - * for the previous bytes - * - * @return {@link #MALFORMED} if the partial byte sequence is - * definitely not well-formed, {@link #COMPLETE} if it is well-formed - * (no additional input needed), or if the byte sequence is - * "incomplete", i.e. apparently terminated in the middle of a character, - * an opaque integer "state" value containing enough information to - * decode the character when passed to a subsequent invocation of a - * partial decoding method. + * @param state either {@link Utf8#COMPLETE} (if this is the initial decoding operation) or the + * value returned from a call to a partial decoding method for the previous bytes + * @return {@link #MALFORMED} if the partial byte sequence is definitely not well-formed, {@link + * #COMPLETE} if it is well-formed (no additional input needed), or if the byte sequence is + * "incomplete", i.e. apparently terminated in the middle of a character, an opaque integer + * "state" value containing enough information to decode the character when passed to a + * subsequent invocation of a partial decoding method. */ public static int partialIsValidUtf8(int state, byte[] bytes, int index, int limit) { return processor.partialIsValidUtf8(state, bytes, index, limit); } private static int incompleteStateFor(int byte1) { - return (byte1 > (byte) 0xF4) ? - MALFORMED : byte1; + return (byte1 > (byte) 0xF4) ? MALFORMED : byte1; } private static int incompleteStateFor(int byte1, int byte2) { - return (byte1 > (byte) 0xF4 || - byte2 > (byte) 0xBF) ? - MALFORMED : byte1 ^ (byte2 << 8); + return (byte1 > (byte) 0xF4 || byte2 > (byte) 0xBF) ? MALFORMED : byte1 ^ (byte2 << 8); } private static int incompleteStateFor(int byte1, int byte2, int byte3) { - return (byte1 > (byte) 0xF4 || - byte2 > (byte) 0xBF || - byte3 > (byte) 0xBF) ? - MALFORMED : byte1 ^ (byte2 << 8) ^ (byte3 << 16); + return (byte1 > (byte) 0xF4 || byte2 > (byte) 0xBF || byte3 > (byte) 0xBF) + ? MALFORMED + : byte1 ^ (byte2 << 8) ^ (byte3 << 16); } private static int incompleteStateFor(byte[] bytes, int index, int limit) { int byte1 = bytes[index - 1]; switch (limit - index) { - case 0: return incompleteStateFor(byte1); - case 1: return incompleteStateFor(byte1, bytes[index]); - case 2: return incompleteStateFor(byte1, bytes[index], bytes[index + 1]); - default: throw new AssertionError(); + case 0: + return incompleteStateFor(byte1); + case 1: + return incompleteStateFor(byte1, bytes[index]); + case 2: + return incompleteStateFor(byte1, bytes[index], bytes[index + 1]); + default: + throw new AssertionError(); } } @@ -236,7 +221,7 @@ final class Utf8 { // These UTF-8 handling methods are copied from Guava's Utf8 class with a modification to throw // a protocol buffer local exception. This exception is then caught in CodedOutputStream so it can // fallback to more lenient behavior. - + static class UnpairedSurrogateException extends IllegalArgumentException { UnpairedSurrogateException(int index, int length) { super("Unpaired surrogate at index " + index + " of " + length); @@ -244,9 +229,9 @@ final class Utf8 { } /** - * Returns the number of bytes in the UTF-8-encoded form of {@code sequence}. For a string, - * this method is equivalent to {@code string.getBytes(UTF_8).length}, but is more efficient in - * both time and space. + * Returns the number of bytes in the UTF-8-encoded form of {@code sequence}. For a string, this + * method is equivalent to {@code string.getBytes(UTF_8).length}, but is more efficient in both + * time and space. * * @throws IllegalArgumentException if {@code sequence} contains ill-formed UTF-16 (unpaired * surrogates) @@ -266,7 +251,7 @@ final class Utf8 { for (; i < utf16Length; i++) { char c = sequence.charAt(i); if (c < 0x800) { - utf8Length += ((0x7f - c) >>> 31); // branch free! + utf8Length += ((0x7f - c) >>> 31); // branch free! } else { utf8Length += encodedLengthGeneral(sequence, i); break; @@ -275,8 +260,8 @@ final class Utf8 { if (utf8Length < utf16Length) { // Necessary and sufficient condition for overflow because of maximum 3x expansion - throw new IllegalArgumentException("UTF-8 length does not fit in int: " - + (utf8Length + (1L << 32))); + throw new IllegalArgumentException( + "UTF-8 length does not fit in int: " + (utf8Length + (1L << 32))); } return utf8Length; } @@ -370,15 +355,15 @@ final class Utf8 { } /** - * Counts (approximately) the number of consecutive ASCII characters in the given buffer. - * The byte order of the {@link ByteBuffer} does not matter, so performance can be improved if - * native byte order is used (i.e. no byte-swapping in {@link ByteBuffer#getLong(int)}). + * Counts (approximately) the number of consecutive ASCII characters in the given buffer. The byte + * order of the {@link ByteBuffer} does not matter, so performance can be improved if native byte + * order is used (i.e. no byte-swapping in {@link ByteBuffer#getLong(int)}). * * @param buffer the buffer to be scanned for ASCII chars * @param index the starting index of the scan * @param limit the limit within buffer for the scan - * @return the number of ASCII characters found. The stopping position will be at or - * before the first non-ASCII byte. + * @return the number of ASCII characters found. The stopping position will be at or before the + * first non-ASCII byte. */ private static int estimateConsecutiveAscii(ByteBuffer buffer, int index, int limit) { int i = index; @@ -390,52 +375,43 @@ final class Utf8 { return i - index; } - /** - * A processor of UTF-8 strings, providing methods for checking validity and encoding. - */ + /** A processor of UTF-8 strings, providing methods for checking validity and encoding. */ // TODO(nathanmittler): Add support for Memory/MemoryBlock on Android. abstract static class Processor { /** - * Returns {@code true} if the given byte array slice is a - * well-formed UTF-8 byte sequence. The range of bytes to be - * checked extends from index {@code index}, inclusive, to {@code - * limit}, exclusive. + * Returns {@code true} if the given byte array slice is a well-formed UTF-8 byte sequence. The + * range of bytes to be checked extends from index {@code index}, inclusive, to {@code limit}, + * exclusive. * - *

This is a convenience method, equivalent to {@code - * partialIsValidUtf8(bytes, index, limit) == Utf8.COMPLETE}. + *

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

This is a convenience method, equivalent to {@code - * partialIsValidUtf8(bytes, index, limit) == Utf8.COMPLETE}. + *

This is a convenience method, equivalent to {@code partialIsValidUtf8(bytes, index, limit) + * == Utf8.COMPLETE}. */ final boolean isValidUtf8(ByteBuffer buffer, int index, int limit) { return partialIsValidUtf8(COMPLETE, buffer, index, limit) == COMPLETE; @@ -452,22 +428,20 @@ final class Utf8 { if (buffer.hasArray()) { final int offset = buffer.arrayOffset(); return partialIsValidUtf8(state, buffer.array(), offset + index, offset + limit); - } else if (buffer.isDirect()){ + } else if (buffer.isDirect()) { return partialIsValidUtf8Direct(state, buffer, index, limit); } return partialIsValidUtf8Default(state, buffer, index, limit); } - /** - * Performs validation for direct {@link ByteBuffer} instances. - */ + /** Performs validation for direct {@link ByteBuffer} instances. */ abstract int partialIsValidUtf8Direct( final int state, final ByteBuffer buffer, int index, final int limit); /** * Performs validation for {@link ByteBuffer} instances using the {@link ByteBuffer} API rather - * than potentially faster approaches. This first completes validation for the current - * character (provided by {@code state}) and then finishes validation for the sequence. + * than potentially faster approaches. This first completes validation for the current character + * (provided by {@code state}) and then finishes validation for the sequence. */ final int partialIsValidUtf8Default( final int state, final ByteBuffer buffer, int index, final int limit) { @@ -566,7 +540,7 @@ final class Utf8 { private static int partialIsValidUtf8(final ByteBuffer buffer, int index, final int limit) { index += estimateConsecutiveAscii(buffer, index, limit); - for (;;) { + for (; ; ) { // Optimize for interior runs of ASCII bytes. // TODO(nathanmittler): Consider checking 8 bytes at a time after some threshold? // Maybe after seeing a few in a row that are ASCII, go back to fast mode? @@ -658,15 +632,13 @@ final class Utf8 { return decodeUtf8Default(buffer, index, size); } - /** - * Decodes direct {@link ByteBuffer} instances into {@link String}. - */ + /** Decodes direct {@link ByteBuffer} instances into {@link String}. */ abstract String decodeUtf8Direct(ByteBuffer buffer, int index, int size) throws InvalidProtocolBufferException; /** - * Decodes {@link ByteBuffer} instances using the {@link ByteBuffer} API rather than - * potentially faster approaches. + * Decodes {@link ByteBuffer} instances using the {@link ByteBuffer} API rather than potentially + * faster approaches. */ final String decodeUtf8Default(ByteBuffer buffer, int index, int size) throws InvalidProtocolBufferException { @@ -747,21 +719,22 @@ final class Utf8 { /** * Encodes an input character sequence ({@code in}) to UTF-8 in the target array ({@code out}). * For a string, this method is similar to + * *

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

To ensure sufficient space in the output buffer, either call {@link #encodedLength} to - * compute the exact amount needed, or leave room for - * {@code Utf8.MAX_BYTES_PER_CHAR * sequence.length()}, which is the largest possible number - * of bytes that any input can be encoded to. + * compute the exact amount needed, or leave room for {@code Utf8.MAX_BYTES_PER_CHAR * + * sequence.length()}, which is the largest possible number of bytes that any input can be + * encoded to. * * @param in the input character sequence to be encoded * @param out the target array @@ -778,26 +751,24 @@ final class Utf8 { /** * Encodes an input character sequence ({@code in}) to UTF-8 in the target buffer ({@code out}). * Upon returning from this method, the {@code out} position will point to the position after - * the last encoded byte. This method requires paired surrogates, and therefore does not - * support chunking. + * the last encoded byte. This method requires paired surrogates, and therefore does not support + * chunking. * *

To ensure sufficient space in the output buffer, either call {@link #encodedLength} to - * compute the exact amount needed, or leave room for - * {@code Utf8.MAX_BYTES_PER_CHAR * in.length()}, which is the largest possible number - * of bytes that any input can be encoded to. + * compute the exact amount needed, or leave room for {@code Utf8.MAX_BYTES_PER_CHAR * + * in.length()}, which is the largest possible number of bytes that any input can be encoded to. * * @param in the source character sequence to be encoded * @param out the target buffer * @throws UnpairedSurrogateException if {@code in} contains ill-formed UTF-16 (unpaired * surrogates) - * @throws ArrayIndexOutOfBoundsException if {@code in} encoded in UTF-8 is longer than - * {@code out.remaining()} + * @throws ArrayIndexOutOfBoundsException if {@code in} encoded in UTF-8 is longer than {@code + * out.remaining()} */ final void encodeUtf8(CharSequence in, ByteBuffer out) { if (out.hasArray()) { final int offset = out.arrayOffset(); - int endIndex = - Utf8.encode(in, out.array(), offset + out.position(), out.remaining()); + int endIndex = Utf8.encode(in, out.array(), offset + out.position(), out.remaining()); out.position(endIndex - offset); } else if (out.isDirect()) { encodeUtf8Direct(in, out); @@ -806,9 +777,7 @@ final class Utf8 { } } - /** - * Encodes the input character sequence to a direct {@link ByteBuffer} instance. - */ + /** Encodes the input character sequence to a direct {@link ByteBuffer} instance. */ abstract void encodeUtf8Direct(CharSequence in, ByteBuffer out); /** @@ -887,9 +856,7 @@ final class Utf8 { } } - /** - * {@link Processor} implementation that does not use any {@code sun.misc.Unsafe} methods. - */ + /** {@link Processor} implementation that does not use any {@code sun.misc.Unsafe} methods. */ static final class SafeProcessor extends Processor { @Override int partialIsValidUtf8(int state, byte[] bytes, int index, int limit) { @@ -901,7 +868,7 @@ final class Utf8 { // // We expect such "straddler characters" to be rare. - if (index >= limit) { // No bytes? No progress. + if (index >= limit) { // No bytes? No progress. return state; } int byte1 = (byte) state; @@ -1098,8 +1065,7 @@ final class Utf8 { // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, // four UTF-8 bytes final char low; - if (i + 1 == in.length() - || !Character.isSurrogatePair(c, (low = in.charAt(++i)))) { + if (i + 1 == in.length() || !Character.isSurrogatePair(c, (low = in.charAt(++i)))) { throw new UnpairedSurrogateException((i - 1), utf16Length); } int codePoint = Character.toCodePoint(c, low); @@ -1111,8 +1077,7 @@ final class Utf8 { // If we are surrogates and we're not a surrogate pair, always throw an // UnpairedSurrogateException instead of an ArrayOutOfBoundsException. if ((Character.MIN_SURROGATE <= c && c <= Character.MAX_SURROGATE) - && (i + 1 == in.length() - || !Character.isSurrogatePair(c, in.charAt(i + 1)))) { + && (i + 1 == in.length() || !Character.isSurrogatePair(c, in.charAt(i + 1)))) { throw new UnpairedSurrogateException(i, utf16Length); } throw new ArrayIndexOutOfBoundsException("Failed writing " + c + " at index " + j); @@ -1138,7 +1103,7 @@ final class Utf8 { } private static int partialIsValidUtf8NonAscii(byte[] bytes, int index, int limit) { - for (;;) { + for (; ; ) { int byte1, byte2; // Optimize for interior runs of ASCII bytes. @@ -1158,8 +1123,7 @@ final class Utf8 { // Simultaneously checks for illegal trailing-byte in // leading position and overlong 2-byte form. - if (byte1 < (byte) 0xC2 - || bytes[index++] > (byte) 0xBF) { + if (byte1 < (byte) 0xC2 || bytes[index++] > (byte) 0xBF) { return MALFORMED; } } else if (byte1 < (byte) 0xF0) { @@ -1180,7 +1144,7 @@ final class Utf8 { } else { // four-byte form - if (index >= limit - 2) { // incomplete sequence + if (index >= limit - 2) { // incomplete sequence return incompleteStateFor(bytes, index, limit); } if ((byte2 = bytes[index++]) > (byte) 0xBF @@ -1200,13 +1164,9 @@ final class Utf8 { } } - /** - * {@link Processor} that uses {@code sun.misc.Unsafe} where possible to improve performance. - */ + /** {@link Processor} that uses {@code sun.misc.Unsafe} where possible to improve performance. */ static final class UnsafeProcessor extends Processor { - /** - * Indicates whether or not all required unsafe operations are supported on this platform. - */ + /** Indicates whether or not all required unsafe operations are supported on this platform. */ static boolean isAvailable() { return hasUnsafeArrayOperations() && hasUnsafeByteBufferOperations(); } @@ -1228,7 +1188,7 @@ final class Utf8 { // // We expect such "straddler characters" to be rare. - if (offset >= offsetLimit) { // No bytes? No progress. + if (offset >= offsetLimit) { // No bytes? No progress. return state; } int byte1 = (byte) state; @@ -1685,8 +1645,8 @@ final class Utf8 { * @param bytes the array containing the character sequence * @param offset the offset position of the index (same as index + arrayBaseOffset) * @param maxChars the maximum number of characters to count - * @return the number of ASCII characters found. The stopping position will be at or - * before the first non-ASCII byte. + * @return the number of ASCII characters found. The stopping position will be at or before the + * first non-ASCII byte. */ private static int unsafeEstimateConsecutiveAscii( byte[] bytes, long offset, final int maxChars) { @@ -1728,24 +1688,24 @@ final class Utf8 { // To speed things up further, we're reading longs instead of bytes so we use a mask to // determine if any byte in the current long is non-ASCII. remaining -= unaligned; - for (; remaining >= 8 && (UnsafeUtil.getLong(address) & ASCII_MASK_LONG) == 0; + for (; + remaining >= 8 && (UnsafeUtil.getLong(address) & ASCII_MASK_LONG) == 0; address += 8, remaining -= 8) {} return maxChars - remaining; } private static int partialIsValidUtf8(final byte[] bytes, long offset, int remaining) { - // Skip past ASCII characters as quickly as possible. + // Skip past ASCII characters as quickly as possible. final int skipped = unsafeEstimateConsecutiveAscii(bytes, offset, remaining); remaining -= skipped; offset += skipped; - for (;;) { + for (; ; ) { // Optimize for interior runs of ASCII bytes. // TODO(nathanmittler): Consider checking 8 bytes at a time after some threshold? // Maybe after seeing a few in a row that are ASCII, go back to fast mode? int byte1 = 0; - for (; remaining > 0 && (byte1 = UnsafeUtil.getByte(bytes, offset++)) >= 0; --remaining) { - } + for (; remaining > 0 && (byte1 = UnsafeUtil.getByte(bytes, offset++)) >= 0; --remaining) {} if (remaining == 0) { return COMPLETE; } @@ -1762,8 +1722,7 @@ final class Utf8 { // Simultaneously checks for illegal trailing-byte in // leading position and overlong 2-byte form. - if (byte1 < (byte) 0xC2 - || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { + if (byte1 < (byte) 0xC2 || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { return MALFORMED; } } else if (byte1 < (byte) 0xF0) { @@ -1815,13 +1774,12 @@ final class Utf8 { address += skipped; remaining -= skipped; - for (;;) { + for (; ; ) { // Optimize for interior runs of ASCII bytes. // TODO(nathanmittler): Consider checking 8 bytes at a time after some threshold? // Maybe after seeing a few in a row that are ASCII, go back to fast mode? int byte1 = 0; - for (; remaining > 0 && (byte1 = UnsafeUtil.getByte(address++)) >= 0; --remaining) { - } + for (; remaining > 0 && (byte1 = UnsafeUtil.getByte(address++)) >= 0; --remaining) {} if (remaining == 0) { return COMPLETE; } @@ -1886,40 +1844,32 @@ final class Utf8 { } } - private static int unsafeIncompleteStateFor(byte[] bytes, int byte1, long offset, - int remaining) { + private static int unsafeIncompleteStateFor( + byte[] bytes, int byte1, long offset, int remaining) { switch (remaining) { - case 0: { + case 0: return incompleteStateFor(byte1); - } - case 1: { + case 1: return incompleteStateFor(byte1, UnsafeUtil.getByte(bytes, offset)); - } - case 2: { - return incompleteStateFor(byte1, UnsafeUtil.getByte(bytes, offset), - UnsafeUtil.getByte(bytes, offset + 1)); - } - default: { + case 2: + return incompleteStateFor( + byte1, UnsafeUtil.getByte(bytes, offset), UnsafeUtil.getByte(bytes, offset + 1)); + default: throw new AssertionError(); - } } } private static int unsafeIncompleteStateFor(long address, final int byte1, int remaining) { switch (remaining) { - case 0: { + case 0: return incompleteStateFor(byte1); - } - case 1: { + case 1: return incompleteStateFor(byte1, UnsafeUtil.getByte(address)); - } - case 2: { - return incompleteStateFor(byte1, UnsafeUtil.getByte(address), - UnsafeUtil.getByte(address + 1)); - } - default: { + case 2: + return incompleteStateFor( + byte1, UnsafeUtil.getByte(address), UnsafeUtil.getByte(address + 1)); + default: throw new AssertionError(); - } } } } @@ -1931,23 +1881,17 @@ final class Utf8 { */ private static class DecodeUtil { - /** - * Returns whether this is a single-byte codepoint (i.e., ASCII) with the form '0XXXXXXX'. - */ + /** Returns whether this is a single-byte codepoint (i.e., ASCII) with the form '0XXXXXXX'. */ private static boolean isOneByte(byte b) { return b >= 0; } - /** - * Returns whether this is a two-byte codepoint with the form '10XXXXXX'. - */ + /** Returns whether this is a two-byte codepoint with the form '10XXXXXX'. */ private static boolean isTwoBytes(byte b) { return b < (byte) 0xE0; } - /** - * Returns whether this is a three-byte codepoint with the form '110XXXXX'. - */ + /** Returns whether this is a three-byte codepoint with the form '110XXXXX'. */ private static boolean isThreeBytes(byte b) { return b < (byte) 0xF0; } @@ -1956,13 +1900,11 @@ final class Utf8 { resultArr[resultPos] = (char) byte1; } - private static void handleTwoBytes( - byte byte1, byte byte2, char[] resultArr, int resultPos) + private static void handleTwoBytes(byte byte1, byte byte2, char[] resultArr, int resultPos) throws InvalidProtocolBufferException { // Simultaneously checks for illegal trailing-byte in leading position (<= '11000000') and // overlong 2-byte, '11000001'. - if (byte1 < (byte) 0xC2 - || isNotTrailingByte(byte2)) { + if (byte1 < (byte) 0xC2 || isNotTrailingByte(byte2)) { throw InvalidProtocolBufferException.invalidUtf8(); } resultArr[resultPos] = (char) (((byte1 & 0x1F) << 6) | trailingByteValue(byte2)); @@ -1979,13 +1921,14 @@ final class Utf8 { || isNotTrailingByte(byte3)) { throw InvalidProtocolBufferException.invalidUtf8(); } - resultArr[resultPos] = (char) - (((byte1 & 0x0F) << 12) | (trailingByteValue(byte2) << 6) | trailingByteValue(byte3)); + resultArr[resultPos] = + (char) + (((byte1 & 0x0F) << 12) | (trailingByteValue(byte2) << 6) | trailingByteValue(byte3)); } private static void handleFourBytes( byte byte1, byte byte2, byte byte3, byte byte4, char[] resultArr, int resultPos) - throws InvalidProtocolBufferException{ + throws InvalidProtocolBufferException { if (isNotTrailingByte(byte2) // Check that 1 <= plane <= 16. Tricky optimized form of: // valid 4-byte leading byte? @@ -1999,31 +1942,28 @@ final class Utf8 { || isNotTrailingByte(byte4)) { throw InvalidProtocolBufferException.invalidUtf8(); } - int codepoint = ((byte1 & 0x07) << 18) - | (trailingByteValue(byte2) << 12) - | (trailingByteValue(byte3) << 6) - | trailingByteValue(byte4); + int codepoint = + ((byte1 & 0x07) << 18) + | (trailingByteValue(byte2) << 12) + | (trailingByteValue(byte3) << 6) + | trailingByteValue(byte4); resultArr[resultPos] = DecodeUtil.highSurrogate(codepoint); resultArr[resultPos + 1] = DecodeUtil.lowSurrogate(codepoint); } - /** - * Returns whether the byte is not a valid continuation of the form '10XXXXXX'. - */ + /** Returns whether the byte is not a valid continuation of the form '10XXXXXX'. */ private static boolean isNotTrailingByte(byte b) { return b > (byte) 0xBF; } - /** - * Returns the actual value of the trailing byte (removes the prefix '10') for composition. - */ + /** Returns the actual value of the trailing byte (removes the prefix '10') for composition. */ private static int trailingByteValue(byte b) { return b & 0x3F; } private static char highSurrogate(int codePoint) { - return (char) ((MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10)) - + (codePoint >>> 10)); + return (char) + ((MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10)) + (codePoint >>> 10)); } private static char lowSurrogate(int codePoint) { diff --git a/java/core/src/main/java/com/google/protobuf/WireFormat.java b/java/core/src/main/java/com/google/protobuf/WireFormat.java index 8b837ee5e1..3c6e8dda4d 100644 --- a/java/core/src/main/java/com/google/protobuf/WireFormat.java +++ b/java/core/src/main/java/com/google/protobuf/WireFormat.java @@ -33,13 +33,12 @@ package com.google.protobuf; import java.io.IOException; /** - * This class is used internally by the Protocol Buffer library and generated - * message implementations. It is public only because those generated messages - * do not reside in the {@code protobuf} package. Others should not use this - * class directly. + * This class is used internally by the Protocol Buffer library and generated message + * implementations. It is public only because those generated messages do not reside in the {@code + * protobuf} package. Others should not use this class directly. * - * This class contains constants and helper functions useful for dealing with - * the Protocol Buffer wire format. + *

This class contains constants and helper functions useful for dealing with the Protocol Buffer + * wire format. * * @author kenton@google.com Kenton Varda */ @@ -53,12 +52,12 @@ public final class WireFormat { static final int MAX_VARINT64_SIZE = 10; static final int MAX_VARINT_SIZE = 10; - public static final int WIRETYPE_VARINT = 0; - public static final int WIRETYPE_FIXED64 = 1; + public static final int WIRETYPE_VARINT = 0; + public static final int WIRETYPE_FIXED64 = 1; public static final int WIRETYPE_LENGTH_DELIMITED = 2; - public static final int WIRETYPE_START_GROUP = 3; - public static final int WIRETYPE_END_GROUP = 4; - public static final int WIRETYPE_FIXED32 = 5; + public static final int WIRETYPE_START_GROUP = 3; + public static final int WIRETYPE_END_GROUP = 4; + public static final int WIRETYPE_FIXED32 = 5; static final int TAG_TYPE_BITS = 3; static final int TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1; @@ -79,8 +78,8 @@ public final class WireFormat { } /** - * Lite equivalent to {@link Descriptors.FieldDescriptor.JavaType}. This is - * only here to support the lite runtime and should not be used by users. + * Lite equivalent to {@link Descriptors.FieldDescriptor.JavaType}. This is only here to support + * the lite runtime and should not be used by users. */ public enum JavaType { INT(0), @@ -97,10 +96,7 @@ public final class WireFormat { this.defaultDefault = defaultDefault; } - /** - * The default default value for fields of this type, if it's a primitive - * type. - */ + /** The default default value for fields of this type, if it's a primitive type. */ Object getDefaultDefault() { return defaultDefault; } @@ -109,44 +105,48 @@ public final class WireFormat { } /** - * Lite equivalent to {@link Descriptors.FieldDescriptor.Type}. This is - * only here to support the lite runtime and should not be used by users. + * Lite equivalent to {@link Descriptors.FieldDescriptor.Type}. This is only here to support the + * lite runtime and should not be used by users. */ public enum FieldType { - DOUBLE (JavaType.DOUBLE , WIRETYPE_FIXED64 ), - FLOAT (JavaType.FLOAT , WIRETYPE_FIXED32 ), - INT64 (JavaType.LONG , WIRETYPE_VARINT ), - UINT64 (JavaType.LONG , WIRETYPE_VARINT ), - INT32 (JavaType.INT , WIRETYPE_VARINT ), - FIXED64 (JavaType.LONG , WIRETYPE_FIXED64 ), - FIXED32 (JavaType.INT , WIRETYPE_FIXED32 ), - BOOL (JavaType.BOOLEAN , WIRETYPE_VARINT ), - STRING (JavaType.STRING , WIRETYPE_LENGTH_DELIMITED) { + DOUBLE(JavaType.DOUBLE, WIRETYPE_FIXED64), + FLOAT(JavaType.FLOAT, WIRETYPE_FIXED32), + INT64(JavaType.LONG, WIRETYPE_VARINT), + UINT64(JavaType.LONG, WIRETYPE_VARINT), + INT32(JavaType.INT, WIRETYPE_VARINT), + FIXED64(JavaType.LONG, WIRETYPE_FIXED64), + FIXED32(JavaType.INT, WIRETYPE_FIXED32), + BOOL(JavaType.BOOLEAN, WIRETYPE_VARINT), + STRING(JavaType.STRING, WIRETYPE_LENGTH_DELIMITED) { @Override public boolean isPackable() { - return false; } + return false; + } }, - GROUP (JavaType.MESSAGE , WIRETYPE_START_GROUP ) { + GROUP(JavaType.MESSAGE, WIRETYPE_START_GROUP) { @Override public boolean isPackable() { - return false; } + return false; + } }, - MESSAGE (JavaType.MESSAGE , WIRETYPE_LENGTH_DELIMITED) { + MESSAGE(JavaType.MESSAGE, WIRETYPE_LENGTH_DELIMITED) { @Override public boolean isPackable() { - return false; } + return false; + } }, - BYTES (JavaType.BYTE_STRING, WIRETYPE_LENGTH_DELIMITED) { + BYTES(JavaType.BYTE_STRING, WIRETYPE_LENGTH_DELIMITED) { @Override public boolean isPackable() { - return false; } + return false; + } }, - UINT32 (JavaType.INT , WIRETYPE_VARINT ), - ENUM (JavaType.ENUM , WIRETYPE_VARINT ), - SFIXED32(JavaType.INT , WIRETYPE_FIXED32 ), - SFIXED64(JavaType.LONG , WIRETYPE_FIXED64 ), - SINT32 (JavaType.INT , WIRETYPE_VARINT ), - SINT64 (JavaType.LONG , WIRETYPE_VARINT ); + UINT32(JavaType.INT, WIRETYPE_VARINT), + ENUM(JavaType.ENUM, WIRETYPE_VARINT), + SFIXED32(JavaType.INT, WIRETYPE_FIXED32), + SFIXED64(JavaType.LONG, WIRETYPE_FIXED64), + SINT32(JavaType.INT, WIRETYPE_VARINT), + SINT64(JavaType.LONG, WIRETYPE_VARINT); FieldType(final JavaType javaType, final int wireType) { this.javaType = javaType; @@ -156,30 +156,34 @@ public final class WireFormat { private final JavaType javaType; private final int wireType; - public JavaType getJavaType() { return javaType; } - public int getWireType() { return wireType; } + public JavaType getJavaType() { + return javaType; + } - public boolean isPackable() { return true; } + public int getWireType() { + return wireType; + } + + public boolean isPackable() { + return true; + } } // Field numbers for fields in MessageSet wire format. - static final int MESSAGE_SET_ITEM = 1; + static final int MESSAGE_SET_ITEM = 1; static final int MESSAGE_SET_TYPE_ID = 2; static final int MESSAGE_SET_MESSAGE = 3; // Tag numbers. - static final int MESSAGE_SET_ITEM_TAG = - makeTag(MESSAGE_SET_ITEM, WIRETYPE_START_GROUP); - static final int MESSAGE_SET_ITEM_END_TAG = - makeTag(MESSAGE_SET_ITEM, WIRETYPE_END_GROUP); - static final int MESSAGE_SET_TYPE_ID_TAG = - makeTag(MESSAGE_SET_TYPE_ID, WIRETYPE_VARINT); + static final int MESSAGE_SET_ITEM_TAG = makeTag(MESSAGE_SET_ITEM, WIRETYPE_START_GROUP); + static final int MESSAGE_SET_ITEM_END_TAG = makeTag(MESSAGE_SET_ITEM, WIRETYPE_END_GROUP); + static final int MESSAGE_SET_TYPE_ID_TAG = makeTag(MESSAGE_SET_TYPE_ID, WIRETYPE_VARINT); static final int MESSAGE_SET_MESSAGE_TAG = - makeTag(MESSAGE_SET_MESSAGE, WIRETYPE_LENGTH_DELIMITED); + makeTag(MESSAGE_SET_MESSAGE, WIRETYPE_LENGTH_DELIMITED); /** - * Validation level for handling incoming string field data which potentially - * contain non-UTF8 bytes. + * Validation level for handling incoming string field data which potentially contain non-UTF8 + * bytes. */ enum Utf8Validation { /** Eagerly parses to String; silently accepts invalid UTF8 bytes. */ @@ -209,54 +213,59 @@ public final class WireFormat { } /** - * Read a field of any primitive type for immutable messages from a - * CodedInputStream. Enums, groups, and embedded messages are not handled by - * this method. + * Read a field of any primitive type for immutable messages from a CodedInputStream. Enums, + * groups, and embedded messages are not handled by this method. * * @param input The stream from which to read. * @param type Declared type of the field. - * @param utf8Validation Different string UTF8 validation level for handling - * string fields. - * @return An object representing the field's value, of the exact - * type which would be returned by - * {@link Message#getField(Descriptors.FieldDescriptor)} for - * this field. + * @param utf8Validation Different string UTF8 validation level for handling string fields. + * @return An object representing the field's value, of the exact type which would be returned by + * {@link Message#getField(Descriptors.FieldDescriptor)} for this field. */ static Object readPrimitiveField( - CodedInputStream input, - FieldType type, - Utf8Validation utf8Validation) throws IOException { + CodedInputStream input, FieldType type, Utf8Validation utf8Validation) throws IOException { switch (type) { - case DOUBLE : return input.readDouble (); - case FLOAT : return input.readFloat (); - case INT64 : return input.readInt64 (); - case UINT64 : return input.readUInt64 (); - case INT32 : return input.readInt32 (); - case FIXED64 : return input.readFixed64 (); - case FIXED32 : return input.readFixed32 (); - case BOOL : return input.readBool (); - case BYTES : return input.readBytes (); - case UINT32 : return input.readUInt32 (); - case SFIXED32: return input.readSFixed32(); - case SFIXED64: return input.readSFixed64(); - case SINT32 : return input.readSInt32 (); - case SINT64 : return input.readSInt64 (); + case DOUBLE: + return input.readDouble(); + case FLOAT: + return input.readFloat(); + case INT64: + return input.readInt64(); + case UINT64: + return input.readUInt64(); + case INT32: + return input.readInt32(); + case FIXED64: + return input.readFixed64(); + case FIXED32: + return input.readFixed32(); + case BOOL: + return input.readBool(); + case BYTES: + return input.readBytes(); + case UINT32: + return input.readUInt32(); + case SFIXED32: + return input.readSFixed32(); + case SFIXED64: + return input.readSFixed64(); + case SINT32: + return input.readSInt32(); + case SINT64: + return input.readSInt64(); - case STRING : return utf8Validation.readString(input); + case STRING: + return utf8Validation.readString(input); case GROUP: - throw new IllegalArgumentException( - "readPrimitiveField() cannot handle nested groups."); + throw new IllegalArgumentException("readPrimitiveField() cannot handle nested groups."); case MESSAGE: - throw new IllegalArgumentException( - "readPrimitiveField() cannot handle embedded messages."); + throw new IllegalArgumentException("readPrimitiveField() cannot handle embedded messages."); case ENUM: // We don't handle enums because we don't know what to do if the // value is not recognized. - throw new IllegalArgumentException( - "readPrimitiveField() cannot handle enums."); + throw new IllegalArgumentException("readPrimitiveField() cannot handle enums."); } - throw new RuntimeException( - "There is no way to get here, but the compiler thinks otherwise."); + throw new RuntimeException("There is no way to get here, but the compiler thinks otherwise."); } } diff --git a/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java b/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java index bb11bd0f96..1020c69c50 100644 --- a/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java +++ b/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java @@ -53,10 +53,9 @@ import junit.framework.TestCase; */ public class AbstractMessageTest extends TestCase { /** - * Extends AbstractMessage and wraps some other message object. The methods - * of the Message interface which aren't explicitly implemented by - * AbstractMessage are forwarded to the wrapped object. This allows us to - * test that AbstractMessage's implementations work even if the wrapped + * Extends AbstractMessage and wraps some other message object. The methods of the Message + * interface which aren't explicitly implemented by AbstractMessage are forwarded to the wrapped + * object. This allows us to test that AbstractMessage's implementations work even if the wrapped * object does not use them. */ private static class AbstractMessageWrapper extends AbstractMessage { @@ -70,39 +69,47 @@ public class AbstractMessageTest extends TestCase { public Descriptors.Descriptor getDescriptorForType() { return wrappedMessage.getDescriptorForType(); } + @Override public AbstractMessageWrapper getDefaultInstanceForType() { - return new AbstractMessageWrapper( - wrappedMessage.getDefaultInstanceForType()); + return new AbstractMessageWrapper(wrappedMessage.getDefaultInstanceForType()); } + @Override public Map getAllFields() { return wrappedMessage.getAllFields(); } + @Override public boolean hasField(Descriptors.FieldDescriptor field) { return wrappedMessage.hasField(field); } + @Override public Object getField(Descriptors.FieldDescriptor field) { return wrappedMessage.getField(field); } + @Override public int getRepeatedFieldCount(Descriptors.FieldDescriptor field) { return wrappedMessage.getRepeatedFieldCount(field); } + @Override public Object getRepeatedField(Descriptors.FieldDescriptor field, int index) { return wrappedMessage.getRepeatedField(field, index); } + @Override public UnknownFieldSet getUnknownFields() { return wrappedMessage.getUnknownFields(); } + @Override public Builder newBuilderForType() { return new Builder(wrappedMessage.newBuilderForType()); } + @Override public Builder toBuilder() { return new Builder(wrappedMessage.toBuilder()); @@ -119,85 +126,103 @@ public class AbstractMessageTest extends TestCase { public AbstractMessageWrapper build() { return new AbstractMessageWrapper(wrappedBuilder.build()); } + @Override public AbstractMessageWrapper buildPartial() { return new AbstractMessageWrapper(wrappedBuilder.buildPartial()); } + @Override public Builder clone() { return new Builder(wrappedBuilder.clone()); } + @Override public boolean isInitialized() { return clone().buildPartial().isInitialized(); } + @Override public Descriptors.Descriptor getDescriptorForType() { return wrappedBuilder.getDescriptorForType(); } + @Override public AbstractMessageWrapper getDefaultInstanceForType() { - return new AbstractMessageWrapper( - wrappedBuilder.getDefaultInstanceForType()); + return new AbstractMessageWrapper(wrappedBuilder.getDefaultInstanceForType()); } + @Override public Map getAllFields() { return wrappedBuilder.getAllFields(); } + @Override public Builder newBuilderForField(Descriptors.FieldDescriptor field) { return new Builder(wrappedBuilder.newBuilderForField(field)); } + @Override public boolean hasField(Descriptors.FieldDescriptor field) { return wrappedBuilder.hasField(field); } + @Override public Object getField(Descriptors.FieldDescriptor field) { return wrappedBuilder.getField(field); } + @Override public Builder setField(Descriptors.FieldDescriptor field, Object value) { wrappedBuilder.setField(field, value); return this; } + @Override public Builder clearField(Descriptors.FieldDescriptor field) { wrappedBuilder.clearField(field); return this; } + @Override public int getRepeatedFieldCount(Descriptors.FieldDescriptor field) { return wrappedBuilder.getRepeatedFieldCount(field); } + @Override public Object getRepeatedField(Descriptors.FieldDescriptor field, int index) { return wrappedBuilder.getRepeatedField(field, index); } + @Override public Builder setRepeatedField(Descriptors.FieldDescriptor field, int index, Object value) { wrappedBuilder.setRepeatedField(field, index, value); return this; } + @Override public Builder addRepeatedField(Descriptors.FieldDescriptor field, Object value) { wrappedBuilder.addRepeatedField(field, value); return this; } + @Override public UnknownFieldSet getUnknownFields() { return wrappedBuilder.getUnknownFields(); } + @Override public Builder setUnknownFields(UnknownFieldSet unknownFields) { wrappedBuilder.setUnknownFields(unknownFields); return this; } + @Override public Message.Builder getFieldBuilder(FieldDescriptor field) { return wrappedBuilder.getFieldBuilder(field); } } + @Override public Parser getParserForType() { return wrappedMessage.getParserForType(); @@ -207,7 +232,7 @@ public class AbstractMessageTest extends TestCase { // ================================================================= TestUtil.ReflectionTester reflectionTester = - new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null); + new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null); TestUtil.ReflectionTester extensionsReflectionTester = new TestUtil.ReflectionTester( @@ -215,16 +240,17 @@ public class AbstractMessageTest extends TestCase { public void testClear() throws Exception { AbstractMessageWrapper message = - new AbstractMessageWrapper.Builder( - TestAllTypes.newBuilder(TestUtil.getAllSet())) - .clear().build(); + new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder(TestUtil.getAllSet())) + .clear() + .build(); TestUtil.assertClear((TestAllTypes) message.wrappedMessage); } public void testCopy() throws Exception { AbstractMessageWrapper message = - new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder()) - .mergeFrom(TestUtil.getAllSet()).build(); + new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder()) + .mergeFrom(TestUtil.getAllSet()) + .build(); TestUtil.assertAllFieldsSet((TestAllTypes) message.wrappedMessage); } @@ -232,25 +258,21 @@ public class AbstractMessageTest extends TestCase { TestAllTypes message = TestUtil.getAllSet(); Message abstractMessage = new AbstractMessageWrapper(TestUtil.getAllSet()); - assertEquals(message.getSerializedSize(), - abstractMessage.getSerializedSize()); + assertEquals(message.getSerializedSize(), abstractMessage.getSerializedSize()); } public void testSerialization() throws Exception { Message abstractMessage = new AbstractMessageWrapper(TestUtil.getAllSet()); - TestUtil.assertAllFieldsSet( - TestAllTypes.parseFrom(abstractMessage.toByteString())); + TestUtil.assertAllFieldsSet(TestAllTypes.parseFrom(abstractMessage.toByteString())); - assertEquals(TestUtil.getAllSet().toByteString(), - abstractMessage.toByteString()); + assertEquals(TestUtil.getAllSet().toByteString(), abstractMessage.toByteString()); } public void testParsing() throws Exception { AbstractMessageWrapper.Builder builder = - new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder()); - AbstractMessageWrapper message = - builder.mergeFrom(TestUtil.getAllSet().toByteString()).build(); + new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder()); + AbstractMessageWrapper message = builder.mergeFrom(TestUtil.getAllSet().toByteString()).build(); TestUtil.assertAllFieldsSet((TestAllTypes) message.wrappedMessage); } @@ -270,8 +292,8 @@ public class AbstractMessageTest extends TestCase { } // test DynamicMessage directly. - Message.Builder dynamicMessageBuilder = DynamicMessage.newBuilder( - TestRequiredForeign.getDescriptor()); + Message.Builder dynamicMessageBuilder = + DynamicMessage.newBuilder(TestRequiredForeign.getDescriptor()); // mergeFrom() should not throw initialization error. dynamicMessageBuilder.mergeFrom(bytes).buildPartial(); try { @@ -283,65 +305,56 @@ public class AbstractMessageTest extends TestCase { } public void testPackedSerialization() throws Exception { - Message abstractMessage = - new AbstractMessageWrapper(TestUtil.getPackedSet()); + Message abstractMessage = new AbstractMessageWrapper(TestUtil.getPackedSet()); - TestUtil.assertPackedFieldsSet( - TestPackedTypes.parseFrom(abstractMessage.toByteString())); + TestUtil.assertPackedFieldsSet(TestPackedTypes.parseFrom(abstractMessage.toByteString())); - assertEquals(TestUtil.getPackedSet().toByteString(), - abstractMessage.toByteString()); + assertEquals(TestUtil.getPackedSet().toByteString(), abstractMessage.toByteString()); } public void testPackedParsing() throws Exception { AbstractMessageWrapper.Builder builder = - new AbstractMessageWrapper.Builder(TestPackedTypes.newBuilder()); + new AbstractMessageWrapper.Builder(TestPackedTypes.newBuilder()); AbstractMessageWrapper message = - builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build(); + builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build(); TestUtil.assertPackedFieldsSet((TestPackedTypes) message.wrappedMessage); } public void testUnpackedSerialization() throws Exception { - Message abstractMessage = - new AbstractMessageWrapper(TestUtil.getUnpackedSet()); + Message abstractMessage = new AbstractMessageWrapper(TestUtil.getUnpackedSet()); - TestUtil.assertUnpackedFieldsSet( - TestUnpackedTypes.parseFrom(abstractMessage.toByteString())); + TestUtil.assertUnpackedFieldsSet(TestUnpackedTypes.parseFrom(abstractMessage.toByteString())); - assertEquals(TestUtil.getUnpackedSet().toByteString(), - abstractMessage.toByteString()); + assertEquals(TestUtil.getUnpackedSet().toByteString(), abstractMessage.toByteString()); } public void testParsePackedToUnpacked() throws Exception { AbstractMessageWrapper.Builder builder = - new AbstractMessageWrapper.Builder(TestUnpackedTypes.newBuilder()); + new AbstractMessageWrapper.Builder(TestUnpackedTypes.newBuilder()); AbstractMessageWrapper message = - builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build(); - TestUtil.assertUnpackedFieldsSet( - (TestUnpackedTypes) message.wrappedMessage); + builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build(); + TestUtil.assertUnpackedFieldsSet((TestUnpackedTypes) message.wrappedMessage); } public void testParseUnpackedToPacked() throws Exception { AbstractMessageWrapper.Builder builder = - new AbstractMessageWrapper.Builder(TestPackedTypes.newBuilder()); + new AbstractMessageWrapper.Builder(TestPackedTypes.newBuilder()); AbstractMessageWrapper message = - builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build(); + builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build(); TestUtil.assertPackedFieldsSet((TestPackedTypes) message.wrappedMessage); } public void testUnpackedParsing() throws Exception { AbstractMessageWrapper.Builder builder = - new AbstractMessageWrapper.Builder(TestUnpackedTypes.newBuilder()); + new AbstractMessageWrapper.Builder(TestUnpackedTypes.newBuilder()); AbstractMessageWrapper message = - builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build(); - TestUtil.assertUnpackedFieldsSet( - (TestUnpackedTypes) message.wrappedMessage); + builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build(); + TestUtil.assertUnpackedFieldsSet((TestUnpackedTypes) message.wrappedMessage); } public void testOptimizedForSize() throws Exception { // We're mostly only checking that this class was compiled successfully. - TestOptimizedForSize message = - TestOptimizedForSize.newBuilder().setI(1).build(); + TestOptimizedForSize message = TestOptimizedForSize.newBuilder().setI(1).build(); message = TestOptimizedForSize.parseFrom(message.toByteString()); assertEquals(2, message.getSerializedSize()); } @@ -351,8 +364,7 @@ public class AbstractMessageTest extends TestCase { public void testIsInitialized() throws Exception { TestRequired.Builder builder = TestRequired.newBuilder(); - AbstractMessageWrapper.Builder abstractBuilder = - new AbstractMessageWrapper.Builder(builder); + AbstractMessageWrapper.Builder abstractBuilder = new AbstractMessageWrapper.Builder(builder); assertFalse(abstractBuilder.isInitialized()); assertEquals("a, b, c", abstractBuilder.getInitializationErrorString()); @@ -369,8 +381,7 @@ public class AbstractMessageTest extends TestCase { public void testForeignIsInitialized() throws Exception { TestRequiredForeign.Builder builder = TestRequiredForeign.newBuilder(); - AbstractMessageWrapper.Builder abstractBuilder = - new AbstractMessageWrapper.Builder(builder); + AbstractMessageWrapper.Builder abstractBuilder = new AbstractMessageWrapper.Builder(builder); assertTrue(abstractBuilder.isInitialized()); assertEquals("", abstractBuilder.getInitializationErrorString()); @@ -378,8 +389,7 @@ public class AbstractMessageTest extends TestCase { builder.setOptionalMessage(TEST_REQUIRED_UNINITIALIZED); assertFalse(abstractBuilder.isInitialized()); assertEquals( - "optional_message.b, optional_message.c", - abstractBuilder.getInitializationErrorString()); + "optional_message.b, optional_message.c", abstractBuilder.getInitializationErrorString()); builder.setOptionalMessage(TEST_REQUIRED_INITIALIZED); assertTrue(abstractBuilder.isInitialized()); @@ -400,36 +410,37 @@ public class AbstractMessageTest extends TestCase { // Tests for mergeFrom static final TestAllTypes MERGE_SOURCE = - TestAllTypes.newBuilder() - .setOptionalInt32(1) - .setOptionalString("foo") - .setOptionalForeignMessage(ForeignMessage.getDefaultInstance()) - .addRepeatedString("bar") - .build(); + TestAllTypes.newBuilder() + .setOptionalInt32(1) + .setOptionalString("foo") + .setOptionalForeignMessage(ForeignMessage.getDefaultInstance()) + .addRepeatedString("bar") + .build(); static final TestAllTypes MERGE_DEST = - TestAllTypes.newBuilder() - .setOptionalInt64(2) - .setOptionalString("baz") - .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(3).build()) - .addRepeatedString("qux") - .build(); + TestAllTypes.newBuilder() + .setOptionalInt64(2) + .setOptionalString("baz") + .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(3).build()) + .addRepeatedString("qux") + .build(); static final String MERGE_RESULT_TEXT = - "optional_int32: 1\n" + - "optional_int64: 2\n" + - "optional_string: \"foo\"\n" + - "optional_foreign_message {\n" + - " c: 3\n" + - "}\n" + - "repeated_string: \"qux\"\n" + - "repeated_string: \"bar\"\n"; + "" + + "optional_int32: 1\n" + + "optional_int64: 2\n" + + "optional_string: \"foo\"\n" + + "optional_foreign_message {\n" + + " c: 3\n" + + "}\n" + + "repeated_string: \"qux\"\n" + + "repeated_string: \"bar\"\n"; public void testMergeFrom() throws Exception { AbstractMessageWrapper result = - new AbstractMessageWrapper.Builder( - TestAllTypes.newBuilder(MERGE_DEST)) - .mergeFrom(MERGE_SOURCE).build(); + new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder(MERGE_DEST)) + .mergeFrom(MERGE_SOURCE) + .build(); assertEquals(MERGE_RESULT_TEXT, result.toString()); } @@ -443,8 +454,10 @@ public class AbstractMessageTest extends TestCase { TestAllTypes c = TestAllTypes.newBuilder(b).addRepeatedString("x").build(); TestAllTypes d = TestAllTypes.newBuilder(c).addRepeatedString("y").build(); TestAllExtensions e = TestUtil.getAllExtensionsSet(); - TestAllExtensions f = TestAllExtensions.newBuilder(e) - .addExtension(UnittestProto.repeatedInt32Extension, 999).build(); + TestAllExtensions f = + TestAllExtensions.newBuilder(e) + .addExtension(UnittestProto.repeatedInt32Extension, 999) + .build(); checkEqualsIsConsistent(a); checkEqualsIsConsistent(b); @@ -489,9 +502,7 @@ public class AbstractMessageTest extends TestCase { checkEqualsIsConsistent(eUnknownFields, eUnknownFields2); } - /** - * Asserts that the given proto has symmetric equals and hashCode methods. - */ + /** Asserts that the given proto has symmetric equals and hashCode methods. */ private void checkEqualsIsConsistent(Message message) { // Object should be equal to itself. assertEquals(message, message); @@ -501,9 +512,7 @@ public class AbstractMessageTest extends TestCase { checkEqualsIsConsistent(message, dynamic); } - /** - * Asserts that the given protos are equal and have the same hash code. - */ + /** Asserts that the given protos are equal and have the same hash code. */ private void checkEqualsIsConsistent(Message message1, Message message2) { assertEquals(message1, message2); assertEquals(message2, message1); @@ -513,9 +522,8 @@ public class AbstractMessageTest extends TestCase { /** * Asserts that the given protos are not equal and have different hash codes. * - * @warning It's valid for non-equal objects to have the same hash code, so - * this test is stricter than it needs to be. However, this should happen - * relatively rarely. + * @warning It's valid for non-equal objects to have the same hash code, so this test is stricter + * than it needs to be. However, this should happen relatively rarely. */ private void checkNotEqual(Message m1, Message m2) { String equalsError = String.format("%s should not be equal to %s", m1, m2); @@ -535,7 +543,7 @@ public class AbstractMessageTest extends TestCase { public void testCheckByteStringIsUtf8OnNonUtf8() { ByteString byteString = - ByteString.copyFrom(new byte[]{(byte) 0x80}); // A lone continuation byte. + ByteString.copyFrom(new byte[] {(byte) 0x80}); // A lone continuation byte. try { AbstractMessageLite.checkByteStringIsUtf8(byteString); fail("Expected AbstractMessageLite.checkByteStringIsUtf8 to throw IllegalArgumentException"); @@ -543,5 +551,4 @@ public class AbstractMessageTest extends TestCase { assertEquals("Byte string is not UTF-8.", exception.getMessage()); } } - } diff --git a/java/core/src/test/java/com/google/protobuf/AnyTest.java b/java/core/src/test/java/com/google/protobuf/AnyTest.java index cf91ed91c6..2fe04a94c9 100644 --- a/java/core/src/test/java/com/google/protobuf/AnyTest.java +++ b/java/core/src/test/java/com/google/protobuf/AnyTest.java @@ -32,7 +32,7 @@ package com.google.protobuf; import any_test.AnyTestProto.TestAny; import protobuf_unittest.UnittestProto.TestAllTypes; - +import java.util.Objects; import junit.framework.TestCase; /** @@ -56,7 +56,7 @@ public class AnyTest extends TestCase { // Unpacking to a wrong type will throw an exception. try { - TestAny wrongMessage = container.getValue().unpack(TestAny.class); + container.getValue().unpack(TestAny.class); fail("Exception is expected."); } catch (InvalidProtocolBufferException e) { // expected. @@ -68,7 +68,7 @@ public class AnyTest extends TestCase { ByteString.copyFrom(new byte[]{0x11})); container = containerBuilder.build(); try { - TestAllTypes parsingFailed = container.getValue().unpack(TestAllTypes.class); + container.getValue().unpack(TestAllTypes.class); fail("Exception is expected."); } catch (InvalidProtocolBufferException e) { // expected. @@ -132,6 +132,6 @@ public class AnyTest extends TestCase { TestAllTypes result1 = container.getValue().unpack(TestAllTypes.class); TestAllTypes result2 = container.getValue().unpack(TestAllTypes.class); - assertTrue(result1 == result2); + assertTrue(Objects.equals(result1, result2)); } } diff --git a/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java b/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java index febe8537f6..8ef8edd225 100644 --- a/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java +++ b/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java @@ -45,8 +45,7 @@ import junit.framework.TestCase; */ public class BooleanArrayListTest extends TestCase { - private static final BooleanArrayList UNARY_LIST = - newImmutableBooleanArrayList(true); + private static final BooleanArrayList UNARY_LIST = newImmutableBooleanArrayList(true); private static final BooleanArrayList TERTIARY_LIST = newImmutableBooleanArrayList(true, false, true); @@ -78,10 +77,10 @@ public class BooleanArrayListTest extends TestCase { list.addAll(asList(true, false, true, false)); Iterator iterator = list.iterator(); assertEquals(4, list.size()); - assertEquals(true, (boolean) list.get(0)); - assertEquals(true, (boolean) iterator.next()); + assertTrue(list.get(0)); + assertTrue(iterator.next()); list.set(0, true); - assertEquals(false, (boolean) iterator.next()); + assertFalse(iterator.next()); list.remove(0); try { @@ -102,9 +101,9 @@ public class BooleanArrayListTest extends TestCase { } public void testGet() { - assertEquals(true, (boolean) TERTIARY_LIST.get(0)); - assertEquals(false, (boolean) TERTIARY_LIST.get(1)); - assertEquals(true, (boolean) TERTIARY_LIST.get(2)); + assertTrue(TERTIARY_LIST.get(0)); + assertFalse(TERTIARY_LIST.get(1)); + assertTrue(TERTIARY_LIST.get(2)); try { TERTIARY_LIST.get(-1); @@ -122,9 +121,9 @@ public class BooleanArrayListTest extends TestCase { } public void testGetBoolean() { - assertEquals(true, TERTIARY_LIST.getBoolean(0)); - assertEquals(false, TERTIARY_LIST.getBoolean(1)); - assertEquals(true, TERTIARY_LIST.getBoolean(2)); + assertTrue(TERTIARY_LIST.getBoolean(0)); + assertFalse(TERTIARY_LIST.getBoolean(1)); + assertTrue(TERTIARY_LIST.getBoolean(2)); try { TERTIARY_LIST.get(-1); @@ -163,11 +162,11 @@ public class BooleanArrayListTest extends TestCase { list.addBoolean(false); list.addBoolean(false); - assertEquals(false, (boolean) list.set(0, true)); - assertEquals(true, list.getBoolean(0)); + assertFalse(list.set(0, true)); + assertTrue(list.getBoolean(0)); - assertEquals(false, (boolean) list.set(1, false)); - assertEquals(false, list.getBoolean(1)); + assertFalse(list.set(1, false)); + assertFalse(list.getBoolean(1)); try { list.set(-1, false); @@ -188,11 +187,11 @@ public class BooleanArrayListTest extends TestCase { list.addBoolean(true); list.addBoolean(true); - assertEquals(true, list.setBoolean(0, false)); - assertEquals(false, list.getBoolean(0)); + assertTrue(list.setBoolean(0, false)); + assertFalse(list.getBoolean(0)); - assertEquals(true, list.setBoolean(1, false)); - assertEquals(false, list.getBoolean(1)); + assertTrue(list.setBoolean(1, false)); + assertFalse(list.getBoolean(1)); try { list.setBoolean(-1, false); @@ -226,8 +225,7 @@ public class BooleanArrayListTest extends TestCase { list.add(i % 2 == 0); } assertEquals( - asList(false, true, false, false, true, true, false, true, false, true, false), - list); + asList(false, true, false, false, true, true, false, true, false, true, false), list); try { list.add(-1, true); @@ -257,8 +255,8 @@ public class BooleanArrayListTest extends TestCase { assertTrue(list.addAll(Collections.singleton(true))); assertEquals(1, list.size()); - assertEquals(true, (boolean) list.get(0)); - assertEquals(true, list.getBoolean(0)); + assertTrue(list.get(0)); + assertTrue(list.getBoolean(0)); assertTrue(list.addAll(asList(false, true, false, true, false))); assertEquals(asList(true, false, true, false, true, false), list); @@ -272,7 +270,7 @@ public class BooleanArrayListTest extends TestCase { public void testRemove() { list.addAll(TERTIARY_LIST); - assertEquals(true, (boolean) list.remove(0)); + assertTrue(list.remove(0)); assertEquals(asList(false, true), list); assertTrue(list.remove(Boolean.TRUE)); @@ -281,7 +279,7 @@ public class BooleanArrayListTest extends TestCase { assertFalse(list.remove(Boolean.TRUE)); assertEquals(asList(false), list); - assertEquals(false, (boolean) list.remove(0)); + assertFalse(list.remove(0)); assertEquals(asList(), list); try { @@ -299,16 +297,14 @@ public class BooleanArrayListTest extends TestCase { } public void testRemoveEndOfCapacity() { - BooleanList toRemove = - BooleanArrayList.emptyList().mutableCopyWithCapacity(1); + BooleanList toRemove = BooleanArrayList.emptyList().mutableCopyWithCapacity(1); toRemove.addBoolean(true); toRemove.remove(0); assertEquals(0, toRemove.size()); } public void testSublistRemoveEndOfCapacity() { - BooleanList toRemove = - BooleanArrayList.emptyList().mutableCopyWithCapacity(1); + BooleanList toRemove = BooleanArrayList.emptyList().mutableCopyWithCapacity(1); toRemove.addBoolean(true); toRemove.subList(0, 1).clear(); assertEquals(0, toRemove.size()); diff --git a/java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java b/java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java index db10ee7483..654d62bc35 100644 --- a/java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java +++ b/java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java @@ -38,9 +38,9 @@ import java.io.ObjectOutputStream; import java.io.UnsupportedEncodingException; /** - * This class tests {@link BoundedByteString}, which extends {@link LiteralByteString}, - * by inheriting the tests from {@link LiteralByteStringTest}. The only method which - * is strange enough that it needs to be overridden here is {@link #testToString()}. + * This class tests {@link BoundedByteString}, which extends {@link LiteralByteString}, by + * inheriting the tests from {@link LiteralByteStringTest}. The only method which is strange enough + * that it needs to be overridden here is {@link #testToString()}. * * @author carlanton@google.com (Carl Haverl) */ @@ -63,12 +63,16 @@ public class BoundedByteStringTest extends LiteralByteStringTest { String testString = "I love unicode \u1234\u5678 characters"; ByteString unicode = ByteString.wrap(testString.getBytes(Internal.UTF_8)); ByteString chopped = unicode.substring(2, unicode.size() - 6); - assertEquals(classUnderTest + ".substring() must have the expected type", - classUnderTest, getActualClassName(chopped)); + assertEquals( + classUnderTest + ".substring() must have the expected type", + classUnderTest, + getActualClassName(chopped)); String roundTripString = chopped.toString(UTF_8); - assertEquals(classUnderTest + " unicode bytes must match", - testString.substring(2, testString.length() - 6), roundTripString); + assertEquals( + classUnderTest + " unicode bytes must match", + testString.substring(2, testString.length() - 6), + roundTripString); } @Override @@ -76,12 +80,16 @@ public class BoundedByteStringTest extends LiteralByteStringTest { String testString = "I love unicode \u1234\u5678 characters"; ByteString unicode = ByteString.wrap(testString.getBytes(Internal.UTF_8)); ByteString chopped = unicode.substring(2, unicode.size() - 6); - assertEquals(classUnderTest + ".substring() must have the expected type", - classUnderTest, getActualClassName(chopped)); + assertEquals( + classUnderTest + ".substring() must have the expected type", + classUnderTest, + getActualClassName(chopped)); String roundTripString = chopped.toString(Internal.UTF_8); - assertEquals(classUnderTest + " unicode bytes must match", - testString.substring(2, testString.length() - 6), roundTripString); + assertEquals( + classUnderTest + " unicode bytes must match", + testString.substring(2, testString.length() - 6), + roundTripString); } @Override diff --git a/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java b/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java index 6b1cfe78c1..5f0ef62028 100644 --- a/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java +++ b/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java @@ -37,9 +37,7 @@ import java.util.Arrays; import java.util.Random; import junit.framework.TestCase; -/** - * Tests for {@link ByteBufferWriter}. - */ +/** Tests for {@link ByteBufferWriter}. */ public class ByteBufferWriterTest extends TestCase { public void testHeapBuffer() throws IOException { diff --git a/java/core/src/test/java/com/google/protobuf/ByteStringTest.java b/java/core/src/test/java/com/google/protobuf/ByteStringTest.java index fc22955d06..83b343ada6 100644 --- a/java/core/src/test/java/com/google/protobuf/ByteStringTest.java +++ b/java/core/src/test/java/com/google/protobuf/ByteStringTest.java @@ -124,22 +124,24 @@ public class ByteStringTest extends TestCase { public void testSubstring_BeginIndex() { byte[] bytes = getTestBytes(); ByteString substring = ByteString.copyFrom(bytes).substring(500); - assertTrue("substring must contain the tail of the string", + assertTrue( + "substring must contain the tail of the string", isArrayRange(substring.toByteArray(), bytes, 500, bytes.length - 500)); } public void testCopyFrom_BytesOffsetSize() { byte[] bytes = getTestBytes(); ByteString byteString = ByteString.copyFrom(bytes, 500, 200); - assertTrue("copyFrom sub-range must contain the expected bytes", + assertTrue( + "copyFrom sub-range must contain the expected bytes", isArrayRange(byteString.toByteArray(), bytes, 500, 200)); } public void testCopyFrom_Bytes() { byte[] bytes = getTestBytes(); ByteString byteString = ByteString.copyFrom(bytes); - assertTrue("copyFrom must contain the expected bytes", - isArray(byteString.toByteArray(), bytes)); + assertTrue( + "copyFrom must contain the expected bytes", isArray(byteString.toByteArray(), bytes)); } public void testCopyFrom_ByteBufferSize() { @@ -148,7 +150,8 @@ public class ByteStringTest extends TestCase { byteBuffer.put(bytes); byteBuffer.position(500); ByteString byteString = ByteString.copyFrom(byteBuffer, 200); - assertTrue("copyFrom byteBuffer sub-range must contain the expected bytes", + assertTrue( + "copyFrom byteBuffer sub-range must contain the expected bytes", isArrayRange(byteString.toByteArray(), bytes, 500, 200)); } @@ -158,7 +161,8 @@ public class ByteStringTest extends TestCase { byteBuffer.put(bytes); byteBuffer.position(500); ByteString byteString = ByteString.copyFrom(byteBuffer); - assertTrue("copyFrom byteBuffer sub-range must contain the expected bytes", + assertTrue( + "copyFrom byteBuffer sub-range must contain the expected bytes", isArrayRange(byteString.toByteArray(), bytes, 500, bytes.length - 500)); } @@ -166,7 +170,8 @@ public class ByteStringTest extends TestCase { String testString = "I love unicode \u1234\u5678 characters"; ByteString byteString = ByteString.copyFrom(testString, UTF_16); byte[] testBytes = testString.getBytes(UTF_16); - assertTrue("copyFrom string must respect the charset", + assertTrue( + "copyFrom string must respect the charset", isArrayRange(byteString.toByteArray(), testBytes, 0, testBytes.length)); } @@ -174,7 +179,8 @@ public class ByteStringTest extends TestCase { String testString = "I love unicode \u1234\u5678 characters"; ByteString byteString = ByteString.copyFromUtf8(testString); byte[] testBytes = testString.getBytes(Internal.UTF_8); - assertTrue("copyFromUtf8 string must respect the charset", + assertTrue( + "copyFromUtf8 string must respect the charset", isArrayRange(byteString.toByteArray(), testBytes, 0, testBytes.length)); } @@ -183,17 +189,20 @@ public class ByteStringTest extends TestCase { final List pieces = makeConcretePieces(testBytes); // Call copyFrom() on a Collection ByteString byteString = ByteString.copyFrom(pieces); - assertTrue("copyFrom a List must contain the expected bytes", + assertTrue( + "copyFrom a List must contain the expected bytes", isArrayRange(byteString.toByteArray(), testBytes, 0, testBytes.length)); // Call copyFrom on an iteration that's not a collection - ByteString byteStringAlt = ByteString.copyFrom(new Iterable() { - @Override - public Iterator iterator() { - return pieces.iterator(); - } - }); - assertEquals("copyFrom from an Iteration must contain the expected bytes", - byteString, byteStringAlt); + ByteString byteStringAlt = + ByteString.copyFrom( + new Iterable() { + @Override + public Iterator iterator() { + return pieces.iterator(); + } + }); + assertEquals( + "copyFrom from an Iteration must contain the expected bytes", byteString, byteStringAlt); } public void testCopyFrom_LengthTooBig() { @@ -229,15 +238,17 @@ public class ByteStringTest extends TestCase { ByteString byteString = ByteString.copyFrom(bytes); byte[] target = new byte[bytes.length + 1000]; byteString.copyTo(target, 400); - assertTrue("copyFrom byteBuffer sub-range must contain the expected bytes", + assertTrue( + "copyFrom byteBuffer sub-range must contain the expected bytes", isArrayRange(bytes, target, 400, bytes.length)); } public void testReadFrom_emptyStream() throws IOException { - ByteString byteString = - ByteString.readFrom(new ByteArrayInputStream(new byte[0])); - assertSame("reading an empty stream must result in the EMPTY constant " - + "byte string", ByteString.EMPTY, byteString); + ByteString byteString = ByteString.readFrom(new ByteArrayInputStream(new byte[0])); + assertSame( + "reading an empty stream must result in the EMPTY constant byte string", + ByteString.EMPTY, + byteString); } public void testReadFrom_smallStream() throws IOException { @@ -245,18 +256,18 @@ public class ByteStringTest extends TestCase { } public void testReadFrom_mutating() throws IOException { - byte[] capturedArray = null; EvilInputStream eis = new EvilInputStream(); ByteString byteString = ByteString.readFrom(eis); + byte[] capturedArray = eis.capturedArray; - capturedArray = eis.capturedArray; byte[] originalValue = byteString.toByteArray(); for (int x = 0; x < capturedArray.length; ++x) { capturedArray[x] = (byte) 0; } byte[] newValue = byteString.toByteArray(); - assertTrue("copyFrom byteBuffer must not grant access to underlying array", + assertTrue( + "copyFrom byteBuffer must not grant access to underlying array", Arrays.equals(originalValue, newValue)); } @@ -318,8 +329,8 @@ public class ByteStringTest extends TestCase { fail("readFrom must throw the underlying IOException"); } catch (IOException e) { - assertEquals("readFrom must throw the expected exception", - "synthetic failure", e.getMessage()); + assertEquals( + "readFrom must throw the expected exception", "synthetic failure", e.getMessage()); } } @@ -329,7 +340,8 @@ public class ByteStringTest extends TestCase { final byte[] data = getTestBytes(0x1000); ByteString byteString = ByteString.readFrom(new ReluctantStream(data)); - assertTrue("readFrom byte stream must contain the expected bytes", + assertTrue( + "readFrom byte stream must contain the expected bytes", isArray(byteString.toByteArray(), data)); // Same test as above, but with some specific chunk sizes. @@ -344,11 +356,10 @@ public class ByteStringTest extends TestCase { // Fails unless ByteString.readFrom reads the bytes correctly from a // reluctant stream with the given chunkSize parameter. - private void assertReadFromReluctantStream(byte[] bytes, int chunkSize) - throws IOException { + private void assertReadFromReluctantStream(byte[] bytes, int chunkSize) throws IOException { ByteString b = ByteString.readFrom(new ReluctantStream(bytes), chunkSize); - assertTrue("readFrom byte stream must contain the expected bytes", - isArray(b.toByteArray(), bytes)); + assertTrue( + "readFrom byte stream must contain the expected bytes", isArray(b.toByteArray(), bytes)); } // Tests that ByteString.readFrom works with streams that implement @@ -357,21 +368,23 @@ public class ByteStringTest extends TestCase { final byte[] data = getTestBytes(0x1001); ByteString byteString = ByteString.readFrom(new AvailableStream(data)); - assertTrue("readFrom byte stream must contain the expected bytes", + assertTrue( + "readFrom byte stream must contain the expected bytes", isArray(byteString.toByteArray(), data)); } // Fails unless ByteString.readFrom reads the bytes correctly. private void assertReadFrom(byte[] bytes) throws IOException { - ByteString byteString = - ByteString.readFrom(new ByteArrayInputStream(bytes)); - assertTrue("readFrom byte stream must contain the expected bytes", + ByteString byteString = ByteString.readFrom(new ByteArrayInputStream(bytes)); + assertTrue( + "readFrom byte stream must contain the expected bytes", isArray(byteString.toByteArray(), bytes)); } // A stream that fails when read. private static final class FailStream extends InputStream { - @Override public int read() throws IOException { + @Override + public int read() throws IOException { throw new IOException("synthetic failure"); } } @@ -386,7 +399,8 @@ public class ByteStringTest extends TestCase { this.data = data; } - @Override public int read() { + @Override + public int read() { if (pos == data.length) { return -1; } else { @@ -394,11 +408,13 @@ public class ByteStringTest extends TestCase { } } - @Override public int read(byte[] buf) { + @Override + public int read(byte[] buf) { return read(buf, 0, buf.length); } - @Override public int read(byte[] buf, int offset, int size) { + @Override + public int read(byte[] buf, int offset, int size) { if (pos == data.length) { return -1; } @@ -415,7 +431,8 @@ public class ByteStringTest extends TestCase { super(data); } - @Override public int available() { + @Override + public int available() { return Math.min(250, data.length - pos); } } @@ -465,8 +482,8 @@ public class ByteStringTest extends TestCase { String testString = "I love unicode \u1234\u5678 characters"; byte[] testBytes = testString.getBytes(Internal.UTF_8); ByteString byteString = ByteString.copyFrom(testBytes); - assertEquals("copyToStringUtf8 must respect the charset", - testString, byteString.toStringUtf8()); + assertEquals( + "copyToStringUtf8 must respect the charset", testString, byteString.toStringUtf8()); } public void testNewOutput_InitialCapacity() throws IOException { @@ -484,8 +501,9 @@ public class ByteStringTest extends TestCase { public void testNewOutput_ArrayWrite() { byte[] bytes = getTestBytes(); int length = bytes.length; - int[] bufferSizes = {128, 256, length / 2, length - 1, length, length + 1, - 2 * length, 3 * length}; + int[] bufferSizes = { + 128, 256, length / 2, length - 1, length, length + 1, 2 * length, 3 * length + }; int[] writeSizes = {1, 4, 5, 7, 23, bytes.length}; for (int bufferSize : bufferSizes) { @@ -496,7 +514,8 @@ public class ByteStringTest extends TestCase { output.write(bytes, i, Math.min(writeSize, length - i)); } ByteString byteString = output.toByteString(); - assertTrue("String built from newOutput() must contain the expected bytes", + assertTrue( + "String built from newOutput() must contain the expected bytes", isArrayRange(bytes, byteString.toByteArray(), 0, bytes.length)); } } @@ -507,16 +526,17 @@ public class ByteStringTest extends TestCase { public void testNewOutput_WriteChar() { byte[] bytes = getTestBytes(); int length = bytes.length; - int[] bufferSizes = {0, 1, 128, 256, length / 2, - length - 1, length, length + 1, - 2 * length, 3 * length}; + int[] bufferSizes = { + 0, 1, 128, 256, length / 2, length - 1, length, length + 1, 2 * length, 3 * length + }; for (int bufferSize : bufferSizes) { ByteString.Output output = ByteString.newOutput(bufferSize); for (byte byteValue : bytes) { output.write(byteValue); } ByteString byteString = output.toByteString(); - assertTrue("String built from newOutput() must contain the expected bytes", + assertTrue( + "String built from newOutput() must contain the expected bytes", isArrayRange(bytes, byteString.toByteArray(), 0, bytes.length)); } } @@ -527,9 +547,9 @@ public class ByteStringTest extends TestCase { Random rng = new Random(1); byte[] bytes = getTestBytes(); int length = bytes.length; - int[] bufferSizes = {0, 1, 128, 256, length / 2, - length - 1, length, length + 1, - 2 * length, 3 * length}; + int[] bufferSizes = { + 0, 1, 128, 256, length / 2, length - 1, length, length + 1, 2 * length, 3 * length + }; for (int bufferSize : bufferSizes) { // Test writing the entire output using a mixture of write sizes and @@ -546,12 +566,13 @@ public class ByteStringTest extends TestCase { position++; } assertEquals("size() returns the right value", position, output.size()); - assertTrue("newOutput() substring must have correct bytes", - isArrayRange(output.toByteString().toByteArray(), - bytes, 0, position)); + assertTrue( + "newOutput() substring must have correct bytes", + isArrayRange(output.toByteString().toByteArray(), bytes, 0, position)); } ByteString byteString = output.toByteString(); - assertTrue("String built from newOutput() must contain the expected bytes", + assertTrue( + "String built from newOutput() must contain the expected bytes", isArrayRange(bytes, byteString.toByteArray(), 0, bytes.length)); } } @@ -572,7 +593,8 @@ public class ByteStringTest extends TestCase { byte[] oldValue = byteString.toByteArray(); Arrays.fill(capturedArray, (byte) 0); byte[] newValue = byteString.toByteArray(); - assertTrue("Output must not provide access to the underlying byte array", + assertTrue( + "Output must not provide access to the underlying byte array", Arrays.equals(oldValue, newValue)); } @@ -581,14 +603,15 @@ public class ByteStringTest extends TestCase { ByteString.CodedBuilder builder = ByteString.newCodedBuilder(bytes.length); builder.getCodedOutput().writeRawBytes(bytes); ByteString byteString = builder.build(); - assertTrue("String built from newCodedBuilder() must contain the expected bytes", + assertTrue( + "String built from newCodedBuilder() must contain the expected bytes", isArrayRange(bytes, byteString.toByteArray(), 0, bytes.length)); } public void testSubstringParity() { byte[] bigBytes = getTestBytes(2048 * 1024, 113344L); int start = 512 * 1024 - 3333; - int end = 512 * 1024 + 7777; + int end = 512 * 1024 + 7777; ByteString concreteSubstring = ByteString.copyFrom(bigBytes).substring(start, end); boolean ok = true; for (int i = start; ok && i < end; ++i) { @@ -597,10 +620,11 @@ public class ByteStringTest extends TestCase { assertTrue("Concrete substring didn't capture the right bytes", ok); ByteString literalString = ByteString.copyFrom(bigBytes, start, end - start); - assertTrue("Substring must be equal to literal string", - concreteSubstring.equals(literalString)); - assertEquals("Substring must have same hashcode as literal string", - literalString.hashCode(), concreteSubstring.hashCode()); + assertEquals("Substring must be equal to literal string", literalString, concreteSubstring); + assertEquals( + "Substring must have same hashcode as literal string", + literalString.hashCode(), + concreteSubstring.hashCode()); } public void testCompositeSubstring() { @@ -626,15 +650,22 @@ public class ByteStringTest extends TestCase { assertTrue("Substring must support byteAt() correctly", stillEqual); ByteString literalSubstring = ByteString.copyFrom(referenceBytes, from, to - from); - assertTrue("Composite substring must equal a literal substring over the same bytes", - compositeSubstring.equals(literalSubstring)); - assertTrue("Literal substring must equal a composite substring over the same bytes", - literalSubstring.equals(compositeSubstring)); + assertEquals( + "Composite substring must equal a literal substring over the same bytes", + literalSubstring, + compositeSubstring); + assertEquals( + "Literal substring must equal a composite substring over the same bytes", + compositeSubstring, + literalSubstring); - assertEquals("We must get the same hashcodes for composite and literal substrings", - literalSubstring.hashCode(), compositeSubstring.hashCode()); + assertEquals( + "We must get the same hashcodes for composite and literal substrings", + literalSubstring.hashCode(), + compositeSubstring.hashCode()); - assertFalse("We can't be equal to a proper substring", + assertFalse( + "We can't be equal to a proper substring", compositeSubstring.equals(literalSubstring.substring(0, literalSubstring.size() - 1))); } @@ -645,10 +676,11 @@ public class ByteStringTest extends TestCase { List pieces = makeConcretePieces(referenceBytes); ByteString listString = ByteString.copyFrom(pieces); - assertTrue("Composite string must be equal to literal string", - listString.equals(literalString)); - assertEquals("Composite string must have same hashcode as literal string", - literalString.hashCode(), listString.hashCode()); + assertEquals("Composite string must be equal to literal string", literalString, listString); + assertEquals( + "Composite string must have same hashcode as literal string", + literalString.hashCode(), + listString.hashCode()); } public void testConcat() { @@ -663,30 +695,34 @@ public class ByteStringTest extends TestCase { concatenatedString = concatenatedString.concat(iter.next()); } - assertTrue("Concatenated string must be equal to literal string", - concatenatedString.equals(literalString)); - assertEquals("Concatenated string must have same hashcode as literal string", - literalString.hashCode(), concatenatedString.hashCode()); + assertEquals( + "Concatenated string must be equal to literal string", literalString, concatenatedString); + assertEquals( + "Concatenated string must have same hashcode as literal string", + literalString.hashCode(), + concatenatedString.hashCode()); } /** - * Test the Rope implementation can deal with Empty nodes, even though we - * guard against them. See also {@link LiteralByteStringTest#testConcat_empty()}. + * Test the Rope implementation can deal with Empty nodes, even though we guard against them. See + * also {@link LiteralByteStringTest#testConcat_empty()}. */ public void testConcat_empty() { byte[] referenceBytes = getTestBytes(7748, 113344L); ByteString literalString = ByteString.copyFrom(referenceBytes); ByteString duo = RopeByteString.newInstanceForTest(literalString, literalString); - ByteString temp = RopeByteString.newInstanceForTest( - RopeByteString.newInstanceForTest(literalString, ByteString.EMPTY), - RopeByteString.newInstanceForTest(ByteString.EMPTY, literalString)); + ByteString temp = + RopeByteString.newInstanceForTest( + RopeByteString.newInstanceForTest(literalString, ByteString.EMPTY), + RopeByteString.newInstanceForTest(ByteString.EMPTY, literalString)); ByteString quintet = RopeByteString.newInstanceForTest(temp, ByteString.EMPTY); - assertTrue("String with concatenated nulls must equal simple concatenate", - duo.equals(quintet)); - assertEquals("String with concatenated nulls have same hashcode as simple concatenate", - duo.hashCode(), quintet.hashCode()); + assertEquals("String with concatenated nulls must equal simple concatenate", quintet, duo); + assertEquals( + "String with concatenated nulls have same hashcode as simple concatenate", + duo.hashCode(), + quintet.hashCode()); ByteString.ByteIterator duoIter = duo.iterator(); ByteString.ByteIterator quintetIter = quintet.iterator(); @@ -716,11 +752,13 @@ public class ByteStringTest extends TestCase { // It is possible, using the testing factory method to create deeply nested // trees of empty leaves, to make a string that will fail this test. for (int i = 1; i < duo.size(); ++i) { - assertTrue("Substrings of size() < 2 must not be RopeByteStrings", + assertTrue( + "Substrings of size() < 2 must not be RopeByteStrings", duo.substring(i - 1, i) instanceof ByteString.LeafByteString); } for (int i = 1; i < quintet.size(); ++i) { - assertTrue("Substrings of size() < 2 must not be RopeByteStrings", + assertTrue( + "Substrings of size() < 2 must not be RopeByteStrings", quintet.substring(i - 1, i) instanceof ByteString.LeafByteString); } } @@ -769,8 +807,7 @@ public class ByteStringTest extends TestCase { return pieces; } - private byte[] substringUsingWriteTo( - ByteString data, int offset, int length) throws IOException { + private byte[] substringUsingWriteTo(ByteString data, int offset, int length) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); data.writeTo(output, offset, length); return output.toByteArray(); @@ -781,9 +818,7 @@ public class ByteStringTest extends TestCase { // won't be merged into one byte array due to some optimizations. final int dataSize = ByteString.CONCATENATE_BY_COPY_SIZE + 1; byte[] data1 = new byte[dataSize]; - for (int i = 0; i < data1.length; i++) { - data1[i] = (byte) 1; - } + Arrays.fill(data1, (byte) 1); data1[1] = (byte) 11; // Test LiteralByteString.writeTo(OutputStream,int,int) ByteString left = ByteString.wrap(data1); @@ -792,9 +827,7 @@ public class ByteStringTest extends TestCase { assertEquals((byte) 11, result[0]); byte[] data2 = new byte[dataSize]; - for (int i = 0; i < data1.length; i++) { - data2[i] = (byte) 2; - } + Arrays.fill(data2, 0, data1.length, (byte) 2); ByteString right = ByteString.wrap(data2); // Concatenate two ByteStrings to create a RopeByteString. ByteString root = left.concat(right); @@ -819,10 +852,8 @@ public class ByteStringTest extends TestCase { assertEquals((byte) 2, result[dataSize - dataSize / 2]); assertEquals((byte) 2, result[dataSize - 1]); } - - /** - * Tests ByteString uses Arrays based byte copier when running under Hotstop VM. - */ + + /** Tests ByteString uses Arrays based byte copier when running under Hotstop VM. */ public void testByteArrayCopier() throws Exception { if (Android.isOnAndroidDevice()) { return; diff --git a/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java b/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java index 50b87ae31f..e276225e7a 100644 --- a/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java +++ b/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java @@ -38,22 +38,21 @@ import java.io.ByteArrayInputStream; import junit.framework.TestCase; /** - * Test that protos generated with file option java_string_check_utf8 do in - * fact perform appropriate UTF-8 checks. + * Test that protos generated with file option java_string_check_utf8 do in fact perform appropriate + * UTF-8 checks. * * @author jbaum@google.com (Jacob Butcher) */ public class CheckUtf8Test extends TestCase { private static final String UTF8_BYTE_STRING_TEXT = "some text"; - private static final ByteString UTF8_BYTE_STRING = - ByteString.copyFromUtf8(UTF8_BYTE_STRING_TEXT); + private static final ByteString UTF8_BYTE_STRING = ByteString.copyFromUtf8(UTF8_BYTE_STRING_TEXT); private static final ByteString NON_UTF8_BYTE_STRING = - ByteString.copyFrom(new byte[]{(byte) 0x80}); // A lone continuation byte. + ByteString.copyFrom(new byte[] {(byte) 0x80}); // A lone continuation byte. public void testBuildRequiredStringWithGoodUtf8() throws Exception { - assertEquals(UTF8_BYTE_STRING_TEXT, - StringWrapper.newBuilder().setReqBytes(UTF8_BYTE_STRING).getReq()); + assertEquals( + UTF8_BYTE_STRING_TEXT, StringWrapper.newBuilder().setReqBytes(UTF8_BYTE_STRING).getReq()); } public void testParseRequiredStringWithGoodUtf8() throws Exception { diff --git a/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java b/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java index 5ea6b79c79..f64df334d1 100644 --- a/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java +++ b/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java @@ -699,7 +699,7 @@ public class CodedInputStreamTest extends TestCase { } assertEquals(true, input.isAtEnd()); } catch (Exception e) { - fail("Catch exception in the testIsAtEnd"); + throw new AssertionError("Catch exception in the testIsAtEnd", e); } } diff --git a/java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java b/java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java index dca69cd543..8dc3e4ce7a 100644 --- a/java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java +++ b/java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java @@ -257,13 +257,27 @@ public class CodedOutputStreamTest extends TestCase { // 41256202580718336 assertWriteVarint( bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49), - (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | (0x43L << 28) | (0x49L << 35) - | (0x24L << 42) | (0x49L << 49)); + (0x00 << 0) + | (0x66 << 7) + | (0x6b << 14) + | (0x1c << 21) + | (0x43L << 28) + | (0x49L << 35) + | (0x24L << 42) + | (0x49L << 49)); // 11964378330978735131 assertWriteVarint( bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01), - (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | (0x3bL << 28) | (0x56L << 35) - | (0x00L << 42) | (0x05L << 49) | (0x26L << 56) | (0x01L << 63)); + (0x1b << 0) + | (0x28 << 7) + | (0x79 << 14) + | (0x42 << 21) + | (0x3bL << 28) + | (0x56L << 35) + | (0x00L << 42) + | (0x05L << 49) + | (0x26L << 56) + | (0x01L << 63)); } /** Tests writeRawLittleEndian32() and writeRawLittleEndian64(). */ @@ -344,8 +358,8 @@ public class CodedOutputStreamTest extends TestCase { } /** - * Tests writing a whole message with every packed field type. Ensures the - * wire format of packed fields is compatible with C++. + * Tests writing a whole message with every packed field type. Ensures the wire format of packed + * fields is compatible with C++. */ public void testWriteWholePackedFieldsMessage() throws Exception { byte[] expectedBytes = TestUtil.getGoldenPackedFieldsMessage().toByteArray(); @@ -361,8 +375,8 @@ public class CodedOutputStreamTest extends TestCase { } /** - * Test writing a message containing a negative enum value. This used to - * fail because the size was not properly computed as a sign-extended varint. + * Test writing a message containing a negative enum value. This used to fail because the size was + * not properly computed as a sign-extended varint. */ public void testWriteMessageWithNegativeEnumValue() throws Exception { SparseEnumMessage message = @@ -394,8 +408,9 @@ public class CodedOutputStreamTest extends TestCase { String string = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"; // Ensure we take the slower fast path. - assertTrue(CodedOutputStream.computeUInt32SizeNoTag(string.length()) - != CodedOutputStream.computeUInt32SizeNoTag(string.length() * Utf8.MAX_BYTES_PER_CHAR)); + assertTrue( + CodedOutputStream.computeUInt32SizeNoTag(string.length()) + != CodedOutputStream.computeUInt32SizeNoTag(string.length() * Utf8.MAX_BYTES_PER_CHAR)); coder.stream().writeStringNoTag(string); coder.stream().flush(); @@ -438,9 +453,7 @@ public class CodedOutputStreamTest extends TestCase { } final int length2 = 8 * 1024; byte[] data = new byte[length2]; - for (int i = 0; i < length2; i++) { - data[i] = (byte) 2; - } + Arrays.fill(data, 0, length2, (byte) 2); codedStream.writeRawBytes(data); final int length3 = bufferSize - length1 - length2; for (int i = 0; i < length3; i++) { @@ -521,10 +534,14 @@ public class CodedOutputStreamTest extends TestCase { } public void testSerializeInvalidUtf8() throws Exception { - String[] invalidStrings = new String[] {newString(Character.MIN_HIGH_SURROGATE), - "foobar" + newString(Character.MIN_HIGH_SURROGATE), newString(Character.MIN_LOW_SURROGATE), - "foobar" + newString(Character.MIN_LOW_SURROGATE), - newString(Character.MIN_HIGH_SURROGATE, Character.MIN_HIGH_SURROGATE)}; + String[] invalidStrings = + new String[] { + newString(Character.MIN_HIGH_SURROGATE), + "foobar" + newString(Character.MIN_HIGH_SURROGATE), + newString(Character.MIN_LOW_SURROGATE), + "foobar" + newString(Character.MIN_LOW_SURROGATE), + newString(Character.MIN_HIGH_SURROGATE, Character.MIN_HIGH_SURROGATE) + }; CodedOutputStream outputWithStream = CodedOutputStream.newInstance(new ByteArrayOutputStream()); CodedOutputStream outputWithArray = CodedOutputStream.newInstance(new byte[10000]); @@ -594,16 +611,17 @@ public class CodedOutputStreamTest extends TestCase { // with ASCII and Unicode characters requiring different UTF-8 byte counts per // char, hence causing the length delimiter varint to sometimes require more // bytes for the Unicode strings than the ASCII string of the same length. - int[] lengths = new int[] { - 0, - 1, - (1 << 4) - 1, // 1 byte for ASCII and Unicode - (1 << 7) - 1, // 1 byte for ASCII, 2 bytes for Unicode - (1 << 11) - 1, // 2 bytes for ASCII and Unicode - (1 << 14) - 1, // 2 bytes for ASCII, 3 bytes for Unicode - (1 << 17) - 1, - // 3 bytes for ASCII and Unicode - }; + int[] lengths = + new int[] { + 0, + 1, + (1 << 4) - 1, // 1 byte for ASCII and Unicode + (1 << 7) - 1, // 1 byte for ASCII, 2 bytes for Unicode + (1 << 11) - 1, // 2 bytes for ASCII and Unicode + (1 << 14) - 1, // 2 bytes for ASCII, 3 bytes for Unicode + (1 << 17) - 1, + // 3 bytes for ASCII and Unicode + }; for (OutputType outputType : OutputType.values()) { for (int i : lengths) { testEncodingOfString(outputType, 'q', i); // 1 byte per char @@ -626,8 +644,8 @@ public class CodedOutputStreamTest extends TestCase { } /** - * Parses the given bytes using writeRawLittleEndian32() and checks - * that the result matches the given value. + * Parses the given bytes using writeRawLittleEndian32() and checks that the result matches the + * given value. */ private static void assertWriteLittleEndian32(byte[] data, int value) throws Exception { for (OutputType outputType : OutputType.values()) { @@ -647,8 +665,8 @@ public class CodedOutputStreamTest extends TestCase { } /** - * Parses the given bytes using writeRawLittleEndian64() and checks - * that the result matches the given value. + * Parses the given bytes using writeRawLittleEndian64() and checks that the result matches the + * given value. */ private static void assertWriteLittleEndian64(byte[] data, long value) throws Exception { for (OutputType outputType : OutputType.values()) { @@ -691,9 +709,8 @@ public class CodedOutputStreamTest extends TestCase { } /** - * Helper to construct a byte array from a bunch of bytes. The inputs are - * actually ints so that I can use hex notation and not get stupid errors - * about precision. + * Helper to construct a byte array from a bunch of bytes. The inputs are actually ints so that I + * can use hex notation and not get stupid errors about precision. */ private static byte[] bytes(int... bytesAsInts) { byte[] bytes = new byte[bytesAsInts.length]; @@ -703,7 +720,7 @@ public class CodedOutputStreamTest extends TestCase { return bytes; } - /** Arrays.asList() does not work with arrays of primitives. :( */ + /** Arrays.asList() does not work with arrays of primitives. :( */ private static List toList(byte[] bytes) { List result = new ArrayList(); for (byte b : bytes) { @@ -717,8 +734,8 @@ public class CodedOutputStreamTest extends TestCase { } /** - * Writes the given value using writeRawVarint32() and writeRawVarint64() and - * checks that the result matches the given bytes. + * Writes the given value using writeRawVarint32() and writeRawVarint64() and checks that the + * result matches the given bytes. */ private static void assertWriteVarint(byte[] data, long value) throws Exception { for (OutputType outputType : OutputType.values()) { diff --git a/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java b/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java index 9c0997c49b..2addde8428 100644 --- a/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java +++ b/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java @@ -41,35 +41,28 @@ import junit.framework.TestCase; * @author birdo@google.com (Roberto Scaramuzzi) */ public class DeprecatedFieldTest extends TestCase { - private String[] deprecatedGetterNames = { - "hasDeprecatedInt32", - "getDeprecatedInt32"}; + private String[] deprecatedGetterNames = {"hasDeprecatedInt32", "getDeprecatedInt32"}; private String[] deprecatedBuilderGetterNames = { - "hasDeprecatedInt32", - "getDeprecatedInt32", - "clearDeprecatedInt32"}; + "hasDeprecatedInt32", "getDeprecatedInt32", "clearDeprecatedInt32" + }; - private String[] deprecatedBuilderSetterNames = { - "setDeprecatedInt32"}; + private String[] deprecatedBuilderSetterNames = {"setDeprecatedInt32"}; public void testDeprecatedField() throws Exception { Class deprecatedFields = TestDeprecatedFields.class; Class deprecatedFieldsBuilder = TestDeprecatedFields.Builder.class; for (String name : deprecatedGetterNames) { Method method = deprecatedFields.getMethod(name); - assertTrue("Method " + name + " should be deprecated", - isDeprecated(method)); + assertTrue("Method " + name + " should be deprecated", isDeprecated(method)); } for (String name : deprecatedBuilderGetterNames) { Method method = deprecatedFieldsBuilder.getMethod(name); - assertTrue("Method " + name + " should be deprecated", - isDeprecated(method)); + assertTrue("Method " + name + " should be deprecated", isDeprecated(method)); } for (String name : deprecatedBuilderSetterNames) { Method method = deprecatedFieldsBuilder.getMethod(name, int.class); - assertTrue("Method " + name + " should be deprecated", - isDeprecated(method)); + assertTrue("Method " + name + " should be deprecated", isDeprecated(method)); } } @@ -77,8 +70,7 @@ public class DeprecatedFieldTest extends TestCase { Class oneofCase = TestDeprecatedFields.OneofFieldsCase.class; String name = "DEPRECATED_INT32_IN_ONEOF"; java.lang.reflect.Field enumValue = oneofCase.getField(name); - assertTrue("Enum value " + name + " should be deprecated.", - isDeprecated(enumValue)); + assertTrue("Enum value " + name + " should be deprecated.", isDeprecated(enumValue)); } private boolean isDeprecated(AnnotatedElement annotated) { diff --git a/java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java b/java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java index 36c4611fd5..01a96ba550 100644 --- a/java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java +++ b/java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java @@ -43,15 +43,13 @@ import org.junit.runners.JUnit4; public class DiscardUnknownFieldsTest { @Test public void testProto2() throws Exception { + testProto2Message(UnittestProto.TestEmptyMessage.getDefaultInstance()); + testProto2Message(UnittestProto.TestEmptyMessageWithExtensions.getDefaultInstance()); testProto2Message( - UnittestProto.TestEmptyMessage.getDefaultInstance()); + DynamicMessage.getDefaultInstance(UnittestProto.TestEmptyMessage.getDescriptor())); testProto2Message( - UnittestProto.TestEmptyMessageWithExtensions.getDefaultInstance()); - testProto2Message( - DynamicMessage.getDefaultInstance(UnittestProto.TestEmptyMessage.getDescriptor())); - testProto2Message( - DynamicMessage.getDefaultInstance( - UnittestProto.TestEmptyMessageWithExtensions.getDescriptor())); + DynamicMessage.getDefaultInstance( + UnittestProto.TestEmptyMessageWithExtensions.getDescriptor())); } @Test @@ -81,18 +79,16 @@ public class DiscardUnknownFieldsTest { payload.copyTo(copied, 0); payload.copyTo(copied, messageSize); CodedInputStream input = CodedInputStream.newInstance(copied); - { - // Use DiscardUnknownFieldsParser to parse the first payload. - int oldLimit = input.pushLimit(messageSize); - Message parsed = DiscardUnknownFieldsParser.wrap(message.getParserForType()).parseFrom(input); - assertEquals(message.getClass().getName(), 0, parsed.getSerializedSize()); - input.popLimit(oldLimit); - } - { - // Use the normal parser to parse the remaining payload should have unknown fields preserved. - Message parsed = message.getParserForType().parseFrom(input); - assertEquals(message.getClass().getName(), payload, parsed.toByteString()); - } + + // Use DiscardUnknownFieldsParser to parse the first payload. + int oldLimit = input.pushLimit(messageSize); + Message parsed = DiscardUnknownFieldsParser.wrap(message.getParserForType()).parseFrom(input); + assertEquals(message.getClass().getName(), 0, parsed.getSerializedSize()); + input.popLimit(oldLimit); + + // Use the normal parser to parse the remaining payload should have unknown fields preserved. + parsed = message.getParserForType().parseFrom(input); + assertEquals(message.getClass().getName(), payload, parsed.toByteString()); } /** @@ -104,34 +100,18 @@ public class DiscardUnknownFieldsTest { UnknownFieldSet unknownFields = UnknownFieldSet.newBuilder().mergeFrom(payload).build(); Message built = message.newBuilderForType().setUnknownFields(unknownFields).build(); assertEquals(message.getClass().getName(), payload, built.toByteString()); - - } - /** - * {@link Message.Builder#setUnknownFields(UnknownFieldSet)} and {@link - * Message.Builder#mergeUnknownFields(UnknownFieldSet)} should discard the unknown fields. - */ - private static void assertUnknownFieldsInUnknownFieldSetAreDiscarded(Message message) - throws Exception { - UnknownFieldSet unknownFields = UnknownFieldSet.newBuilder().mergeFrom(payload).build(); - Message built = message.newBuilderForType().setUnknownFields(unknownFields).build(); - assertEquals(message.getClass().getName(), 0, built.getSerializedSize()); } private static void assertUnknownFieldsPreserved(MessageLite message) throws Exception { - { - MessageLite parsed = message.getParserForType().parseFrom(payload); - assertEquals(message.getClass().getName(), payload, parsed.toByteString()); - } + MessageLite parsed = message.getParserForType().parseFrom(payload); + assertEquals(message.getClass().getName(), payload, parsed.toByteString()); - { - MessageLite parsed = message.newBuilderForType().mergeFrom(payload).build(); - assertEquals(message.getClass().getName(), payload, parsed.toByteString()); - } + parsed = message.newBuilderForType().mergeFrom(payload).build(); + assertEquals(message.getClass().getName(), payload, parsed.toByteString()); } private static void assertUnknownFieldsExplicitlyDiscarded(Message message) throws Exception { - Message parsed = - DiscardUnknownFieldsParser.wrap(message.getParserForType()).parseFrom(payload); + Message parsed = DiscardUnknownFieldsParser.wrap(message.getParserForType()).parseFrom(payload); assertEquals(message.getClass().getName(), 0, parsed.getSerializedSize()); } diff --git a/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java b/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java index a4c2f5aa89..6a9421212d 100644 --- a/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java +++ b/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java @@ -45,10 +45,8 @@ import junit.framework.TestCase; */ public class DoubleArrayListTest extends TestCase { - private static final DoubleArrayList UNARY_LIST = - newImmutableDoubleArrayList(1); - private static final DoubleArrayList TERTIARY_LIST = - newImmutableDoubleArrayList(1, 2, 3); + private static final DoubleArrayList UNARY_LIST = newImmutableDoubleArrayList(1); + private static final DoubleArrayList TERTIARY_LIST = newImmutableDoubleArrayList(1, 2, 3); private DoubleArrayList list; @@ -225,9 +223,7 @@ public class DoubleArrayListTest extends TestCase { for (int i = 0; i < 6; i++) { list.add(Double.valueOf(5 + i)); } - assertEquals( - asList(0D, 1D, 4D, 2D, 3D, 5D, 6D, 7D, 8D, 9D, 10D), - list); + assertEquals(asList(0D, 1D, 4D, 2D, 3D, 5D, 6D, 7D, 8D, 9D, 10D), list); try { list.add(-1, 5D); @@ -299,16 +295,14 @@ public class DoubleArrayListTest extends TestCase { } public void testRemoveEndOfCapacity() { - DoubleList toRemove = - DoubleArrayList.emptyList().mutableCopyWithCapacity(1); + DoubleList toRemove = DoubleArrayList.emptyList().mutableCopyWithCapacity(1); toRemove.addDouble(3); toRemove.remove(0); assertEquals(0, toRemove.size()); } public void testSublistRemoveEndOfCapacity() { - DoubleList toRemove = - DoubleArrayList.emptyList().mutableCopyWithCapacity(1); + DoubleList toRemove = DoubleArrayList.emptyList().mutableCopyWithCapacity(1); toRemove.addDouble(3); toRemove.subList(0, 1).clear(); assertEquals(0, toRemove.size()); diff --git a/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java b/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java index 346c1e6a72..0514241a67 100644 --- a/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java +++ b/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java @@ -41,32 +41,30 @@ import java.util.Arrays; import junit.framework.TestCase; /** - * Unit test for {@link DynamicMessage}. See also {@link MessageTest}, which - * tests some {@link DynamicMessage} functionality. + * Unit test for {@link DynamicMessage}. See also {@link MessageTest}, which tests some {@link + * DynamicMessage} functionality. * * @author kenton@google.com Kenton Varda */ public class DynamicMessageTest extends TestCase { TestUtil.ReflectionTester reflectionTester = - new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null); + new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null); TestUtil.ReflectionTester extensionsReflectionTester = new TestUtil.ReflectionTester( TestAllExtensions.getDescriptor(), TestUtil.getFullExtensionRegistry()); TestUtil.ReflectionTester packedReflectionTester = - new TestUtil.ReflectionTester(TestPackedTypes.getDescriptor(), null); + new TestUtil.ReflectionTester(TestPackedTypes.getDescriptor(), null); public void testDynamicMessageAccessors() throws Exception { - Message.Builder builder = - DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); + Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); reflectionTester.setAllFieldsViaReflection(builder); Message message = builder.build(); reflectionTester.assertAllFieldsSetViaReflection(message); } public void testSettersAfterBuild() throws Exception { - Message.Builder builder = - DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); + Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); Message firstMessage = builder.build(); // double build() builder.build(); @@ -85,12 +83,12 @@ public class DynamicMessageTest extends TestCase { } public void testUnknownFields() throws Exception { - Message.Builder builder = - DynamicMessage.newBuilder(TestEmptyMessage.getDescriptor()); - builder.setUnknownFields(UnknownFieldSet.newBuilder() - .addField(1, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) - .addField(2, UnknownFieldSet.Field.newBuilder().addFixed32(1).build()) - .build()); + Message.Builder builder = DynamicMessage.newBuilder(TestEmptyMessage.getDescriptor()); + builder.setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(1, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .addField(2, UnknownFieldSet.Field.newBuilder().addFixed32(1).build()) + .build()); Message message = builder.build(); assertEquals(2, message.getUnknownFields().asMap().size()); // clone() with unknown fields @@ -105,8 +103,7 @@ public class DynamicMessageTest extends TestCase { } public void testDynamicMessageSettersRejectNull() throws Exception { - Message.Builder builder = - DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); + Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); reflectionTester.assertReflectionSettersRejectNull(builder); } @@ -114,22 +111,19 @@ public class DynamicMessageTest extends TestCase { // We don't need to extensively test DynamicMessage's handling of // extensions because, frankly, it doesn't do anything special with them. // It treats them just like any other fields. - Message.Builder builder = - DynamicMessage.newBuilder(TestAllExtensions.getDescriptor()); + Message.Builder builder = DynamicMessage.newBuilder(TestAllExtensions.getDescriptor()); extensionsReflectionTester.setAllFieldsViaReflection(builder); Message message = builder.build(); extensionsReflectionTester.assertAllFieldsSetViaReflection(message); } public void testDynamicMessageExtensionSettersRejectNull() throws Exception { - Message.Builder builder = - DynamicMessage.newBuilder(TestAllExtensions.getDescriptor()); + Message.Builder builder = DynamicMessage.newBuilder(TestAllExtensions.getDescriptor()); extensionsReflectionTester.assertReflectionSettersRejectNull(builder); } public void testDynamicMessageRepeatedSetters() throws Exception { - Message.Builder builder = - DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); + Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); reflectionTester.setAllFieldsViaReflection(builder); reflectionTester.modifyRepeatedFieldsViaReflection(builder); Message message = builder.build(); @@ -137,33 +131,29 @@ public class DynamicMessageTest extends TestCase { } public void testDynamicMessageRepeatedSettersRejectNull() throws Exception { - Message.Builder builder = - DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); + Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); reflectionTester.assertReflectionRepeatedSettersRejectNull(builder); } public void testDynamicMessageDefaults() throws Exception { reflectionTester.assertClearViaReflection( - DynamicMessage.getDefaultInstance(TestAllTypes.getDescriptor())); + DynamicMessage.getDefaultInstance(TestAllTypes.getDescriptor())); reflectionTester.assertClearViaReflection( - DynamicMessage.newBuilder(TestAllTypes.getDescriptor()).build()); + DynamicMessage.newBuilder(TestAllTypes.getDescriptor()).build()); } public void testDynamicMessageSerializedSize() throws Exception { TestAllTypes message = TestUtil.getAllSet(); - Message.Builder dynamicBuilder = - DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); + Message.Builder dynamicBuilder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); reflectionTester.setAllFieldsViaReflection(dynamicBuilder); Message dynamicMessage = dynamicBuilder.build(); - assertEquals(message.getSerializedSize(), - dynamicMessage.getSerializedSize()); + assertEquals(message.getSerializedSize(), dynamicMessage.getSerializedSize()); } public void testDynamicMessageSerialization() throws Exception { - Message.Builder builder = - DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); + Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); reflectionTester.setAllFieldsViaReflection(builder); Message message = builder.build(); @@ -183,8 +173,7 @@ public class DynamicMessageTest extends TestCase { ByteString rawBytes = message.toByteString(); - Message message2 = - DynamicMessage.parseFrom(TestAllTypes.getDescriptor(), rawBytes); + Message message2 = DynamicMessage.parseFrom(TestAllTypes.getDescriptor(), rawBytes); reflectionTester.assertAllFieldsSetViaReflection(message2); // Test Parser interface. @@ -200,14 +189,13 @@ public class DynamicMessageTest extends TestCase { extensionsReflectionTester.assertAllFieldsSetViaReflection(message); // Test Parser interface. - Message message2 = message.getParserForType().parseFrom( - rawBytes, TestUtil.getExtensionRegistry()); + Message message2 = + message.getParserForType().parseFrom(rawBytes, TestUtil.getExtensionRegistry()); extensionsReflectionTester.assertAllFieldsSetViaReflection(message2); } public void testDynamicMessagePackedSerialization() throws Exception { - Message.Builder builder = - DynamicMessage.newBuilder(TestPackedTypes.getDescriptor()); + Message.Builder builder = DynamicMessage.newBuilder(TestPackedTypes.getDescriptor()); packedReflectionTester.setPackedFieldsViaReflection(builder); Message message = builder.build(); @@ -227,8 +215,7 @@ public class DynamicMessageTest extends TestCase { ByteString rawBytes = message.toByteString(); - Message message2 = - DynamicMessage.parseFrom(TestPackedTypes.getDescriptor(), rawBytes); + Message message2 = DynamicMessage.parseFrom(TestPackedTypes.getDescriptor(), rawBytes); packedReflectionTester.assertPackedFieldsSetViaReflection(message2); // Test Parser interface. @@ -245,41 +232,38 @@ public class DynamicMessageTest extends TestCase { reflectionTester.assertAllFieldsSetViaReflection(copy); // Test oneof behavior - FieldDescriptor bytesField = - TestAllTypes.getDescriptor().findFieldByName("oneof_bytes"); - FieldDescriptor uint32Field = - TestAllTypes.getDescriptor().findFieldByName("oneof_uint32"); + FieldDescriptor bytesField = TestAllTypes.getDescriptor().findFieldByName("oneof_bytes"); + FieldDescriptor uint32Field = TestAllTypes.getDescriptor().findFieldByName("oneof_uint32"); assertTrue(copy.hasField(bytesField)); assertFalse(copy.hasField(uint32Field)); - DynamicMessage copy2 = - DynamicMessage.newBuilder(message).setField(uint32Field, 123).build(); + DynamicMessage copy2 = DynamicMessage.newBuilder(message).setField(uint32Field, 123).build(); assertFalse(copy2.hasField(bytesField)); assertTrue(copy2.hasField(uint32Field)); assertEquals(123, copy2.getField(uint32Field)); } public void testToBuilder() throws Exception { - DynamicMessage.Builder builder = - DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); + DynamicMessage.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); reflectionTester.setAllFieldsViaReflection(builder); int unknownFieldNum = 9; long unknownFieldVal = 90; - builder.setUnknownFields(UnknownFieldSet.newBuilder() - .addField(unknownFieldNum, - UnknownFieldSet.Field.newBuilder() - .addVarint(unknownFieldVal).build()) - .build()); + builder.setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + unknownFieldNum, + UnknownFieldSet.Field.newBuilder().addVarint(unknownFieldVal).build()) + .build()); DynamicMessage message = builder.build(); DynamicMessage derived = message.toBuilder().build(); reflectionTester.assertAllFieldsSetViaReflection(derived); - assertEquals(Arrays.asList(unknownFieldVal), + assertEquals( + Arrays.asList(unknownFieldVal), derived.getUnknownFields().getField(unknownFieldNum).getVarintList()); } public void testDynamicOneofMessage() throws Exception { - DynamicMessage.Builder builder = - DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); + DynamicMessage.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); OneofDescriptor oneof = TestAllTypes.getDescriptor().getOneofs().get(0); assertFalse(builder.hasOneof(oneof)); assertSame(null, builder.getOneofFieldDescriptor(oneof)); @@ -292,8 +276,7 @@ public class DynamicMessageTest extends TestCase { DynamicMessage message = builder.buildPartial(); assertTrue(message.hasOneof(oneof)); - DynamicMessage.Builder mergedBuilder = - DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); + DynamicMessage.Builder mergedBuilder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); FieldDescriptor mergedField = oneof.getField(0); mergedBuilder.setField(mergedField, 123); assertTrue(mergedBuilder.hasField(mergedField)); @@ -310,15 +293,12 @@ public class DynamicMessageTest extends TestCase { // Regression test for a bug that makes setField() not work for repeated // enum fields. public void testSettersForRepeatedEnumField() throws Exception { - DynamicMessage.Builder builder = - DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); + DynamicMessage.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor()); FieldDescriptor repeatedEnumField = - TestAllTypes.getDescriptor().findFieldByName( - "repeated_nested_enum"); + TestAllTypes.getDescriptor().findFieldByName("repeated_nested_enum"); EnumDescriptor enumDescriptor = TestAllTypes.NestedEnum.getDescriptor(); builder.setField(repeatedEnumField, enumDescriptor.getValues()); DynamicMessage message = builder.build(); - assertEquals( - enumDescriptor.getValues(), message.getField(repeatedEnumField)); + assertEquals(enumDescriptor.getValues(), message.getField(repeatedEnumField)); } } diff --git a/java/core/src/test/java/com/google/protobuf/EnumTest.java b/java/core/src/test/java/com/google/protobuf/EnumTest.java index 14c7406b3d..80c176a771 100644 --- a/java/core/src/test/java/com/google/protobuf/EnumTest.java +++ b/java/core/src/test/java/com/google/protobuf/EnumTest.java @@ -34,43 +34,43 @@ import com.google.protobuf.UnittestLite.ForeignEnumLite; import com.google.protobuf.UnittestLite.TestAllTypesLite; import protobuf_unittest.UnittestProto.ForeignEnum; import protobuf_unittest.UnittestProto.TestAllTypes; - import junit.framework.TestCase; public class EnumTest extends TestCase { - + public void testForNumber() { ForeignEnum e = ForeignEnum.forNumber(ForeignEnum.FOREIGN_BAR.getNumber()); assertEquals(ForeignEnum.FOREIGN_BAR, e); e = ForeignEnum.forNumber(1000); - assertEquals(null, e); + assertNull(e); } - + public void testForNumber_oneof() { - TestAllTypes.OneofFieldCase e = TestAllTypes.OneofFieldCase.forNumber( - TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber()); + TestAllTypes.OneofFieldCase e = + TestAllTypes.OneofFieldCase.forNumber( + TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber()); assertEquals(TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE, e); e = TestAllTypes.OneofFieldCase.forNumber(1000); - assertEquals(null, e); + assertNull(e); } - + public void testForNumberLite() { ForeignEnumLite e = ForeignEnumLite.forNumber(ForeignEnumLite.FOREIGN_LITE_BAR.getNumber()); assertEquals(ForeignEnumLite.FOREIGN_LITE_BAR, e); e = ForeignEnumLite.forNumber(1000); - assertEquals(null, e); + assertNull(e); } - + public void testForNumberLite_oneof() { - TestAllTypesLite.OneofFieldCase e = TestAllTypesLite.OneofFieldCase.forNumber( - TestAllTypesLite.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber()); + TestAllTypesLite.OneofFieldCase e = + TestAllTypesLite.OneofFieldCase.forNumber( + TestAllTypesLite.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber()); assertEquals(TestAllTypesLite.OneofFieldCase.ONEOF_NESTED_MESSAGE, e); e = TestAllTypesLite.OneofFieldCase.forNumber(1000); - assertEquals(null, e); + assertNull(e); } } - diff --git a/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java b/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java index 6157e58966..a0e9137552 100644 --- a/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java +++ b/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java @@ -47,31 +47,31 @@ import junit.framework.TestSuite; * creates. * *

This test simulates the runtime behaviour of the ExtensionRegistryFactory by delegating test - * definitions to two inner classes {@link InnerTest} and {@link InnerLiteTest}, the latter of - * which is executed using a custom ClassLoader, simulating the ProtoLite environment. + * definitions to two inner classes {@link InnerTest} and {@link InnerLiteTest}, the latter of which + * is executed using a custom ClassLoader, simulating the ProtoLite environment. * - *

The test mechanism employed here is based on the pattern in - * {@code com.google.common.util.concurrent.AbstractFutureFallbackAtomicHelperTest} + *

The test mechanism employed here is based on the pattern in {@code + * com.google.common.util.concurrent.AbstractFutureFallbackAtomicHelperTest} */ public class ExtensionRegistryFactoryTest extends TestCase { // A classloader which blacklists some non-Lite classes. private static final ClassLoader LITE_CLASS_LOADER = getLiteOnlyClassLoader(); - /** - * Defines the set of test methods which will be run. - */ + /** Defines the set of test methods which will be run. */ static interface RegistryTests { void testCreate(); + void testEmpty(); + void testIsFullRegistry(); + void testAdd(); + void testAdd_immutable(); } - /** - * Test implementations for the non-Lite usage of ExtensionRegistryFactory. - */ + /** Test implementations for the non-Lite usage of ExtensionRegistryFactory. */ public static class InnerTest implements RegistryTests { @Override @@ -108,20 +108,25 @@ public class ExtensionRegistryFactoryTest extends TestCase { ExtensionRegistry fullRegistry1 = (ExtensionRegistry) registry1; ExtensionRegistry fullRegistry2 = (ExtensionRegistry) registry2; - assertTrue("Test is using a non-lite extension", + assertTrue( + "Test is using a non-lite extension", GeneratedMessageLite.GeneratedExtension.class.isAssignableFrom( NonNestedExtensionLite.nonNestedExtensionLite.getClass())); - assertNull("Extension is not registered in masqueraded full registry", + assertNull( + "Extension is not registered in masqueraded full registry", fullRegistry1.findImmutableExtensionByName("protobuf_unittest.nonNestedExtension")); GeneratedMessageLite.GeneratedExtension - extension = registry1.findLiteExtensionByNumber( - NonNestedExtensionLite.MessageLiteToBeExtended.getDefaultInstance(), 1); + extension = + registry1.findLiteExtensionByNumber( + NonNestedExtensionLite.MessageLiteToBeExtended.getDefaultInstance(), 1); assertNotNull("Extension registered in lite registry", extension); - assertTrue("Test is using a non-lite extension", + assertTrue( + "Test is using a non-lite extension", GeneratedMessage.GeneratedExtension.class.isAssignableFrom( - NonNestedExtension.nonNestedExtension.getClass())); - assertNotNull("Extension is registered in masqueraded full registry", + NonNestedExtension.nonNestedExtension.getClass())); + assertNotNull( + "Extension is registered in masqueraded full registry", fullRegistry2.findImmutableExtensionByName("protobuf_unittest.nonNestedExtension")); } @@ -131,27 +136,29 @@ public class ExtensionRegistryFactoryTest extends TestCase { try { NonNestedExtensionLite.registerAllExtensions(registry1); fail(); - } catch (UnsupportedOperationException expected) {} + } catch (UnsupportedOperationException expected) { + } try { registry1.add(NonNestedExtensionLite.nonNestedExtensionLite); fail(); - } catch (UnsupportedOperationException expected) {} + } catch (UnsupportedOperationException expected) { + } ExtensionRegistryLite registry2 = ExtensionRegistryLite.newInstance().getUnmodifiable(); try { NonNestedExtension.registerAllExtensions((ExtensionRegistry) registry2); fail(); - } catch (IllegalArgumentException expected) {} + } catch (IllegalArgumentException expected) { + } try { registry2.add(NonNestedExtension.nonNestedExtension); fail(); - } catch (IllegalArgumentException expected) {} + } catch (IllegalArgumentException expected) { + } } } - /** - * Test implementations for the Lite usage of ExtensionRegistryFactory. - */ + /** Test implementations for the Lite usage of ExtensionRegistryFactory. */ public static final class InnerLiteTest implements RegistryTests { @Override @@ -180,8 +187,9 @@ public class ExtensionRegistryFactoryTest extends TestCase { ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance(); NonNestedExtensionLite.registerAllExtensions(registry); GeneratedMessageLite.GeneratedExtension - extension = registry.findLiteExtensionByNumber( - NonNestedExtensionLite.MessageLiteToBeExtended.getDefaultInstance(), 1); + extension = + registry.findLiteExtensionByNumber( + NonNestedExtensionLite.MessageLiteToBeExtended.getDefaultInstance(), 1); assertNotNull("Extension is registered in Lite registry", extension); } @@ -191,13 +199,12 @@ public class ExtensionRegistryFactoryTest extends TestCase { try { NonNestedExtensionLite.registerAllExtensions(registry); fail(); - } catch (UnsupportedOperationException expected) {} + } catch (UnsupportedOperationException expected) { + } } } - /** - * Defines a suite of tests which the JUnit3 runner retrieves by reflection. - */ + /** Defines a suite of tests which the JUnit3 runner retrieves by reflection. */ public static Test suite() { TestSuite suite = new TestSuite(); for (Method method : RegistryTests.class.getMethods()) { @@ -235,8 +242,8 @@ public class ExtensionRegistryFactoryTest extends TestCase { } /** - * Constructs a custom ClassLoader blacklisting the classes which are inspected in the SUT - * to determine the Lite/non-Lite runtime. + * Constructs a custom ClassLoader blacklisting the classes which are inspected in the SUT to + * determine the Lite/non-Lite runtime. */ private static ClassLoader getLiteOnlyClassLoader() { ClassLoader testClassLoader = ExtensionRegistryFactoryTest.class.getClassLoader(); @@ -250,8 +257,8 @@ public class ExtensionRegistryFactoryTest extends TestCase { // Construct a URLClassLoader delegating to the system ClassLoader, and looking up classes // in jar files based on the URLs already configured for this test's UrlClassLoader. // Certain classes throw a ClassNotFoundException by design. - return new URLClassLoader(((URLClassLoader) testClassLoader).getURLs(), - ClassLoader.getSystemClassLoader()) { + return new URLClassLoader( + ((URLClassLoader) testClassLoader).getURLs(), ClassLoader.getSystemClassLoader()) { @Override public Class loadClass(String name, boolean resolve) throws ClassNotFoundException { if (classNamesNotInLite.contains(name)) { diff --git a/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java b/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java index 42da5bb38b..85a2fe086e 100644 --- a/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java +++ b/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java @@ -38,12 +38,10 @@ import com.google.protobuf.FieldPresenceTestProto.TestAllTypes; import com.google.protobuf.FieldPresenceTestProto.TestOptionalFieldsOnly; import com.google.protobuf.FieldPresenceTestProto.TestRepeatedFieldsOnly; import protobuf_unittest.UnittestProto; - import junit.framework.TestCase; /** - * Unit tests for protos that doesn't support field presence test for optional - * non-message fields. + * Unit tests for protos that doesn't support field presence test for optional non-message fields. */ public class FieldPresenceTest extends TestCase { private static boolean hasMethod(Class clazz, String name) { @@ -59,9 +57,7 @@ public class FieldPresenceTest extends TestCase { } private static void assertHasMethodRemoved( - Class classWithFieldPresence, - Class classWithoutFieldPresence, - String camelName) { + Class classWithFieldPresence, Class classWithoutFieldPresence, String camelName) { assertTrue(hasMethod(classWithFieldPresence, "get" + camelName)); assertTrue(hasMethod(classWithFieldPresence, "has" + camelName)); assertTrue(hasMethod(classWithoutFieldPresence, "get" + camelName)); @@ -70,72 +66,38 @@ public class FieldPresenceTest extends TestCase { public void testHasMethod() { // Optional non-message fields don't have a hasFoo() method generated. + assertHasMethodRemoved(UnittestProto.TestAllTypes.class, TestAllTypes.class, "OptionalInt32"); + assertHasMethodRemoved(UnittestProto.TestAllTypes.class, TestAllTypes.class, "OptionalString"); + assertHasMethodRemoved(UnittestProto.TestAllTypes.class, TestAllTypes.class, "OptionalBytes"); assertHasMethodRemoved( - UnittestProto.TestAllTypes.class, - TestAllTypes.class, - "OptionalInt32"); - assertHasMethodRemoved( - UnittestProto.TestAllTypes.class, - TestAllTypes.class, - "OptionalString"); - assertHasMethodRemoved( - UnittestProto.TestAllTypes.class, - TestAllTypes.class, - "OptionalBytes"); - assertHasMethodRemoved( - UnittestProto.TestAllTypes.class, - TestAllTypes.class, - "OptionalNestedEnum"); + UnittestProto.TestAllTypes.class, TestAllTypes.class, "OptionalNestedEnum"); assertHasMethodRemoved( - UnittestProto.TestAllTypes.Builder.class, - TestAllTypes.Builder.class, - "OptionalInt32"); + UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OptionalInt32"); assertHasMethodRemoved( - UnittestProto.TestAllTypes.Builder.class, - TestAllTypes.Builder.class, - "OptionalString"); + UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OptionalString"); assertHasMethodRemoved( - UnittestProto.TestAllTypes.Builder.class, - TestAllTypes.Builder.class, - "OptionalBytes"); + UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OptionalBytes"); assertHasMethodRemoved( - UnittestProto.TestAllTypes.Builder.class, - TestAllTypes.Builder.class, - "OptionalNestedEnum"); + UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OptionalNestedEnum"); // message fields still have the hasFoo() method generated. - assertFalse(TestAllTypes.newBuilder().build().hasOptionalNestedMessage()); + assertFalse(TestAllTypes.getDefaultInstance().hasOptionalNestedMessage()); assertFalse(TestAllTypes.newBuilder().hasOptionalNestedMessage()); // oneof fields don't have hasFoo() methods for non-message types. - assertHasMethodRemoved( - UnittestProto.TestAllTypes.class, - TestAllTypes.class, - "OneofUint32"); - assertHasMethodRemoved( - UnittestProto.TestAllTypes.class, - TestAllTypes.class, - "OneofString"); - assertHasMethodRemoved( - UnittestProto.TestAllTypes.class, - TestAllTypes.class, - "OneofBytes"); - assertFalse(TestAllTypes.newBuilder().build().hasOneofNestedMessage()); + assertHasMethodRemoved(UnittestProto.TestAllTypes.class, TestAllTypes.class, "OneofUint32"); + assertHasMethodRemoved(UnittestProto.TestAllTypes.class, TestAllTypes.class, "OneofString"); + assertHasMethodRemoved(UnittestProto.TestAllTypes.class, TestAllTypes.class, "OneofBytes"); + assertFalse(TestAllTypes.getDefaultInstance().hasOneofNestedMessage()); assertFalse(TestAllTypes.newBuilder().hasOneofNestedMessage()); assertHasMethodRemoved( - UnittestProto.TestAllTypes.Builder.class, - TestAllTypes.Builder.class, - "OneofUint32"); + UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OneofUint32"); assertHasMethodRemoved( - UnittestProto.TestAllTypes.Builder.class, - TestAllTypes.Builder.class, - "OneofString"); + UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OneofString"); assertHasMethodRemoved( - UnittestProto.TestAllTypes.Builder.class, - TestAllTypes.Builder.class, - "OneofBytes"); + UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OneofBytes"); } public void testOneofEquals() throws Exception { @@ -200,10 +162,10 @@ public class FieldPresenceTest extends TestCase { assertEquals(TestAllTypes.NestedEnum.BAR, message.getOptionalNestedEnum()); // equals()/hashCode() should produce the same results. - TestAllTypes empty = TestAllTypes.newBuilder().build(); + TestAllTypes empty = TestAllTypes.getDefaultInstance(); message = builder.build(); - assertTrue(empty.equals(message)); - assertTrue(message.equals(empty)); + assertEquals(message, empty); + assertEquals(empty, message); assertEquals(empty.hashCode(), message.hashCode()); } @@ -215,7 +177,7 @@ public class FieldPresenceTest extends TestCase { FieldDescriptor optionalNestedEnumField = descriptor.findFieldByName("optional_nested_enum"); // Field not present. - TestAllTypes message = TestAllTypes.newBuilder().build(); + TestAllTypes message = TestAllTypes.getDefaultInstance(); assertFalse(message.hasField(optionalInt32Field)); assertFalse(message.hasField(optionalStringField)); assertFalse(message.hasField(optionalBytesField)); @@ -223,12 +185,13 @@ public class FieldPresenceTest extends TestCase { assertEquals(0, message.getAllFields().size()); // Field set to default value is seen as not present. - message = TestAllTypes.newBuilder() - .setOptionalInt32(0) - .setOptionalString("") - .setOptionalBytes(ByteString.EMPTY) - .setOptionalNestedEnum(TestAllTypes.NestedEnum.FOO) - .build(); + message = + TestAllTypes.newBuilder() + .setOptionalInt32(0) + .setOptionalString("") + .setOptionalBytes(ByteString.EMPTY) + .setOptionalNestedEnum(TestAllTypes.NestedEnum.FOO) + .build(); assertFalse(message.hasField(optionalInt32Field)); assertFalse(message.hasField(optionalStringField)); assertFalse(message.hasField(optionalBytesField)); @@ -236,12 +199,13 @@ public class FieldPresenceTest extends TestCase { assertEquals(0, message.getAllFields().size()); // Field set to non-default value is seen as present. - message = TestAllTypes.newBuilder() - .setOptionalInt32(1) - .setOptionalString("x") - .setOptionalBytes(ByteString.copyFromUtf8("y")) - .setOptionalNestedEnum(TestAllTypes.NestedEnum.BAR) - .build(); + message = + TestAllTypes.newBuilder() + .setOptionalInt32(1) + .setOptionalString("x") + .setOptionalBytes(ByteString.copyFromUtf8("y")) + .setOptionalNestedEnum(TestAllTypes.NestedEnum.BAR) + .build(); assertTrue(message.hasField(optionalInt32Field)); assertTrue(message.hasField(optionalStringField)); assertTrue(message.hasField(optionalBytesField)); @@ -284,7 +248,9 @@ public class FieldPresenceTest extends TestCase { assertEquals(4, message.getAllFields().size()); // Field set to default value is seen as not present. - message = message.toBuilder() + message = + message + .toBuilder() .setField(optionalInt32Field, 0) .setField(optionalStringField, "") .setField(optionalBytesField, ByteString.EMPTY) @@ -302,8 +268,7 @@ public class FieldPresenceTest extends TestCase { assertFalse(builder.hasOptionalNestedMessage()); assertFalse(builder.build().hasOptionalNestedMessage()); - TestAllTypes.NestedMessage.Builder nestedBuilder = - builder.getOptionalNestedMessageBuilder(); + TestAllTypes.NestedMessage.Builder nestedBuilder = builder.getOptionalNestedMessageBuilder(); assertTrue(builder.hasOptionalNestedMessage()); assertTrue(builder.build().hasOptionalNestedMessage()); @@ -341,8 +306,7 @@ public class FieldPresenceTest extends TestCase { assertTrue(message.hasOptionalNestedMessage()); assertEquals(0, message.getOptionalNestedMessage().getValue()); // The oneof field set to its default value is also present. - assertEquals( - TestAllTypes.OneofFieldCase.ONEOF_INT32, message.getOneofFieldCase()); + assertEquals(TestAllTypes.OneofFieldCase.ONEOF_INT32, message.getOneofFieldCase()); } // Regression test for b/16173397 @@ -376,8 +340,7 @@ public class FieldPresenceTest extends TestCase { TestAllTypes.Builder builder = TestAllTypes.newBuilder(); // Test optional proto2 message fields. - UnittestProto.TestRequired.Builder proto2Builder = - builder.getOptionalProto2MessageBuilder(); + UnittestProto.TestRequired.Builder proto2Builder = builder.getOptionalProto2MessageBuilder(); assertFalse(builder.isInitialized()); assertFalse(builder.buildPartial().isInitialized()); diff --git a/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java b/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java index 38eccc93b2..7ed613403c 100644 --- a/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java +++ b/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java @@ -45,10 +45,8 @@ import junit.framework.TestCase; */ public class FloatArrayListTest extends TestCase { - private static final FloatArrayList UNARY_LIST = - newImmutableFloatArrayList(1); - private static final FloatArrayList TERTIARY_LIST = - newImmutableFloatArrayList(1, 2, 3); + private static final FloatArrayList UNARY_LIST = newImmutableFloatArrayList(1); + private static final FloatArrayList TERTIARY_LIST = newImmutableFloatArrayList(1, 2, 3); private FloatArrayList list; @@ -225,9 +223,7 @@ public class FloatArrayListTest extends TestCase { for (int i = 0; i < 6; i++) { list.add(Float.valueOf(5 + i)); } - assertEquals( - asList(0F, 1F, 4F, 2F, 3F, 5F, 6F, 7F, 8F, 9F, 10F), - list); + assertEquals(asList(0F, 1F, 4F, 2F, 3F, 5F, 6F, 7F, 8F, 9F, 10F), list); try { list.add(-1, 5F); @@ -299,16 +295,14 @@ public class FloatArrayListTest extends TestCase { } public void testRemoveEndOfCapacity() { - FloatList toRemove = - FloatArrayList.emptyList().mutableCopyWithCapacity(1); + FloatList toRemove = FloatArrayList.emptyList().mutableCopyWithCapacity(1); toRemove.addFloat(3); toRemove.remove(0); assertEquals(0, toRemove.size()); } public void testSublistRemoveEndOfCapacity() { - FloatList toRemove = - FloatArrayList.emptyList().mutableCopyWithCapacity(1); + FloatList toRemove = FloatArrayList.emptyList().mutableCopyWithCapacity(1); toRemove.addFloat(3); toRemove.subList(0, 1).clear(); assertEquals(0, toRemove.size()); diff --git a/java/core/src/test/java/com/google/protobuf/ForceFieldBuildersPreRun.java b/java/core/src/test/java/com/google/protobuf/ForceFieldBuildersPreRun.java index b7eaebf5e2..baa6d08670 100644 --- a/java/core/src/test/java/com/google/protobuf/ForceFieldBuildersPreRun.java +++ b/java/core/src/test/java/com/google/protobuf/ForceFieldBuildersPreRun.java @@ -31,11 +31,10 @@ package com.google.protobuf; /** - * A prerun for a test suite that allows running the full protocol buffer - * tests in a mode that disables the optimization for not using - * {@link RepeatedFieldBuilder} and {@link SingleFieldBuilder} until they are - * requested. This allows us to run all the tests through both code paths - * and ensures that both code paths produce identical results. + * A prerun for a test suite that allows running the full protocol buffer tests in a mode that + * disables the optimization for not using {@link RepeatedFieldBuilder} and {@link + * SingleFieldBuilder} until they are requested. This allows us to run all the tests through both + * code paths and ensures that both code paths produce identical results. * * @author jonp@google.com (Jon Perlow) */ diff --git a/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java b/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java index 4489dacea5..13457bc07d 100644 --- a/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java +++ b/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java @@ -32,7 +32,6 @@ package com.google.protobuf; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; -import com.google.protobuf.Int32Value; import com.google.protobuf.test.UnittestImport; import protobuf_unittest.EnumWithNoOuter; import protobuf_unittest.MessageWithNoOuter; @@ -72,20 +71,21 @@ import java.util.List; import junit.framework.TestCase; /** - * Unit test for generated messages and generated code. See also - * {@link MessageTest}, which tests some generated message functionality. + * Unit test for generated messages and generated code. See also {@link MessageTest}, which tests + * some generated message functionality. * * @author kenton@google.com Kenton Varda */ public class GeneratedMessageTest extends TestCase { TestUtil.ReflectionTester reflectionTester = - new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null); + new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null); public void testDefaultInstance() throws Exception { - assertSame(TestAllTypes.getDefaultInstance(), - TestAllTypes.getDefaultInstance().getDefaultInstanceForType()); - assertSame(TestAllTypes.getDefaultInstance(), - TestAllTypes.newBuilder().getDefaultInstanceForType()); + assertSame( + TestAllTypes.getDefaultInstance(), + TestAllTypes.getDefaultInstance().getDefaultInstanceForType()); + assertSame( + TestAllTypes.getDefaultInstance(), TestAllTypes.newBuilder().getDefaultInstanceForType()); } public void testMessageOrBuilder() throws Exception { @@ -111,10 +111,8 @@ public class GeneratedMessageTest extends TestCase { assertEquals(100, value1.getOptionalSfixed64()); assertEquals(100, value1.getRepeatedInt32(0)); - assertEquals(UnittestImport.ImportEnum.IMPORT_BAR, - value1.getOptionalImportEnum()); - assertEquals(UnittestImport.ImportEnum.IMPORT_BAR, - value1.getRepeatedImportEnum(0)); + assertEquals(UnittestImport.ImportEnum.IMPORT_BAR, value1.getOptionalImportEnum()); + assertEquals(UnittestImport.ImportEnum.IMPORT_BAR, value1.getRepeatedImportEnum(0)); assertEquals(1, value1.getOptionalForeignMessage().getC()); assertEquals(1, value1.getRepeatedForeignMessage(0).getC()); @@ -131,20 +129,16 @@ public class GeneratedMessageTest extends TestCase { // Make sure value1 didn't change. assertEquals(100, value1.getOptionalSfixed64()); assertEquals(100, value1.getRepeatedInt32(0)); - assertEquals(UnittestImport.ImportEnum.IMPORT_BAR, - value1.getOptionalImportEnum()); - assertEquals(UnittestImport.ImportEnum.IMPORT_BAR, - value1.getRepeatedImportEnum(0)); + assertEquals(UnittestImport.ImportEnum.IMPORT_BAR, value1.getOptionalImportEnum()); + assertEquals(UnittestImport.ImportEnum.IMPORT_BAR, value1.getRepeatedImportEnum(0)); assertEquals(1, value1.getOptionalForeignMessage().getC()); assertEquals(1, value1.getRepeatedForeignMessage(0).getC()); // Make sure value2 is correct assertEquals(200, value2.getOptionalSfixed64()); assertEquals(200, value2.getRepeatedInt32(0)); - assertEquals(UnittestImport.ImportEnum.IMPORT_FOO, - value2.getOptionalImportEnum()); - assertEquals(UnittestImport.ImportEnum.IMPORT_FOO, - value2.getRepeatedImportEnum(0)); + assertEquals(UnittestImport.ImportEnum.IMPORT_FOO, value2.getOptionalImportEnum()); + assertEquals(UnittestImport.ImportEnum.IMPORT_FOO, value2.getRepeatedImportEnum(0)); assertEquals(2, value2.getOptionalForeignMessage().getC()); assertEquals(2, value2.getRepeatedForeignMessage(0).getC()); } @@ -158,8 +152,7 @@ public class GeneratedMessageTest extends TestCase { TestAllTypes value2 = value1.toBuilder().build(); assertSame(value1.getRepeatedInt32List(), value2.getRepeatedInt32List()); - assertSame(value1.getRepeatedForeignMessageList(), - value2.getRepeatedForeignMessageList()); + assertSame(value1.getRepeatedForeignMessageList(), value2.getRepeatedForeignMessageList()); } public void testRepeatedArraysAreImmutable() throws Exception { @@ -172,7 +165,6 @@ public class GeneratedMessageTest extends TestCase { assertIsUnmodifiable(builder.getRepeatedForeignMessageList()); assertIsUnmodifiable(builder.getRepeatedFloatList()); - TestAllTypes value = builder.build(); assertIsUnmodifiable(value.getRepeatedInt32List()); assertIsUnmodifiable(value.getRepeatedImportEnumList()); @@ -240,8 +232,7 @@ public class GeneratedMessageTest extends TestCase { // We expect this exception. } try { - builder.setOptionalNestedMessage( - (TestAllTypes.NestedMessage.Builder) null); + builder.setOptionalNestedMessage((TestAllTypes.NestedMessage.Builder) null); fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. @@ -271,8 +262,7 @@ public class GeneratedMessageTest extends TestCase { // We expect this exception. } try { - builder.addRepeatedNestedMessage( - (TestAllTypes.NestedMessage.Builder) null); + builder.addRepeatedNestedMessage((TestAllTypes.NestedMessage.Builder) null); fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. @@ -314,10 +304,8 @@ public class GeneratedMessageTest extends TestCase { // We expect this exception. } - builder.addRepeatedNestedMessage( - TestAllTypes.NestedMessage.newBuilder().setBb(218).build()); - builder.addRepeatedNestedMessage( - TestAllTypes.NestedMessage.newBuilder().setBb(456).build()); + builder.addRepeatedNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(218).build()); + builder.addRepeatedNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(456).build()); try { builder.setRepeatedNestedMessage(1, (TestAllTypes.NestedMessage) null); fail("Exception was not thrown"); @@ -325,8 +313,7 @@ public class GeneratedMessageTest extends TestCase { // We expect this exception. } try { - builder.setRepeatedNestedMessage( - 1, (TestAllTypes.NestedMessage.Builder) null); + builder.setRepeatedNestedMessage(1, (TestAllTypes.NestedMessage.Builder) null); fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. @@ -348,14 +335,12 @@ public class GeneratedMessageTest extends TestCase { builder.addAllRepeatedInt32(Arrays.asList(1, 2, 3, 4)); builder.addAllRepeatedForeignEnum(Arrays.asList(ForeignEnum.FOREIGN_BAZ)); - ForeignMessage foreignMessage = - ForeignMessage.newBuilder().setC(12).build(); + ForeignMessage foreignMessage = ForeignMessage.newBuilder().setC(12).build(); builder.addAllRepeatedForeignMessage(Arrays.asList(foreignMessage)); TestAllTypes message = builder.build(); assertEquals(message.getRepeatedInt32List(), Arrays.asList(1, 2, 3, 4)); - assertEquals(message.getRepeatedForeignEnumList(), - Arrays.asList(ForeignEnum.FOREIGN_BAZ)); + assertEquals(message.getRepeatedForeignEnumList(), Arrays.asList(ForeignEnum.FOREIGN_BAZ)); assertEquals(1, message.getRepeatedForeignMessageCount()); assertEquals(12, message.getRepeatedForeignMessage(0).getC()); } @@ -363,19 +348,16 @@ public class GeneratedMessageTest extends TestCase { public void testRepeatedAppendRejectsNull() throws Exception { TestAllTypes.Builder builder = TestAllTypes.newBuilder(); - ForeignMessage foreignMessage = - ForeignMessage.newBuilder().setC(12).build(); + ForeignMessage foreignMessage = ForeignMessage.newBuilder().setC(12).build(); try { - builder.addAllRepeatedForeignMessage( - Arrays.asList(foreignMessage, (ForeignMessage) null)); + builder.addAllRepeatedForeignMessage(Arrays.asList(foreignMessage, (ForeignMessage) null)); fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. } try { - builder.addAllRepeatedForeignEnum( - Arrays.asList(ForeignEnum.FOREIGN_BAZ, null)); + builder.addAllRepeatedForeignEnum(Arrays.asList(ForeignEnum.FOREIGN_BAZ, null)); fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. @@ -395,20 +377,22 @@ public class GeneratedMessageTest extends TestCase { // We expect this exception. } } - + public void testRepeatedAppendIterateOnlyOnce() throws Exception { // Create a Iterable that can only be iterated once. - Iterable stringIterable = new Iterable() { - private boolean called = false; - @Override - public Iterator iterator() { - if (called) { - throw new IllegalStateException(); - } - called = true; - return Arrays.asList("one", "two", "three").iterator(); - } - }; + Iterable stringIterable = + new Iterable() { + private boolean called = false; + + @Override + public Iterator iterator() { + if (called) { + throw new IllegalStateException(); + } + called = true; + return Arrays.asList("one", "two", "three").iterator(); + } + }; TestAllTypes.Builder builder = TestAllTypes.newBuilder(); builder.addAllRepeatedString(stringIterable); assertEquals(3, builder.getRepeatedStringCount()); @@ -435,29 +419,31 @@ public class GeneratedMessageTest extends TestCase { } public void testSettingForeignMessageUsingBuilder() throws Exception { - TestAllTypes message = TestAllTypes.newBuilder() - // Pass builder for foreign message instance. - .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(123)) - .build(); - TestAllTypes expectedMessage = TestAllTypes.newBuilder() - // Create expected version passing foreign message instance explicitly. - .setOptionalForeignMessage( - ForeignMessage.newBuilder().setC(123).build()) - .build(); + TestAllTypes message = + TestAllTypes.newBuilder() + // Pass builder for foreign message instance. + .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(123)) + .build(); + TestAllTypes expectedMessage = + TestAllTypes.newBuilder() + // Create expected version passing foreign message instance explicitly. + .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(123).build()) + .build(); // TODO(ngd): Upgrade to using real #equals method once implemented assertEquals(expectedMessage.toString(), message.toString()); } public void testSettingRepeatedForeignMessageUsingBuilder() throws Exception { - TestAllTypes message = TestAllTypes.newBuilder() - // Pass builder for foreign message instance. - .addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(456)) - .build(); - TestAllTypes expectedMessage = TestAllTypes.newBuilder() - // Create expected version passing foreign message instance explicitly. - .addRepeatedForeignMessage( - ForeignMessage.newBuilder().setC(456).build()) - .build(); + TestAllTypes message = + TestAllTypes.newBuilder() + // Pass builder for foreign message instance. + .addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(456)) + .build(); + TestAllTypes expectedMessage = + TestAllTypes.newBuilder() + // Create expected version passing foreign message instance explicitly. + .addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(456).build()) + .build(); assertEquals(expectedMessage.toString(), message.toString()); } @@ -465,14 +451,13 @@ public class GeneratedMessageTest extends TestCase { TestUtil.assertClear(TestAllTypes.getDefaultInstance()); TestUtil.assertClear(TestAllTypes.newBuilder().build()); - TestExtremeDefaultValues message = - TestExtremeDefaultValues.getDefaultInstance(); + TestExtremeDefaultValues message = TestExtremeDefaultValues.getDefaultInstance(); assertEquals("\u1234", message.getUtf8String()); - assertEquals(Double.POSITIVE_INFINITY, message.getInfDouble()); - assertEquals(Double.NEGATIVE_INFINITY, message.getNegInfDouble()); + assertEquals(Double.POSITIVE_INFINITY, message.getInfDouble(), 0.0); + assertEquals(Double.NEGATIVE_INFINITY, message.getNegInfDouble(), 0.0); assertTrue(Double.isNaN(message.getNanDouble())); - assertEquals(Float.POSITIVE_INFINITY, message.getInfFloat()); - assertEquals(Float.NEGATIVE_INFINITY, message.getNegInfFloat()); + assertEquals(Float.POSITIVE_INFINITY, message.getInfFloat(), 0.0f); + assertEquals(Float.NEGATIVE_INFINITY, message.getNegInfFloat(), 0.0f); assertTrue(Float.isNaN(message.getNanFloat())); assertEquals("? ? ?? ?? ??? ??/ ??-", message.getCppTrigraph()); } @@ -524,19 +509,15 @@ public class GeneratedMessageTest extends TestCase { } public void testReflectionDefaults() throws Exception { - reflectionTester.assertClearViaReflection( - TestAllTypes.getDefaultInstance()); - reflectionTester.assertClearViaReflection( - TestAllTypes.newBuilder().build()); + reflectionTester.assertClearViaReflection(TestAllTypes.getDefaultInstance()); + reflectionTester.assertClearViaReflection(TestAllTypes.newBuilder().build()); } public void testReflectionGetOneof() throws Exception { TestAllTypes.Builder builder = TestAllTypes.newBuilder(); reflectionTester.setAllFieldsViaReflection(builder); - Descriptors.OneofDescriptor oneof = - TestAllTypes.getDescriptor().getOneofs().get(0); - Descriptors.FieldDescriptor field = - TestAllTypes.getDescriptor().findFieldByName("oneof_bytes"); + Descriptors.OneofDescriptor oneof = TestAllTypes.getDescriptor().getOneofs().get(0); + Descriptors.FieldDescriptor field = TestAllTypes.getDescriptor().findFieldByName("oneof_bytes"); assertSame(field, builder.getOneofFieldDescriptor(oneof)); TestAllTypes message = builder.build(); @@ -546,10 +527,8 @@ public class GeneratedMessageTest extends TestCase { public void testReflectionClearOneof() throws Exception { TestAllTypes.Builder builder = TestAllTypes.newBuilder(); reflectionTester.setAllFieldsViaReflection(builder); - Descriptors.OneofDescriptor oneof = - TestAllTypes.getDescriptor().getOneofs().get(0); - Descriptors.FieldDescriptor field = - TestAllTypes.getDescriptor().findFieldByName("oneof_bytes"); + Descriptors.OneofDescriptor oneof = TestAllTypes.getDescriptor().getOneofs().get(0); + Descriptors.FieldDescriptor field = TestAllTypes.getDescriptor().findFieldByName("oneof_bytes"); assertTrue(builder.hasOneof(oneof)); assertTrue(builder.hasField(field)); @@ -559,8 +538,8 @@ public class GeneratedMessageTest extends TestCase { } public void testEnumInterface() throws Exception { - assertTrue(TestAllTypes.getDefaultInstance().getDefaultNestedEnum() - instanceof ProtocolMessageEnum); + assertTrue( + TestAllTypes.getDefaultInstance().getDefaultNestedEnum() instanceof ProtocolMessageEnum); } public void testEnumMap() throws Exception { @@ -575,15 +554,13 @@ public class GeneratedMessageTest extends TestCase { public void testParsePackedToUnpacked() throws Exception { TestUnpackedTypes.Builder builder = TestUnpackedTypes.newBuilder(); - TestUnpackedTypes message = - builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build(); + TestUnpackedTypes message = builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build(); TestUtil.assertUnpackedFieldsSet(message); } public void testParseUnpackedToPacked() throws Exception { TestPackedTypes.Builder builder = TestPackedTypes.newBuilder(); - TestPackedTypes message = - builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build(); + TestPackedTypes message = builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build(); TestUtil.assertPackedFieldsSet(message); } @@ -662,32 +639,29 @@ public class GeneratedMessageTest extends TestCase { TestUtil.assertRepeatedExtensionsModified(message); } - public void testExtensionReflectionRepeatedSettersRejectNull() - throws Exception { + public void testExtensionReflectionRepeatedSettersRejectNull() throws Exception { TestAllExtensions.Builder builder = TestAllExtensions.newBuilder(); - extensionsReflectionTester.assertReflectionRepeatedSettersRejectNull( - builder); + extensionsReflectionTester.assertReflectionRepeatedSettersRejectNull(builder); } public void testExtensionReflectionDefaults() throws Exception { - extensionsReflectionTester.assertClearViaReflection( - TestAllExtensions.getDefaultInstance()); - extensionsReflectionTester.assertClearViaReflection( - TestAllExtensions.newBuilder().build()); + extensionsReflectionTester.assertClearViaReflection(TestAllExtensions.getDefaultInstance()); + extensionsReflectionTester.assertClearViaReflection(TestAllExtensions.newBuilder().build()); } public void testClearExtension() throws Exception { // clearExtension() is not actually used in TestUtil, so try it manually. assertFalse( - TestAllExtensions.newBuilder() - .setExtension(UnittestProto.optionalInt32Extension, 1) - .clearExtension(UnittestProto.optionalInt32Extension) - .hasExtension(UnittestProto.optionalInt32Extension)); - assertEquals(0, - TestAllExtensions.newBuilder() - .addExtension(UnittestProto.repeatedInt32Extension, 1) - .clearExtension(UnittestProto.repeatedInt32Extension) - .getExtensionCount(UnittestProto.repeatedInt32Extension)); + TestAllExtensions.newBuilder() + .setExtension(UnittestProto.optionalInt32Extension, 1) + .clearExtension(UnittestProto.optionalInt32Extension) + .hasExtension(UnittestProto.optionalInt32Extension)); + assertEquals( + 0, + TestAllExtensions.newBuilder() + .addExtension(UnittestProto.repeatedInt32Extension, 1) + .clearExtension(UnittestProto.repeatedInt32Extension) + .getExtensionCount(UnittestProto.repeatedInt32Extension)); } public void testExtensionCopy() throws Exception { @@ -698,13 +672,12 @@ public class GeneratedMessageTest extends TestCase { public void testExtensionMergeFrom() throws Exception { TestAllExtensions original = - TestAllExtensions.newBuilder() - .setExtension(UnittestProto.optionalInt32Extension, 1).build(); - TestAllExtensions merged = - TestAllExtensions.newBuilder().mergeFrom(original).build(); + TestAllExtensions.newBuilder() + .setExtension(UnittestProto.optionalInt32Extension, 1) + .build(); + TestAllExtensions merged = TestAllExtensions.newBuilder().mergeFrom(original).build(); assertTrue(merged.hasExtension(UnittestProto.optionalInt32Extension)); - assertEquals( - 1, (int) merged.getExtension(UnittestProto.optionalInt32Extension)); + assertEquals(1, (int) merged.getExtension(UnittestProto.optionalInt32Extension)); } // ================================================================= @@ -715,64 +688,69 @@ public class GeneratedMessageTest extends TestCase { // or messages defined in multiple_files_test.proto because the class loading // order affects initialization process of custom options. public void testEnumValueOptionsInMultipleFilesMode() throws Exception { - assertEquals(12345, EnumWithNoOuter.FOO.getValueDescriptor().getOptions() - .getExtension(MultipleFilesTestProto.enumValueOption).intValue()); + assertEquals( + 12345, + EnumWithNoOuter.FOO + .getValueDescriptor() + .getOptions() + .getExtension(MultipleFilesTestProto.enumValueOption) + .intValue()); } public void testMultipleFilesOption() throws Exception { // We mostly just want to check that things compile. MessageWithNoOuter message = - MessageWithNoOuter.newBuilder() - .setNested(MessageWithNoOuter.NestedMessage.newBuilder().setI(1)) - .addForeign(TestAllTypes.newBuilder().setOptionalInt32(1)) - .setNestedEnum(MessageWithNoOuter.NestedEnum.BAZ) - .setForeignEnum(EnumWithNoOuter.BAR) - .build(); + MessageWithNoOuter.newBuilder() + .setNested(MessageWithNoOuter.NestedMessage.newBuilder().setI(1)) + .addForeign(TestAllTypes.newBuilder().setOptionalInt32(1)) + .setNestedEnum(MessageWithNoOuter.NestedEnum.BAZ) + .setForeignEnum(EnumWithNoOuter.BAR) + .build(); assertEquals(message, MessageWithNoOuter.parseFrom(message.toByteString())); - assertEquals(MultipleFilesTestProto.getDescriptor(), - MessageWithNoOuter.getDescriptor().getFile()); + assertEquals( + MultipleFilesTestProto.getDescriptor(), MessageWithNoOuter.getDescriptor().getFile()); Descriptors.FieldDescriptor field = - MessageWithNoOuter.getDescriptor().findFieldByName("foreign_enum"); - assertEquals(EnumWithNoOuter.BAR.getValueDescriptor(), - message.getField(field)); + MessageWithNoOuter.getDescriptor().findFieldByName("foreign_enum"); + assertEquals(EnumWithNoOuter.BAR.getValueDescriptor(), message.getField(field)); - assertEquals(MultipleFilesTestProto.getDescriptor(), - ServiceWithNoOuter.getDescriptor().getFile()); + assertEquals( + MultipleFilesTestProto.getDescriptor(), ServiceWithNoOuter.getDescriptor().getFile()); assertFalse( - TestAllExtensions.getDefaultInstance().hasExtension( - MultipleFilesTestProto.extensionWithOuter)); + TestAllExtensions.getDefaultInstance() + .hasExtension(MultipleFilesTestProto.extensionWithOuter)); } - public void testOptionalFieldWithRequiredSubfieldsOptimizedForSize() - throws Exception { - TestOptionalOptimizedForSize message = - TestOptionalOptimizedForSize.getDefaultInstance(); + public void testOptionalFieldWithRequiredSubfieldsOptimizedForSize() throws Exception { + TestOptionalOptimizedForSize message = TestOptionalOptimizedForSize.getDefaultInstance(); assertTrue(message.isInitialized()); - message = TestOptionalOptimizedForSize.newBuilder().setO( - TestRequiredOptimizedForSize.newBuilder().buildPartial() - ).buildPartial(); + message = + TestOptionalOptimizedForSize.newBuilder() + .setO(TestRequiredOptimizedForSize.newBuilder().buildPartial()) + .buildPartial(); assertFalse(message.isInitialized()); - message = TestOptionalOptimizedForSize.newBuilder().setO( - TestRequiredOptimizedForSize.newBuilder().setX(5).buildPartial() - ).buildPartial(); + message = + TestOptionalOptimizedForSize.newBuilder() + .setO(TestRequiredOptimizedForSize.newBuilder().setX(5).buildPartial()) + .buildPartial(); assertTrue(message.isInitialized()); } - public void testUninitializedExtensionInOptimizedForSize() - throws Exception { + public void testUninitializedExtensionInOptimizedForSize() throws Exception { TestOptimizedForSize.Builder builder = TestOptimizedForSize.newBuilder(); - builder.setExtension(TestOptimizedForSize.testExtension2, + builder.setExtension( + TestOptimizedForSize.testExtension2, TestRequiredOptimizedForSize.newBuilder().buildPartial()); assertFalse(builder.isInitialized()); assertFalse(builder.buildPartial().isInitialized()); builder = TestOptimizedForSize.newBuilder(); - builder.setExtension(TestOptimizedForSize.testExtension2, + builder.setExtension( + TestOptimizedForSize.testExtension2, TestRequiredOptimizedForSize.newBuilder().setX(10).buildPartial()); assertTrue(builder.isInitialized()); assertTrue(builder.buildPartial().isInitialized()); @@ -803,13 +781,11 @@ public class GeneratedMessageTest extends TestCase { assertEquals(UnittestProto.TestRequired.MULTI_FIELD_NUMBER, 1001); assertEquals(UnittestProto.OPTIONAL_INT32_EXTENSION_FIELD_NUMBER, 1); assertEquals(UnittestProto.OPTIONALGROUP_EXTENSION_FIELD_NUMBER, 16); - assertEquals( - UnittestProto.OPTIONAL_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 18); + assertEquals(UnittestProto.OPTIONAL_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 18); assertEquals(UnittestProto.OPTIONAL_NESTED_ENUM_EXTENSION_FIELD_NUMBER, 21); assertEquals(UnittestProto.REPEATED_INT32_EXTENSION_FIELD_NUMBER, 31); assertEquals(UnittestProto.REPEATEDGROUP_EXTENSION_FIELD_NUMBER, 46); - assertEquals( - UnittestProto.REPEATED_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 48); + assertEquals(UnittestProto.REPEATED_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 48); assertEquals(UnittestProto.REPEATED_NESTED_ENUM_EXTENSION_FIELD_NUMBER, 51); } @@ -818,7 +794,7 @@ public class GeneratedMessageTest extends TestCase { UnittestProto.TestRecursiveMessage.getDefaultInstance(); assertTrue(message != null); assertNotNull(message.getA()); - assertTrue(message.getA() == message); + assertTrue(message.getA().equals(message)); } public void testSerialize() throws Exception { @@ -859,21 +835,19 @@ public class GeneratedMessageTest extends TestCase { // just includes messageClassName and asBytes // Int32Value.newBuilder().setValue(123).build() - byte[] int32ValueBytes = new byte[]{ - -84, -19, 0, 5, 115, 114, 0, 55, 99, 111, 109, 46, 103, 111, 111, - 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 71, - 101, 110, 101, 114, 97, 116, 101, 100, 77, 101, 115, 115, 97, 103, - 101, 76, 105, 116, 101, 36, 83, 101, 114, 105, 97, 108, 105, 122, - 101, 100, 70, 111, 114, 109, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 91, - 0, 7, 97, 115, 66, 121, 116, 101, 115, 116, 0, 2, 91, 66, 76, 0, - 16, 109, 101, 115, 115, 97, 103, 101, 67, 108, 97, 115, 115, 78, - 97, 109, 101, 116, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, - 103, 47, 83, 116, 114, 105, 110, 103, 59, 120, 112, 117, 114, 0, - 2, 91, 66, -84, -13, 23, -8, 6, 8, 84, -32, 2, 0, 0, 120, 112, 0, - 0, 0, 2, 8, 123, 116, 0, 30, 99, 111, 109, 46, 103, 111, 111, 103, - 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 73, 110, - 116, 51, 50, 86, 97, 108, 117, 101 - }; + byte[] int32ValueBytes = + new byte[] { + -84, -19, 0, 5, 115, 114, 0, 55, 99, 111, 109, 46, 103, 111, 111, 103, 108, 101, 46, 112, + 114, 111, 116, 111, 98, 117, 102, 46, 71, 101, 110, 101, 114, 97, 116, 101, 100, 77, 101, + 115, 115, 97, 103, 101, 76, 105, 116, 101, 36, 83, 101, 114, 105, 97, 108, 105, 122, 101, + 100, 70, 111, 114, 109, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 91, 0, 7, 97, 115, 66, 121, 116, + 101, 115, 116, 0, 2, 91, 66, 76, 0, 16, 109, 101, 115, 115, 97, 103, 101, 67, 108, 97, + 115, 115, 78, 97, 109, 101, 116, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, + 83, 116, 114, 105, 110, 103, 59, 120, 112, 117, 114, 0, 2, 91, 66, -84, -13, 23, -8, 6, 8, + 84, -32, 2, 0, 0, 120, 112, 0, 0, 0, 2, 8, 123, 116, 0, 30, 99, 111, 109, 46, 103, 111, + 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 73, 110, 116, 51, 50, + 86, 97, 108, 117, 101 + }; ByteArrayInputStream bais = new ByteArrayInputStream(int32ValueBytes); ObjectInputStream in = new ObjectInputStream(bais); @@ -886,36 +860,30 @@ public class GeneratedMessageTest extends TestCase { // includes messageClass, messageClassName (for compatibility), and asBytes // Int32Value.newBuilder().setValue(123).build() - byte[] int32ValueBytes = new byte[]{ - -84, -19, 0, 5, 115, 114, 0, 55, 99, 111, 109, 46, 103, 111, 111, - 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 71, - 101, 110, 101, 114, 97, 116, 101, 100, 77, 101, 115, 115, 97, 103, - 101, 76, 105, 116, 101, 36, 83, 101, 114, 105, 97, 108, 105, 122, - 101, 100, 70, 111, 114, 109, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 91, - 0, 7, 97, 115, 66, 121, 116, 101, 115, 116, 0, 2, 91, 66, 76, 0, - 12, 109, 101, 115, 115, 97, 103, 101, 67, 108, 97, 115, 115, 116, - 0, 17, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 67, 108, - 97, 115, 115, 59, 76, 0, 16, 109, 101, 115, 115, 97, 103, 101, 67, - 108, 97, 115, 115, 78, 97, 109, 101, 116, 0, 18, 76, 106, 97, 118, - 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, - 120, 112, 117, 114, 0, 2, 91, 66, -84, -13, 23, -8, 6, 8, 84, -32, - 2, 0, 0, 120, 112, 0, 0, 0, 2, 8, 123, 118, 114, 0, 30, 99, 111, - 109, 46, 103, 111, 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, - 98, 117, 102, 46, 73, 110, 116, 51, 50, 86, 97, 108, 117, 101, 0, 0, - 0, 0, 0, 0, 0, 0, 2, 0, 2, 66, 0, 21, 109, 101, 109, 111, 105, 122, - 101, 100, 73, 115, 73, 110, 105, 116, 105, 97, 108, 105, 122, 101, - 100, 73, 0, 6, 118, 97, 108, 117, 101, 95, 120, 114, 0, 38, 99, 111, - 109, 46, 103, 111, 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, - 98, 117, 102, 46, 71, 101, 110, 101, 114, 97, 116, 101, 100, 77, - 101, 115, 115, 97, 103, 101, 86, 51, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, - 1, 76, 0, 13, 117, 110, 107, 110, 111, 119, 110, 70, 105, 101, 108, - 100, 115, 116, 0, 37, 76, 99, 111, 109, 47, 103, 111, 111, 103, 108, - 101, 47, 112, 114, 111, 116, 111, 98, 117, 102, 47, 85, 110, 107, - 110, 111, 119, 110, 70, 105, 101, 108, 100, 83, 101, 116, 59, 120, - 112, 116, 0, 30, 99, 111, 109, 46, 103, 111, 111, 103, 108, 101, 46, - 112, 114, 111, 116, 111, 98, 117, 102, 46, 73, 110, 116, 51, 50, 86, - 97, 108, 117, 101 - }; + byte[] int32ValueBytes = + new byte[] { + -84, -19, 0, 5, 115, 114, 0, 55, 99, 111, 109, 46, 103, 111, 111, 103, 108, 101, 46, 112, + 114, 111, 116, 111, 98, 117, 102, 46, 71, 101, 110, 101, 114, 97, 116, 101, 100, 77, 101, + 115, 115, 97, 103, 101, 76, 105, 116, 101, 36, 83, 101, 114, 105, 97, 108, 105, 122, 101, + 100, 70, 111, 114, 109, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 91, 0, 7, 97, 115, 66, 121, 116, + 101, 115, 116, 0, 2, 91, 66, 76, 0, 12, 109, 101, 115, 115, 97, 103, 101, 67, 108, 97, + 115, 115, 116, 0, 17, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 67, 108, 97, 115, + 115, 59, 76, 0, 16, 109, 101, 115, 115, 97, 103, 101, 67, 108, 97, 115, 115, 78, 97, 109, + 101, 116, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, + 103, 59, 120, 112, 117, 114, 0, 2, 91, 66, -84, -13, 23, -8, 6, 8, 84, -32, 2, 0, 0, 120, + 112, 0, 0, 0, 2, 8, 123, 118, 114, 0, 30, 99, 111, 109, 46, 103, 111, 111, 103, 108, 101, + 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 73, 110, 116, 51, 50, 86, 97, 108, 117, + 101, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 66, 0, 21, 109, 101, 109, 111, 105, 122, 101, 100, + 73, 115, 73, 110, 105, 116, 105, 97, 108, 105, 122, 101, 100, 73, 0, 6, 118, 97, 108, 117, + 101, 95, 120, 114, 0, 38, 99, 111, 109, 46, 103, 111, 111, 103, 108, 101, 46, 112, 114, + 111, 116, 111, 98, 117, 102, 46, 71, 101, 110, 101, 114, 97, 116, 101, 100, 77, 101, 115, + 115, 97, 103, 101, 86, 51, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 1, 76, 0, 13, 117, 110, 107, 110, + 111, 119, 110, 70, 105, 101, 108, 100, 115, 116, 0, 37, 76, 99, 111, 109, 47, 103, 111, + 111, 103, 108, 101, 47, 112, 114, 111, 116, 111, 98, 117, 102, 47, 85, 110, 107, 110, 111, + 119, 110, 70, 105, 101, 108, 100, 83, 101, 116, 59, 120, 112, 116, 0, 30, 99, 111, 109, + 46, 103, 111, 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 73, 110, + 116, 51, 50, 86, 97, 108, 117, 101 + }; ByteArrayInputStream bais = new ByteArrayInputStream(int32ValueBytes); ObjectInputStream in = new ObjectInputStream(bais); @@ -930,33 +898,33 @@ public class GeneratedMessageTest extends TestCase { } public void testNonNestedExtensionInitialization() { - assertTrue(NonNestedExtension.nonNestedExtension - .getMessageDefaultInstance() instanceof MyNonNestedExtension); - assertEquals("nonNestedExtension", - NonNestedExtension.nonNestedExtension.getDescriptor().getName()); + assertTrue( + NonNestedExtension.nonNestedExtension.getMessageDefaultInstance() + instanceof MyNonNestedExtension); + assertEquals( + "nonNestedExtension", NonNestedExtension.nonNestedExtension.getDescriptor().getName()); } public void testNestedExtensionInitialization() { - assertTrue(MyNestedExtension.recursiveExtension.getMessageDefaultInstance() - instanceof MessageToBeExtended); - assertEquals("recursiveExtension", - MyNestedExtension.recursiveExtension.getDescriptor().getName()); + assertTrue( + MyNestedExtension.recursiveExtension.getMessageDefaultInstance() + instanceof MessageToBeExtended); + assertEquals( + "recursiveExtension", MyNestedExtension.recursiveExtension.getDescriptor().getName()); } public void testInvalidations() throws Exception { GeneratedMessage.enableAlwaysUseFieldBuildersForTesting(); - TestAllTypes.NestedMessage nestedMessage1 = - TestAllTypes.NestedMessage.newBuilder().build(); - TestAllTypes.NestedMessage nestedMessage2 = - TestAllTypes.NestedMessage.newBuilder().build(); + TestAllTypes.NestedMessage nestedMessage1 = TestAllTypes.NestedMessage.newBuilder().build(); + TestAllTypes.NestedMessage nestedMessage2 = TestAllTypes.NestedMessage.newBuilder().build(); // Set all three flavors (enum, primitive, message and singular/repeated) // and verify no invalidations fired TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent(); - TestAllTypes.Builder builder = (TestAllTypes.Builder) - ((AbstractMessage) TestAllTypes.getDefaultInstance()). - newBuilderForType(mockParent); + TestAllTypes.Builder builder = + (TestAllTypes.Builder) + ((AbstractMessage) TestAllTypes.getDefaultInstance()).newBuilderForType(mockParent); builder.setOptionalInt32(1); builder.setOptionalNestedEnum(TestAllTypes.NestedEnum.BAR); builder.setOptionalNestedMessage(nestedMessage1); @@ -1003,15 +971,15 @@ public class GeneratedMessageTest extends TestCase { builder.addRepeatedNestedMessage(nestedMessage2); builder.addRepeatedNestedMessage(nestedMessage1); assertEquals(6, mockParent.getInvalidationCount()); - } public void testInvalidations_Extensions() throws Exception { TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent(); - TestAllExtensions.Builder builder = (TestAllExtensions.Builder) - ((AbstractMessage) TestAllExtensions.getDefaultInstance()). - newBuilderForType(mockParent); + TestAllExtensions.Builder builder = + (TestAllExtensions.Builder) + ((AbstractMessage) TestAllExtensions.getDefaultInstance()) + .newBuilderForType(mockParent); builder.addExtension(UnittestProto.repeatedInt32Extension, 1); builder.setExtension(UnittestProto.repeatedInt32Extension, 0, 2); @@ -1039,25 +1007,19 @@ public class GeneratedMessageTest extends TestCase { // Mostly just makes sure the base interface exists and has some methods. TestAllTypes.Builder builder = TestAllTypes.newBuilder(); TestAllTypes message = builder.buildPartial(); - TestAllTypesOrBuilder builderAsInterface = (TestAllTypesOrBuilder) builder; TestAllTypesOrBuilder messageAsInterface = (TestAllTypesOrBuilder) message; + assertEquals(messageAsInterface.getDefaultBool(), messageAsInterface.getDefaultBool()); assertEquals( - messageAsInterface.getDefaultBool(), - messageAsInterface.getDefaultBool()); - assertEquals( - messageAsInterface.getOptionalDouble(), - messageAsInterface.getOptionalDouble()); + messageAsInterface.getOptionalDouble(), messageAsInterface.getOptionalDouble(), 0.0); } public void testMessageOrBuilderGetters() { TestAllTypes.Builder builder = TestAllTypes.newBuilder(); // single fields - assertSame(ForeignMessage.getDefaultInstance(), - builder.getOptionalForeignMessageOrBuilder()); - ForeignMessage.Builder subBuilder = - builder.getOptionalForeignMessageBuilder(); + assertSame(ForeignMessage.getDefaultInstance(), builder.getOptionalForeignMessageOrBuilder()); + ForeignMessage.Builder subBuilder = builder.getOptionalForeignMessageBuilder(); assertSame(subBuilder, builder.getOptionalForeignMessageOrBuilder()); // repeated fields @@ -1086,36 +1048,37 @@ public class GeneratedMessageTest extends TestCase { public void testGetFieldBuilder() { Descriptor descriptor = TestAllTypes.getDescriptor(); - FieldDescriptor fieldDescriptor = - descriptor.findFieldByName("optional_nested_message"); - FieldDescriptor foreignFieldDescriptor = - descriptor.findFieldByName("optional_foreign_message"); - FieldDescriptor importFieldDescriptor = - descriptor.findFieldByName("optional_import_message"); + FieldDescriptor fieldDescriptor = descriptor.findFieldByName("optional_nested_message"); + FieldDescriptor foreignFieldDescriptor = descriptor.findFieldByName("optional_foreign_message"); + FieldDescriptor importFieldDescriptor = descriptor.findFieldByName("optional_import_message"); // Mutate the message with new field builder // Mutate nested message TestAllTypes.Builder builder1 = TestAllTypes.newBuilder(); - Message.Builder fieldBuilder1 = builder1.newBuilderForField(fieldDescriptor) - .mergeFrom((Message) builder1.getField(fieldDescriptor)); + Message.Builder fieldBuilder1 = + builder1 + .newBuilderForField(fieldDescriptor) + .mergeFrom((Message) builder1.getField(fieldDescriptor)); FieldDescriptor subFieldDescriptor1 = fieldBuilder1.getDescriptorForType().findFieldByName("bb"); fieldBuilder1.setField(subFieldDescriptor1, 1); builder1.setField(fieldDescriptor, fieldBuilder1.build()); // Mutate foreign message - Message.Builder foreignFieldBuilder1 = builder1.newBuilderForField( - foreignFieldDescriptor) - .mergeFrom((Message) builder1.getField(foreignFieldDescriptor)); + Message.Builder foreignFieldBuilder1 = + builder1 + .newBuilderForField(foreignFieldDescriptor) + .mergeFrom((Message) builder1.getField(foreignFieldDescriptor)); FieldDescriptor subForeignFieldDescriptor1 = foreignFieldBuilder1.getDescriptorForType().findFieldByName("c"); foreignFieldBuilder1.setField(subForeignFieldDescriptor1, 2); builder1.setField(foreignFieldDescriptor, foreignFieldBuilder1.build()); // Mutate import message - Message.Builder importFieldBuilder1 = builder1.newBuilderForField( - importFieldDescriptor) - .mergeFrom((Message) builder1.getField(importFieldDescriptor)); + Message.Builder importFieldBuilder1 = + builder1 + .newBuilderForField(importFieldDescriptor) + .mergeFrom((Message) builder1.getField(importFieldDescriptor)); FieldDescriptor subImportFieldDescriptor1 = importFieldBuilder1.getDescriptorForType().findFieldByName("d"); importFieldBuilder1.setField(subImportFieldDescriptor1, 3); @@ -1133,18 +1096,20 @@ public class GeneratedMessageTest extends TestCase { builder2.setField(fieldDescriptor, fieldBuilder2.build()); // Mutate foreign message - Message.Builder foreignFieldBuilder2 = builder2.newBuilderForField( - foreignFieldDescriptor) - .mergeFrom((Message) builder2.getField(foreignFieldDescriptor)); + Message.Builder foreignFieldBuilder2 = + builder2 + .newBuilderForField(foreignFieldDescriptor) + .mergeFrom((Message) builder2.getField(foreignFieldDescriptor)); FieldDescriptor subForeignFieldDescriptor2 = foreignFieldBuilder2.getDescriptorForType().findFieldByName("c"); foreignFieldBuilder2.setField(subForeignFieldDescriptor2, 2); builder2.setField(foreignFieldDescriptor, foreignFieldBuilder2.build()); // Mutate import message - Message.Builder importFieldBuilder2 = builder2.newBuilderForField( - importFieldDescriptor) - .mergeFrom((Message) builder2.getField(importFieldDescriptor)); + Message.Builder importFieldBuilder2 = + builder2 + .newBuilderForField(importFieldDescriptor) + .mergeFrom((Message) builder2.getField(importFieldDescriptor)); FieldDescriptor subImportFieldDescriptor2 = importFieldBuilder2.getDescriptorForType().findFieldByName("d"); importFieldBuilder2.setField(subImportFieldDescriptor2, 3); @@ -1158,10 +1123,9 @@ public class GeneratedMessageTest extends TestCase { public void testGetFieldBuilderWithInitializedValue() { Descriptor descriptor = TestAllTypes.getDescriptor(); - FieldDescriptor fieldDescriptor = - descriptor.findFieldByName("optional_nested_message"); + FieldDescriptor fieldDescriptor = descriptor.findFieldByName("optional_nested_message"); - // Before setting field, builder is initialized by default value. + // Before setting field, builder is initialized by default value. TestAllTypes.Builder builder = TestAllTypes.newBuilder(); NestedMessage.Builder fieldBuilder = (NestedMessage.Builder) builder.getFieldBuilder(fieldDescriptor); @@ -1169,12 +1133,10 @@ public class GeneratedMessageTest extends TestCase { // Setting field value with new field builder instance. builder = TestAllTypes.newBuilder(); - NestedMessage.Builder newFieldBuilder = - builder.getOptionalNestedMessageBuilder(); + NestedMessage.Builder newFieldBuilder = builder.getOptionalNestedMessageBuilder(); newFieldBuilder.setBb(2); // Then get the field builder instance by getFieldBuilder(). - fieldBuilder = - (NestedMessage.Builder) builder.getFieldBuilder(fieldDescriptor); + fieldBuilder = (NestedMessage.Builder) builder.getFieldBuilder(fieldDescriptor); // It should contain new value. assertEquals(2, fieldBuilder.getBb()); // These two builder should be equal. @@ -1191,8 +1153,7 @@ public class GeneratedMessageTest extends TestCase { // We expect this exception. } try { - builder.getFieldBuilder( - descriptor.findFieldByName("optional_nested_enum")); + builder.getFieldBuilder(descriptor.findFieldByName("optional_nested_enum")); fail("Exception was not thrown"); } catch (UnsupportedOperationException e) { // We expect this exception. @@ -1204,15 +1165,13 @@ public class GeneratedMessageTest extends TestCase { // We expect this exception. } try { - builder.getFieldBuilder( - descriptor.findFieldByName("repeated_nested_enum")); + builder.getFieldBuilder(descriptor.findFieldByName("repeated_nested_enum")); fail("Exception was not thrown"); } catch (UnsupportedOperationException e) { // We expect this exception. } try { - builder.getFieldBuilder( - descriptor.findFieldByName("repeated_nested_message")); + builder.getFieldBuilder(descriptor.findFieldByName("repeated_nested_message")); fail("Exception was not thrown"); } catch (UnsupportedOperationException e) { // We expect this exception. @@ -1227,25 +1186,25 @@ public class GeneratedMessageTest extends TestCase { // expected name. There is nothing else to test. OuterClassNameTestOuterClass.OuterClassNameTest message = OuterClassNameTestOuterClass.OuterClassNameTest.newBuilder().build(); - assertTrue(message.getDescriptorForType() == - OuterClassNameTestOuterClass.OuterClassNameTest.getDescriptor()); + assertTrue( + message.getDescriptorForType() + == OuterClassNameTestOuterClass.OuterClassNameTest.getDescriptor()); - OuterClassNameTest2OuterClass.TestMessage2.NestedMessage.OuterClassNameTest2 - message2 = OuterClassNameTest2OuterClass.TestMessage2.NestedMessage - .OuterClassNameTest2.newBuilder().build(); + OuterClassNameTest2OuterClass.TestMessage2.NestedMessage.OuterClassNameTest2 message2 = + OuterClassNameTest2OuterClass.TestMessage2.NestedMessage.OuterClassNameTest2.newBuilder() + .build(); assertEquals(0, message2.getSerializedSize()); - OuterClassNameTest3OuterClass.TestMessage3.NestedMessage.OuterClassNameTest3 - enumValue = OuterClassNameTest3OuterClass.TestMessage3.NestedMessage - .OuterClassNameTest3.DUMMY_VALUE; + OuterClassNameTest3OuterClass.TestMessage3.NestedMessage.OuterClassNameTest3 enumValue = + OuterClassNameTest3OuterClass.TestMessage3.NestedMessage.OuterClassNameTest3.DUMMY_VALUE; assertEquals(1, enumValue.getNumber()); } // ================================================================= // oneof generated code test public void testOneofEnumCase() throws Exception { - TestOneof2 message = TestOneof2.newBuilder() - .setFooInt(123).setFooString("foo").setFooCord("bar").build(); + TestOneof2 message = + TestOneof2.newBuilder().setFooInt(123).setFooString("foo").setFooCord("bar").build(); TestUtil.assertAtMostOneFieldSetOneof(message); } @@ -1258,8 +1217,7 @@ public class GeneratedMessageTest extends TestCase { public void testSetOneofClearsOthers() throws Exception { TestOneof2.Builder builder = TestOneof2.newBuilder(); - TestOneof2 message = - builder.setFooInt(123).setFooString("foo").buildPartial(); + TestOneof2 message = builder.setFooInt(123).setFooString("foo").buildPartial(); assertTrue(message.hasFooString()); TestUtil.assertAtMostOneFieldSetOneof(message); @@ -1279,8 +1237,10 @@ public class GeneratedMessageTest extends TestCase { assertTrue(message.hasFooEnum()); TestUtil.assertAtMostOneFieldSetOneof(message); - message = builder.setFooMessage( - TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()).buildPartial(); + message = + builder + .setFooMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()) + .buildPartial(); assertTrue(message.hasFooMessage()); TestUtil.assertAtMostOneFieldSetOneof(message); @@ -1396,8 +1356,7 @@ public class GeneratedMessageTest extends TestCase { // set TestOneof2.Builder builder = TestOneof2.newBuilder(); assertEquals(0, builder.getFooMessage().getQuxInt()); - builder.setFooMessage( - TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()); + builder.setFooMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()); assertTrue(builder.hasFooMessage()); assertEquals(234, builder.getFooMessage().getQuxInt()); TestOneof2 message = builder.buildPartial(); @@ -1412,8 +1371,7 @@ public class GeneratedMessageTest extends TestCase { // nested builder builder = TestOneof2.newBuilder(); - assertSame(builder.getFooMessageOrBuilder(), - TestOneof2.NestedMessage.getDefaultInstance()); + assertSame(builder.getFooMessageOrBuilder(), TestOneof2.NestedMessage.getDefaultInstance()); assertFalse(builder.hasFooMessage()); builder.getFooMessageBuilder().setQuxInt(123); assertTrue(builder.hasFooMessage()); @@ -1457,8 +1415,10 @@ public class GeneratedMessageTest extends TestCase { // Message { TestOneof2.Builder builder = TestOneof2.newBuilder(); - TestOneof2 message = builder.setFooMessage( - TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()).build(); + TestOneof2 message = + builder + .setFooMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()) + .build(); TestOneof2 message2 = TestOneof2.newBuilder().mergeFrom(message).build(); assertTrue(message2.hasFooMessage()); assertEquals(234, message2.getFooMessage().getQuxInt()); @@ -1499,8 +1459,10 @@ public class GeneratedMessageTest extends TestCase { // Message { TestOneof2.Builder builder = TestOneof2.newBuilder(); - TestOneof2 message = builder.setFooMessage( - TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()).build(); + TestOneof2 message = + builder + .setFooMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()) + .build(); ByteString serialized = message.toByteString(); TestOneof2 message2 = TestOneof2.parseFrom(serialized); assertTrue(message2.hasFooMessage()); @@ -1522,40 +1484,32 @@ public class GeneratedMessageTest extends TestCase { public void testGetRepeatedFieldBuilder() { Descriptor descriptor = TestAllTypes.getDescriptor(); - FieldDescriptor fieldDescriptor = - descriptor.findFieldByName("repeated_nested_message"); - FieldDescriptor foreignFieldDescriptor = - descriptor.findFieldByName("repeated_foreign_message"); - FieldDescriptor importFieldDescriptor = - descriptor.findFieldByName("repeated_import_message"); + FieldDescriptor fieldDescriptor = descriptor.findFieldByName("repeated_nested_message"); + FieldDescriptor foreignFieldDescriptor = descriptor.findFieldByName("repeated_foreign_message"); + FieldDescriptor importFieldDescriptor = descriptor.findFieldByName("repeated_import_message"); // Mutate the message with new field builder // Mutate nested message TestAllTypes.Builder builder1 = TestAllTypes.newBuilder(); - Message.Builder fieldBuilder1 = builder1.newBuilderForField( - fieldDescriptor); + Message.Builder fieldBuilder1 = builder1.newBuilderForField(fieldDescriptor); FieldDescriptor subFieldDescriptor1 = fieldBuilder1.getDescriptorForType().findFieldByName("bb"); fieldBuilder1.setField(subFieldDescriptor1, 1); builder1.addRepeatedField(fieldDescriptor, fieldBuilder1.build()); // Mutate foreign message - Message.Builder foreignFieldBuilder1 = builder1.newBuilderForField( - foreignFieldDescriptor); + Message.Builder foreignFieldBuilder1 = builder1.newBuilderForField(foreignFieldDescriptor); FieldDescriptor subForeignFieldDescriptor1 = foreignFieldBuilder1.getDescriptorForType().findFieldByName("c"); foreignFieldBuilder1.setField(subForeignFieldDescriptor1, 2); - builder1.addRepeatedField(foreignFieldDescriptor, - foreignFieldBuilder1.build()); + builder1.addRepeatedField(foreignFieldDescriptor, foreignFieldBuilder1.build()); // Mutate import message - Message.Builder importFieldBuilder1 = builder1.newBuilderForField( - importFieldDescriptor); + Message.Builder importFieldBuilder1 = builder1.newBuilderForField(importFieldDescriptor); FieldDescriptor subImportFieldDescriptor1 = importFieldBuilder1.getDescriptorForType().findFieldByName("d"); importFieldBuilder1.setField(subImportFieldDescriptor1, 3); - builder1.addRepeatedField(importFieldDescriptor, - importFieldBuilder1.build()); + builder1.addRepeatedField(importFieldDescriptor, importFieldBuilder1.build()); Message newMessage1 = builder1.build(); @@ -1563,29 +1517,24 @@ public class GeneratedMessageTest extends TestCase { // Mutate nested message TestAllTypes.Builder builder2 = TestAllTypes.newBuilder(); builder2.addRepeatedNestedMessageBuilder(); - Message.Builder fieldBuilder2 = builder2.getRepeatedFieldBuilder( - fieldDescriptor, 0); + Message.Builder fieldBuilder2 = builder2.getRepeatedFieldBuilder(fieldDescriptor, 0); FieldDescriptor subFieldDescriptor2 = fieldBuilder2.getDescriptorForType().findFieldByName("bb"); fieldBuilder2.setField(subFieldDescriptor2, 1); // Mutate foreign message - Message.Builder foreignFieldBuilder2 = builder2.newBuilderForField( - foreignFieldDescriptor); + Message.Builder foreignFieldBuilder2 = builder2.newBuilderForField(foreignFieldDescriptor); FieldDescriptor subForeignFieldDescriptor2 = foreignFieldBuilder2.getDescriptorForType().findFieldByName("c"); foreignFieldBuilder2.setField(subForeignFieldDescriptor2, 2); - builder2.addRepeatedField(foreignFieldDescriptor, - foreignFieldBuilder2.build()); + builder2.addRepeatedField(foreignFieldDescriptor, foreignFieldBuilder2.build()); // Mutate import message - Message.Builder importFieldBuilder2 = builder2.newBuilderForField( - importFieldDescriptor); + Message.Builder importFieldBuilder2 = builder2.newBuilderForField(importFieldDescriptor); FieldDescriptor subImportFieldDescriptor2 = importFieldBuilder2.getDescriptorForType().findFieldByName("d"); importFieldBuilder2.setField(subImportFieldDescriptor2, 3); - builder2.addRepeatedField(importFieldDescriptor, - importFieldBuilder2.build()); + builder2.addRepeatedField(importFieldDescriptor, importFieldBuilder2.build()); Message newMessage2 = builder2.build(); @@ -1595,10 +1544,9 @@ public class GeneratedMessageTest extends TestCase { public void testGetRepeatedFieldBuilderWithInitializedValue() { Descriptor descriptor = TestAllTypes.getDescriptor(); - FieldDescriptor fieldDescriptor = - descriptor.findFieldByName("repeated_nested_message"); + FieldDescriptor fieldDescriptor = descriptor.findFieldByName("repeated_nested_message"); - // Before setting field, builder is initialized by default value. + // Before setting field, builder is initialized by default value. TestAllTypes.Builder builder = TestAllTypes.newBuilder(); builder.addRepeatedNestedMessageBuilder(); NestedMessage.Builder fieldBuilder = @@ -1607,12 +1555,10 @@ public class GeneratedMessageTest extends TestCase { // Setting field value with new field builder instance. builder = TestAllTypes.newBuilder(); - NestedMessage.Builder newFieldBuilder = - builder.addRepeatedNestedMessageBuilder(); + NestedMessage.Builder newFieldBuilder = builder.addRepeatedNestedMessageBuilder(); newFieldBuilder.setBb(2); // Then get the field builder instance by getRepeatedFieldBuilder(). - fieldBuilder = - (NestedMessage.Builder) builder.getRepeatedFieldBuilder(fieldDescriptor, 0); + fieldBuilder = (NestedMessage.Builder) builder.getRepeatedFieldBuilder(fieldDescriptor, 0); // It should contain new value. assertEquals(2, fieldBuilder.getBb()); // These two builder should be equal. @@ -1629,8 +1575,7 @@ public class GeneratedMessageTest extends TestCase { // We expect this exception. } try { - builder.getRepeatedFieldBuilder( - descriptor.findFieldByName("repeated_nested_enum"), 0); + builder.getRepeatedFieldBuilder(descriptor.findFieldByName("repeated_nested_enum"), 0); fail("Exception was not thrown"); } catch (UnsupportedOperationException e) { // We expect this exception. @@ -1642,15 +1587,13 @@ public class GeneratedMessageTest extends TestCase { // We expect this exception. } try { - builder.getRepeatedFieldBuilder( - descriptor.findFieldByName("optional_nested_enum"), 0); + builder.getRepeatedFieldBuilder(descriptor.findFieldByName("optional_nested_enum"), 0); fail("Exception was not thrown"); } catch (UnsupportedOperationException e) { // We expect this exception. } try { - builder.getRepeatedFieldBuilder( - descriptor.findFieldByName("optional_nested_message"), 0); + builder.getRepeatedFieldBuilder(descriptor.findFieldByName("optional_nested_message"), 0); fail("Exception was not thrown"); } catch (UnsupportedOperationException e) { // We expect this exception. diff --git a/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java b/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java index 9edc43441c..d6943e0243 100644 --- a/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java +++ b/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java @@ -45,10 +45,8 @@ import junit.framework.TestCase; */ public class IntArrayListTest extends TestCase { - private static final IntArrayList UNARY_LIST = - newImmutableIntArrayList(1); - private static final IntArrayList TERTIARY_LIST = - newImmutableIntArrayList(1, 2, 3); + private static final IntArrayList UNARY_LIST = newImmutableIntArrayList(1); + private static final IntArrayList TERTIARY_LIST = newImmutableIntArrayList(1, 2, 3); private IntArrayList list; @@ -225,9 +223,7 @@ public class IntArrayListTest extends TestCase { for (int i = 0; i < 6; i++) { list.add(Integer.valueOf(5 + i)); } - assertEquals( - asList(0, 1, 4, 2, 3, 5, 6, 7, 8, 9, 10), - list); + assertEquals(asList(0, 1, 4, 2, 3, 5, 6, 7, 8, 9, 10), list); try { list.add(-1, 5); @@ -299,16 +295,14 @@ public class IntArrayListTest extends TestCase { } public void testRemoveEndOfCapacity() { - IntList toRemove = - IntArrayList.emptyList().mutableCopyWithCapacity(1); + IntList toRemove = IntArrayList.emptyList().mutableCopyWithCapacity(1); toRemove.addInt(3); toRemove.remove(0); assertEquals(0, toRemove.size()); } public void testSublistRemoveEndOfCapacity() { - IntList toRemove = - IntArrayList.emptyList().mutableCopyWithCapacity(1); + IntList toRemove = IntArrayList.emptyList().mutableCopyWithCapacity(1); toRemove.addInt(3); toRemove.subList(0, 1).clear(); assertEquals(0, toRemove.size()); diff --git a/java/core/src/test/java/com/google/protobuf/IsValidUtf8Test.java b/java/core/src/test/java/com/google/protobuf/IsValidUtf8Test.java index 756049b41f..2518f20dd6 100644 --- a/java/core/src/test/java/com/google/protobuf/IsValidUtf8Test.java +++ b/java/core/src/test/java/com/google/protobuf/IsValidUtf8Test.java @@ -39,45 +39,36 @@ import static com.google.protobuf.IsValidUtf8TestUtil.testBytes; import com.google.protobuf.IsValidUtf8TestUtil.ByteStringFactory; import com.google.protobuf.IsValidUtf8TestUtil.Shard; - import junit.framework.TestCase; /** - * Tests cases for {@link ByteString#isValidUtf8()}. This includes three - * brute force tests that actually test every permutation of one byte, two byte, - * and three byte sequences to ensure that the method produces the right result - * for every possible byte encoding where "right" means it's consistent with - * java's UTF-8 string encoding/decoding such that the method returns true for - * any sequence that will round trip when converted to a String and then back to - * bytes and will return false for any sequence that will not round trip. - * See also {@link IsValidUtf8FourByteTest}. It also includes some - * other more targeted tests. + * Tests cases for {@link ByteString#isValidUtf8()}. This includes three brute force tests that + * actually test every permutation of one byte, two byte, and three byte sequences to ensure that + * the method produces the right result for every possible byte encoding where "right" means it's + * consistent with java's UTF-8 string encoding/decoding such that the method returns true for any + * sequence that will round trip when converted to a String and then back to bytes and will return + * false for any sequence that will not round trip. See also {@link IsValidUtf8FourByteTest}. It + * also includes some other more targeted tests. * * @author jonp@google.com (Jon Perlow) * @author martinrb@google.com (Martin Buchholz) */ public class IsValidUtf8Test extends TestCase { - /** - * Tests that round tripping of all two byte permutations work. - */ + /** Tests that round tripping of all two byte permutations work. */ public void testIsValidUtf8_1Byte() { testBytes(LITERAL_FACTORY, 1, EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT); testBytes(HEAP_NIO_FACTORY, 1, EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT); testBytes(DIRECT_NIO_FACTORY, 1, EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT); } - /** - * Tests that round tripping of all two byte permutations work. - */ + /** Tests that round tripping of all two byte permutations work. */ public void testIsValidUtf8_2Bytes() { testBytes(LITERAL_FACTORY, 2, IsValidUtf8TestUtil.EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT); testBytes(HEAP_NIO_FACTORY, 2, IsValidUtf8TestUtil.EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT); testBytes(DIRECT_NIO_FACTORY, 2, IsValidUtf8TestUtil.EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT); } - /** - * Tests that round tripping of all three byte permutations work. - */ + /** Tests that round tripping of all three byte permutations work. */ public void testIsValidUtf8_3Bytes() { // Travis' OOM killer doesn't like this test if (System.getenv("TRAVIS") == null) { @@ -88,10 +79,9 @@ public class IsValidUtf8Test extends TestCase { } /** - * Tests that round tripping of a sample of four byte permutations work. - * All permutations are prohibitively expensive to test for automated runs; - * {@link IsValidUtf8FourByteTest} is used for full coverage. This method - * tests specific four-byte cases. + * Tests that round tripping of a sample of four byte permutations work. All permutations are + * prohibitively expensive to test for automated runs; {@link IsValidUtf8FourByteTest} is used for + * full coverage. This method tests specific four-byte cases. */ public void testIsValidUtf8_4BytesSamples() { // Valid 4 byte. @@ -106,9 +96,7 @@ public class IsValidUtf8Test extends TestCase { assertInvalidUtf8(0xF4, 0x90, 0xAD, 0xA2); } - /** - * Tests some hard-coded test cases. - */ + /** Tests some hard-coded test cases. */ public void testSomeSequences() { // Empty assertTrue(asBytes("").isValidUtf8()); @@ -149,11 +137,12 @@ public class IsValidUtf8Test extends TestCase { assertTrue(not ^ leaf.isValidUtf8()); assertTrue(not ^ sub.isValidUtf8()); ByteString[] ropes = { - RopeByteString.newInstanceForTest(ByteString.EMPTY, leaf), - RopeByteString.newInstanceForTest(ByteString.EMPTY, sub), - RopeByteString.newInstanceForTest(leaf, ByteString.EMPTY), - RopeByteString.newInstanceForTest(sub, ByteString.EMPTY), - RopeByteString.newInstanceForTest(sub, leaf)}; + RopeByteString.newInstanceForTest(ByteString.EMPTY, leaf), + RopeByteString.newInstanceForTest(ByteString.EMPTY, sub), + RopeByteString.newInstanceForTest(leaf, ByteString.EMPTY), + RopeByteString.newInstanceForTest(sub, ByteString.EMPTY), + RopeByteString.newInstanceForTest(sub, leaf) + }; for (ByteString rope : ropes) { assertTrue(not ^ rope.isValidUtf8()); } diff --git a/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java b/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java index 1bcf63e7d9..2c086e11b5 100644 --- a/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java +++ b/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java @@ -50,8 +50,7 @@ import java.util.Random; import java.util.logging.Logger; /** - * Shared testing code for {@link IsValidUtf8Test} and - * {@link IsValidUtf8FourByteTest}. + * Shared testing code for {@link IsValidUtf8Test} and {@link IsValidUtf8FourByteTest}. * * @author jonp@google.com (Jon Perlow) * @author martinrb@google.com (Martin Buchholz) @@ -65,44 +64,47 @@ final class IsValidUtf8TestUtil { ByteString newByteString(byte[] bytes); } - static final ByteStringFactory LITERAL_FACTORY = new ByteStringFactory() { - @Override - public ByteString newByteString(byte[] bytes) { - return ByteString.wrap(bytes); - } - }; + static final ByteStringFactory LITERAL_FACTORY = + new ByteStringFactory() { + @Override + public ByteString newByteString(byte[] bytes) { + return ByteString.wrap(bytes); + } + }; - static final ByteStringFactory HEAP_NIO_FACTORY = new ByteStringFactory() { - @Override - public ByteString newByteString(byte[] bytes) { - return new NioByteString(ByteBuffer.wrap(bytes)); - } - }; + static final ByteStringFactory HEAP_NIO_FACTORY = + new ByteStringFactory() { + @Override + public ByteString newByteString(byte[] bytes) { + return new NioByteString(ByteBuffer.wrap(bytes)); + } + }; private static ThreadLocal> directBuffer = new ThreadLocal>(); /** - * Factory for direct {@link ByteBuffer} instances. To reduce direct memory usage, this - * uses a thread local direct buffer. This means that each call will overwrite the buffer's - * contents from the previous call, so the calling code must be careful not to continue using - * a buffer returned from a previous invocation. + * Factory for direct {@link ByteBuffer} instances. To reduce direct memory usage, this uses a + * thread local direct buffer. This means that each call will overwrite the buffer's contents from + * the previous call, so the calling code must be careful not to continue using a buffer returned + * from a previous invocation. */ - static final ByteStringFactory DIRECT_NIO_FACTORY = new ByteStringFactory() { - @Override - public ByteString newByteString(byte[] bytes) { - SoftReference ref = directBuffer.get(); - ByteBuffer buffer = ref == null ? null : ref.get(); - if (buffer == null || buffer.capacity() < bytes.length) { - buffer = ByteBuffer.allocateDirect(bytes.length); - directBuffer.set(new SoftReference(buffer)); - } - buffer.clear(); - buffer.put(bytes); - buffer.flip(); - return new NioByteString(buffer); - } - }; + static final ByteStringFactory DIRECT_NIO_FACTORY = + new ByteStringFactory() { + @Override + public ByteString newByteString(byte[] bytes) { + SoftReference ref = directBuffer.get(); + ByteBuffer buffer = ref == null ? null : ref.get(); + if (buffer == null || buffer.capacity() < bytes.length) { + buffer = ByteBuffer.allocateDirect(bytes.length); + directBuffer.set(new SoftReference(buffer)); + } + buffer.clear(); + buffer.put(bytes); + buffer.flip(); + return new NioByteString(buffer); + } + }; // 128 - [chars 0x0000 to 0x007f] static final long ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS = 0x007f - 0x0000 + 1; @@ -116,9 +118,10 @@ final class IsValidUtf8TestUtil { // 18,304 static final long EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT = // Both bytes are one byte characters - (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 2) + - // The possible number of two byte characters - TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS; + (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 2) + + + // The possible number of two byte characters + TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS; // 2048 static final long THREE_BYTE_SURROGATES = 2 * 1024; @@ -130,11 +133,13 @@ final class IsValidUtf8TestUtil { // 2,650,112 static final long EXPECTED_THREE_BYTE_ROUNDTRIPPABLE_COUNT = // All one byte characters - (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 3) + - // One two byte character and a one byte character - 2 * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS + - // Three byte characters - THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS; + (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 3) + + + // One two byte character and a one byte character + 2 * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS + + + // Three byte characters + THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS; // 1,048,576 [chars 0x10000L to 0x10FFFF] static final long FOUR_BYTE_ROUNDTRIPPABLE_CHARACTERS = 0x10FFFF - 0x10000L + 1; @@ -142,17 +147,22 @@ final class IsValidUtf8TestUtil { // 289,571,839 static final long EXPECTED_FOUR_BYTE_ROUNDTRIPPABLE_COUNT = // All one byte characters - (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 4) + - // One and three byte characters - 2 * THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS + - // Two two byte characters - TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS + - // Permutations of one and two byte characters - 3 * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS - * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS - + - // Four byte characters - FOUR_BYTE_ROUNDTRIPPABLE_CHARACTERS; + (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 4) + + + // One and three byte characters + 2 * THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS + + + // Two two byte characters + TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS + + + // Permutations of one and two byte characters + 3 + * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS + * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS + * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS + + + // Four byte characters + FOUR_BYTE_ROUNDTRIPPABLE_CHARACTERS; static final class Shard { final long index; @@ -160,7 +170,6 @@ final class IsValidUtf8TestUtil { final long lim; final long expected; - public Shard(long index, long start, long lim, long expected) { assertTrue(start < lim); this.index = index; @@ -206,7 +215,6 @@ final class IsValidUtf8TestUtil { static final List FOUR_BYTE_SHARDS = generateFourByteShards(128, FOUR_BYTE_SHARDS_EXPECTED_ROUNTRIPPABLES); - private static List generateFourByteShards(int numShards, long[] expected) { assertEquals(numShards, expected.length); List shards = new ArrayList(numShards); @@ -220,8 +228,7 @@ final class IsValidUtf8TestUtil { } /** - * Helper to run the loop to test all the permutations for the number of bytes - * specified. + * Helper to run the loop to test all the permutations for the number of bytes specified. * * @param factory the factory for {@link ByteString} instances. * @param numBytes the number of bytes in the byte array @@ -232,16 +239,15 @@ final class IsValidUtf8TestUtil { } /** - * Helper to run the loop to test all the permutations for the number of bytes - * specified. This overload is useful for debugging to get the loop to start - * at a certain character. + * Helper to run the loop to test all the permutations for the number of bytes specified. This + * overload is useful for debugging to get the loop to start at a certain character. * * @param factory the factory for {@link ByteString} instances. * @param numBytes the number of bytes in the byte array * @param expectedCount the expected number of roundtrippable permutations * @param start the starting bytes encoded as a long as big-endian - * @param lim the limit of bytes to process encoded as a long as big-endian, - * or -1 to mean the max limit for numBytes + * @param lim the limit of bytes to process encoded as a long as big-endian, or -1 to mean the max + * limit for numBytes */ static void testBytes( ByteStringFactory factory, int numBytes, long expectedCount, long start, long lim) { @@ -301,9 +307,10 @@ final class IsValidUtf8TestUtil { assertEquals(isRoundTrippable, (state3 == Utf8.COMPLETE)); // Test ropes built out of small partial sequences - ByteString rope = RopeByteString.newInstanceForTest( - bs.substring(0, i), - RopeByteString.newInstanceForTest(bs.substring(i, j), bs.substring(j, numBytes))); + ByteString rope = + RopeByteString.newInstanceForTest( + bs.substring(0, i), + RopeByteString.newInstanceForTest(bs.substring(i, j), bs.substring(j, numBytes))); assertSame(RopeByteString.class, rope.getClass()); ByteString[] byteStrings = {bs, bs.substring(0, numBytes), rope}; @@ -336,27 +343,28 @@ final class IsValidUtf8TestUtil { } /** - * Variation of {@link #testBytes} that does less allocation using the - * low-level encoders/decoders directly. Checked in because it's useful for - * debugging when trying to process bytes faster, but since it doesn't use the - * actual String class, it's possible for incompatibilities to develop + * Variation of {@link #testBytes} that does less allocation using the low-level encoders/decoders + * directly. Checked in because it's useful for debugging when trying to process bytes faster, but + * since it doesn't use the actual String class, it's possible for incompatibilities to develop * (although unlikely). * * @param factory the factory for {@link ByteString} instances. * @param numBytes the number of bytes in the byte array * @param expectedCount the expected number of roundtrippable permutations * @param start the starting bytes encoded as a long as big-endian - * @param lim the limit of bytes to process encoded as a long as big-endian, - * or -1 to mean the max limit for numBytes + * @param lim the limit of bytes to process encoded as a long as big-endian, or -1 to mean the max + * limit for numBytes */ static void testBytesUsingByteBuffers( ByteStringFactory factory, int numBytes, long expectedCount, long start, long lim) { CharsetDecoder decoder = - Internal.UTF_8.newDecoder() + Internal.UTF_8 + .newDecoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE); CharsetEncoder encoder = - Internal.UTF_8.newEncoder() + Internal.UTF_8 + .newEncoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE); byte[] bytes = new byte[numBytes]; @@ -434,8 +442,10 @@ final class IsValidUtf8TestUtil { } private static void outputFailure(long byteChar, byte[] bytes, byte[] after, int len) { - fail("Failure: (" + Long.toHexString(byteChar) + ") " + toHexString(bytes) + " => " - + toHexString(after, len)); + fail( + String.format( + "Failure: (%s) %s => %s", + Long.toHexString(byteChar), toHexString(bytes), toHexString(after, len))); } private static String toHexString(byte[] b) { diff --git a/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java b/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java index f27e8e51b2..a3901e91b9 100644 --- a/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java +++ b/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java @@ -42,8 +42,7 @@ import junit.framework.TestCase; public class LazyFieldTest extends TestCase { public void testHashCode() { MessageLite message = TestUtil.getAllSet(); - LazyField lazyField = - createLazyFieldFromMessage(message); + LazyField lazyField = createLazyFieldFromMessage(message); assertEquals(message.hashCode(), lazyField.hashCode()); lazyField.getValue(); assertEquals(message.hashCode(), lazyField.hashCode()); @@ -102,8 +101,8 @@ public class LazyFieldTest extends TestCase { private LazyField createLazyFieldFromMessage(MessageLite message) { ByteString bytes = message.toByteString(); - return new LazyField(message.getDefaultInstanceForType(), - TestUtil.getExtensionRegistry(), bytes); + return new LazyField( + message.getDefaultInstanceForType(), TestUtil.getExtensionRegistry(), bytes); } private void changeValue(LazyField lazyField) { @@ -114,7 +113,6 @@ public class LazyFieldTest extends TestCase { } private void assertNotEqual(Object unexpected, Object actual) { - assertFalse(unexpected == actual - || (unexpected != null && unexpected.equals(actual))); + assertFalse(unexpected == actual || (unexpected != null && unexpected.equals(actual))); } } diff --git a/java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java b/java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java index 968ca2065c..c5880d5065 100644 --- a/java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java +++ b/java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java @@ -44,8 +44,6 @@ import junit.framework.TestCase; */ public class LazyMessageLiteTest extends TestCase { - private Parser originalLazyInnerMessageLiteParser; - @Override protected void setUp() throws Exception { super.setUp(); @@ -57,19 +55,16 @@ public class LazyMessageLiteTest extends TestCase { } public void testSetValues() { - LazyNestedInnerMessageLite nested = LazyNestedInnerMessageLite.newBuilder() - .setNum(3) - .build(); - LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder() - .setNum(2) - .setNested(nested) - .build(); - LazyMessageLite outer = LazyMessageLite.newBuilder() - .setNum(1) - .setInner(inner) - .setOneofNum(123) - .setOneofInner(inner) - .build(); + LazyNestedInnerMessageLite nested = LazyNestedInnerMessageLite.newBuilder().setNum(3).build(); + LazyInnerMessageLite inner = + LazyInnerMessageLite.newBuilder().setNum(2).setNested(nested).build(); + LazyMessageLite outer = + LazyMessageLite.newBuilder() + .setNum(1) + .setInner(inner) + .setOneofNum(123) + .setOneofInner(inner) + .build(); assertEquals(1, outer.getNum()); assertEquals(421, outer.getNumWithDefault()); @@ -90,44 +85,43 @@ public class LazyMessageLiteTest extends TestCase { } public void testSetRepeatedValues() { - LazyMessageLite outer = LazyMessageLite.newBuilder() - .setNum(1) - .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(119)) - .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(122)) - .build(); + LazyMessageLite outer = + LazyMessageLite.newBuilder() + .setNum(1) + .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(119)) + .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(122)) + .build(); assertEquals(1, outer.getNum()); assertEquals(2, outer.getRepeatedInnerCount()); assertEquals(119, outer.getRepeatedInner(0).getNum()); assertEquals(122, outer.getRepeatedInner(1).getNum()); } - + public void testRepeatedMutability() throws Exception { - LazyMessageLite outer = LazyMessageLite.newBuilder() - .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(119)) - .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(122)) - .build(); - + LazyMessageLite outer = + LazyMessageLite.newBuilder() + .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(119)) + .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(122)) + .build(); + outer = LazyMessageLite.parseFrom(outer.toByteArray()); try { outer.getRepeatedInnerList().set(1, null); fail(); - } catch (UnsupportedOperationException expected) {} + } catch (UnsupportedOperationException expected) { + } } public void testAddAll() { - ArrayList inners = new ArrayList(); + ArrayList inners = new ArrayList<>(); int count = 4; for (int i = 0; i < count; i++) { - LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder() - .setNum(i) - .build(); + LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder().setNum(i).build(); inners.add(inner); } - LazyMessageLite outer = LazyMessageLite.newBuilder() - .addAllRepeatedInner(inners) - .build(); + LazyMessageLite outer = LazyMessageLite.newBuilder().addAllRepeatedInner(inners).build(); assertEquals(count, outer.getRepeatedInnerCount()); for (int i = 0; i < count; i++) { assertEquals(i, outer.getRepeatedInner(i).getNum()); @@ -135,8 +129,7 @@ public class LazyMessageLiteTest extends TestCase { } public void testGetDefaultValues() { - LazyMessageLite outer = LazyMessageLite.newBuilder() - .build(); + LazyMessageLite outer = LazyMessageLite.getDefaultInstance(); assertEquals(0, outer.getNum()); assertEquals(421, outer.getNumWithDefault()); @@ -156,15 +149,12 @@ public class LazyMessageLiteTest extends TestCase { } public void testClearValues() { - LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder() - .setNum(115) - .build(); + LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder().setNum(115).build(); LazyMessageLite.Builder outerBuilder = LazyMessageLite.newBuilder(); assertEquals(0, outerBuilder.build().getNum()); - // Set/Clear num outerBuilder.setNum(100); @@ -178,9 +168,9 @@ public class LazyMessageLiteTest extends TestCase { assertEquals(421, outerBuilder.build().getNumWithDefault()); assertFalse(outerBuilder.build().hasInner()); - // Set/Clear all - outerBuilder.setNum(100) + outerBuilder + .setNum(100) .setInner(inner) .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(119)) .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(122)) @@ -210,23 +200,17 @@ public class LazyMessageLiteTest extends TestCase { } public void testMergeValues() { - LazyMessageLite outerBase = LazyMessageLite.newBuilder() - .setNumWithDefault(122) - .build(); - - LazyInnerMessageLite innerMerging = LazyInnerMessageLite.newBuilder() - .setNum(115) - .build(); - LazyMessageLite outerMerging = LazyMessageLite.newBuilder() - .setNum(119) - .setInner(innerMerging) - .setOneofInner(innerMerging) - .build(); - - LazyMessageLite merged = LazyMessageLite - .newBuilder(outerBase) - .mergeFrom(outerMerging) - .build(); + LazyMessageLite outerBase = LazyMessageLite.newBuilder().setNumWithDefault(122).build(); + + LazyInnerMessageLite innerMerging = LazyInnerMessageLite.newBuilder().setNum(115).build(); + LazyMessageLite outerMerging = + LazyMessageLite.newBuilder() + .setNum(119) + .setInner(innerMerging) + .setOneofInner(innerMerging) + .build(); + + LazyMessageLite merged = LazyMessageLite.newBuilder(outerBase).mergeFrom(outerMerging).build(); assertEquals(119, merged.getNum()); assertEquals(122, merged.getNumWithDefault()); assertEquals(115, merged.getInner().getNum()); @@ -236,23 +220,18 @@ public class LazyMessageLiteTest extends TestCase { } public void testMergeDefaultValues() { - LazyInnerMessageLite innerBase = LazyInnerMessageLite.newBuilder() - .setNum(115) - .build(); - LazyMessageLite outerBase = LazyMessageLite.newBuilder() - .setNum(119) - .setNumWithDefault(122) - .setInner(innerBase) - .setOneofInner(innerBase) - .build(); - - LazyMessageLite outerMerging = LazyMessageLite.newBuilder() - .build(); - - LazyMessageLite merged = LazyMessageLite - .newBuilder(outerBase) - .mergeFrom(outerMerging) - .build(); + LazyInnerMessageLite innerBase = LazyInnerMessageLite.newBuilder().setNum(115).build(); + LazyMessageLite outerBase = + LazyMessageLite.newBuilder() + .setNum(119) + .setNumWithDefault(122) + .setInner(innerBase) + .setOneofInner(innerBase) + .build(); + + LazyMessageLite outerMerging = LazyMessageLite.getDefaultInstance(); + + LazyMessageLite merged = LazyMessageLite.newBuilder(outerBase).mergeFrom(outerMerging).build(); // Merging default-instance shouldn't overwrite values in the base message. assertEquals(119, merged.getNum()); assertEquals(122, merged.getNumWithDefault()); @@ -264,7 +243,7 @@ public class LazyMessageLiteTest extends TestCase { // Regression test for b/28198805. public void testMergeOneofMessages() throws Exception { - LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder().build(); + LazyInnerMessageLite inner = LazyInnerMessageLite.getDefaultInstance(); LazyMessageLite outer = LazyMessageLite.newBuilder().setOneofInner(inner).build(); ByteString data1 = outer.toByteString(); @@ -280,18 +259,11 @@ public class LazyMessageLiteTest extends TestCase { } public void testSerialize() throws InvalidProtocolBufferException { - LazyNestedInnerMessageLite nested = LazyNestedInnerMessageLite.newBuilder() - .setNum(3) - .build(); - LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder() - .setNum(2) - .setNested(nested) - .build(); - LazyMessageLite outer = LazyMessageLite.newBuilder() - .setNum(1) - .setInner(inner) - .setOneofInner(inner) - .build(); + LazyNestedInnerMessageLite nested = LazyNestedInnerMessageLite.newBuilder().setNum(3).build(); + LazyInnerMessageLite inner = + LazyInnerMessageLite.newBuilder().setNum(2).setNested(nested).build(); + LazyMessageLite outer = + LazyMessageLite.newBuilder().setNum(1).setInner(inner).setOneofInner(inner).build(); ByteString bytes = outer.toByteString(); assertEquals(bytes.size(), outer.getSerializedSize()); @@ -299,18 +271,18 @@ public class LazyMessageLiteTest extends TestCase { LazyMessageLite deserialized = LazyMessageLite.parseFrom(bytes); assertEquals(1, deserialized.getNum()); - assertEquals(421, deserialized.getNumWithDefault()); + assertEquals(421, deserialized.getNumWithDefault()); - assertEquals(2, deserialized.getInner().getNum()); - assertEquals(42, deserialized.getInner().getNumWithDefault()); + assertEquals(2, deserialized.getInner().getNum()); + assertEquals(42, deserialized.getInner().getNumWithDefault()); - assertEquals(3, deserialized.getInner().getNested().getNum()); - assertEquals(4, deserialized.getInner().getNested().getNumWithDefault()); + assertEquals(3, deserialized.getInner().getNested().getNum()); + assertEquals(4, deserialized.getInner().getNested().getNumWithDefault()); - assertEquals(2, deserialized.getOneofInner().getNum()); - assertEquals(42, deserialized.getOneofInner().getNumWithDefault()); - assertEquals(3, deserialized.getOneofInner().getNested().getNum()); - assertEquals(4, deserialized.getOneofInner().getNested().getNumWithDefault()); + assertEquals(2, deserialized.getOneofInner().getNum()); + assertEquals(42, deserialized.getOneofInner().getNumWithDefault()); + assertEquals(3, deserialized.getOneofInner().getNested().getNum()); + assertEquals(4, deserialized.getOneofInner().getNested().getNumWithDefault()); assertEquals(bytes, deserialized.toByteString()); } @@ -318,8 +290,7 @@ public class LazyMessageLiteTest extends TestCase { public void testExtensions() throws Exception { LazyInnerMessageLite.Builder innerBuilder = LazyInnerMessageLite.newBuilder(); innerBuilder.setExtension( - LazyExtension.extension, LazyExtension.newBuilder() - .setName("name").build()); + LazyExtension.extension, LazyExtension.newBuilder().setName("name").build()); assertTrue(innerBuilder.hasExtension(LazyExtension.extension)); assertEquals("name", innerBuilder.getExtension(LazyExtension.extension).getName()); @@ -327,8 +298,7 @@ public class LazyMessageLiteTest extends TestCase { assertTrue(innerMessage.hasExtension(LazyExtension.extension)); assertEquals("name", innerMessage.getExtension(LazyExtension.extension).getName()); - LazyMessageLite lite = LazyMessageLite.newBuilder() - .setInner(innerMessage).build(); + LazyMessageLite lite = LazyMessageLite.newBuilder().setInner(innerMessage).build(); assertTrue(lite.getInner().hasExtension(LazyExtension.extension)); assertEquals("name", lite.getInner().getExtension(LazyExtension.extension).getName()); } diff --git a/java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java b/java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java index 2fc3124d4c..24d0038b3d 100644 --- a/java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java +++ b/java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java @@ -46,13 +46,13 @@ import junit.framework.TestCase; */ public class LazyStringArrayListTest extends TestCase { - private static String STRING_A = "A"; - private static String STRING_B = "B"; - private static String STRING_C = "C"; + private static final String STRING_A = "A"; + private static final String STRING_B = "B"; + private static final String STRING_C = "C"; - private static ByteString BYTE_STRING_A = ByteString.copyFromUtf8("A"); - private static ByteString BYTE_STRING_B = ByteString.copyFromUtf8("B"); - private static ByteString BYTE_STRING_C = ByteString.copyFromUtf8("C"); + private static final ByteString BYTE_STRING_A = ByteString.copyFromUtf8("A"); + private static final ByteString BYTE_STRING_B = ByteString.copyFromUtf8("B"); + private static final ByteString BYTE_STRING_C = ByteString.copyFromUtf8("C"); public void testJustStrings() { LazyStringArrayList list = new LazyStringArrayList(); @@ -175,7 +175,7 @@ public class LazyStringArrayListTest extends TestCase { assertSame(BYTE_STRING_B, list2.getByteString(1)); assertSame(BYTE_STRING_C, list2.getByteString(2)); } - + public void testModificationWithIteration() { LazyStringArrayList list = new LazyStringArrayList(); list.addAll(asList(STRING_A, STRING_B, STRING_C)); @@ -183,12 +183,12 @@ public class LazyStringArrayListTest extends TestCase { assertEquals(3, list.size()); assertEquals(STRING_A, list.get(0)); assertEquals(STRING_A, iterator.next()); - + // Does not structurally modify. iterator = list.iterator(); list.set(0, STRING_B); iterator.next(); - + list.remove(0); try { iterator.next(); @@ -196,7 +196,7 @@ public class LazyStringArrayListTest extends TestCase { } catch (ConcurrentModificationException e) { // expected } - + iterator = list.iterator(); list.add(0, STRING_C); try { @@ -206,7 +206,7 @@ public class LazyStringArrayListTest extends TestCase { // expected } } - + public void testMakeImmutable() { LazyStringArrayList list = new LazyStringArrayList(); list.add(STRING_A); @@ -214,52 +214,52 @@ public class LazyStringArrayListTest extends TestCase { list.add(STRING_C); list.makeImmutable(); assertGenericListImmutable(list, STRING_A); - + // LazyStringArrayList has extra methods not covered in the generic // assertion. - + try { list.add(BYTE_STRING_A.toByteArray()); fail(); } catch (UnsupportedOperationException e) { // expected } - + try { list.add(BYTE_STRING_A); fail(); } catch (UnsupportedOperationException e) { // expected } - + try { list.addAllByteArray(Collections.singletonList(BYTE_STRING_A.toByteArray())); fail(); } catch (UnsupportedOperationException e) { // expected } - + try { list.addAllByteString(asList(BYTE_STRING_A)); fail(); } catch (UnsupportedOperationException e) { // expected } - + try { list.mergeFrom(new LazyStringArrayList()); fail(); } catch (UnsupportedOperationException e) { // expected } - + try { list.set(0, BYTE_STRING_A.toByteArray()); fail(); } catch (UnsupportedOperationException e) { // expected } - + try { list.set(0, BYTE_STRING_A); fail(); @@ -267,20 +267,20 @@ public class LazyStringArrayListTest extends TestCase { // expected } } - + public void testImmutabilityPropagation() { LazyStringArrayList list = new LazyStringArrayList(); list.add(STRING_A); list.makeImmutable(); assertGenericListImmutable(list.asByteStringList(), BYTE_STRING_A); - + // Arrays use reference equality so need to retrieve the underlying value // to properly test deep immutability. List byteArrayList = list.asByteArrayList(); assertGenericListImmutable(byteArrayList, byteArrayList.get(0)); } - + @SuppressWarnings("unchecked") private static void assertGenericListImmutable(List list, T value) { try { @@ -289,21 +289,21 @@ public class LazyStringArrayListTest extends TestCase { } catch (UnsupportedOperationException e) { // expected } - + try { list.add(0, value); fail(); } catch (UnsupportedOperationException e) { // expected } - + try { list.addAll(asList(value)); fail(); } catch (UnsupportedOperationException e) { // expected } - + try { list.addAll(0, asList(value)); fail(); @@ -317,42 +317,42 @@ public class LazyStringArrayListTest extends TestCase { } catch (UnsupportedOperationException e) { // expected } - + try { list.remove(0); fail(); } catch (UnsupportedOperationException e) { // expected } - + try { list.remove(value); fail(); } catch (UnsupportedOperationException e) { // expected } - + try { list.removeAll(asList(value)); fail(); } catch (UnsupportedOperationException e) { // expected } - + try { list.retainAll(asList()); fail(); } catch (UnsupportedOperationException e) { // expected } - + try { list.retainAll(asList()); fail(); } catch (UnsupportedOperationException e) { // expected } - + try { list.set(0, value); fail(); diff --git a/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java b/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java index 006e493366..18c9c74ec3 100644 --- a/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java +++ b/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java @@ -30,44 +30,42 @@ package com.google.protobuf; - import protobuf_unittest.UnittestProto; import java.io.IOException; import junit.framework.TestCase; /** - * Tests to make sure the lazy conversion of UTF8-encoded byte arrays to - * strings works correctly. + * Tests to make sure the lazy conversion of UTF8-encoded byte arrays to strings works correctly. * * @author jonp@google.com (Jon Perlow) */ public class LazyStringEndToEndTest extends TestCase { - private static ByteString TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8 = - ByteString.copyFrom(new byte[] { - 114, 4, -1, 0, -1, 0, -30, 2, 4, -1, - 0, -1, 0, -30, 2, 4, -1, 0, -1, 0, }); + private static final ByteString TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8 = + ByteString.copyFrom( + new byte[] { + 114, 4, -1, 0, -1, 0, -30, 2, 4, -1, + 0, -1, 0, -30, 2, 4, -1, 0, -1, 0, + }); private ByteString encodedTestAllTypes; @Override protected void setUp() throws Exception { super.setUp(); - this.encodedTestAllTypes = UnittestProto.TestAllTypes.newBuilder() - .setOptionalString("foo") - .addRepeatedString("bar") - .addRepeatedString("baz") - .build() - .toByteString(); + this.encodedTestAllTypes = + UnittestProto.TestAllTypes.newBuilder() + .setOptionalString("foo") + .addRepeatedString("bar") + .addRepeatedString("baz") + .build() + .toByteString(); } - /** - * Tests that an invalid UTF8 string will roundtrip through a parse - * and serialization. - */ + /** Tests that an invalid UTF8 string will roundtrip through a parse and serialization. */ public void testParseAndSerialize() throws InvalidProtocolBufferException { - UnittestProto.TestAllTypes tV2 = UnittestProto.TestAllTypes.parseFrom( - TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8); + UnittestProto.TestAllTypes tV2 = + UnittestProto.TestAllTypes.parseFrom(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8); ByteString bytes = tV2.toByteString(); assertEquals(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8, bytes); @@ -77,33 +75,31 @@ public class LazyStringEndToEndTest extends TestCase { } public void testParseAndWrite() throws IOException { - UnittestProto.TestAllTypes tV2 = UnittestProto.TestAllTypes.parseFrom( - TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8); + UnittestProto.TestAllTypes tV2 = + UnittestProto.TestAllTypes.parseFrom(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8); byte[] sink = new byte[TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8.size()]; CodedOutputStream outputStream = CodedOutputStream.newInstance(sink); tV2.writeTo(outputStream); outputStream.flush(); - assertEquals( - TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8, - ByteString.copyFrom(sink)); + assertEquals(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8, ByteString.copyFrom(sink)); } - + public void testCaching() { String a = "a"; String b = "b"; String c = "c"; - UnittestProto.TestAllTypes proto = UnittestProto.TestAllTypes.newBuilder() - .setOptionalString(a) - .addRepeatedString(b) - .addRepeatedString(c) - .build(); + UnittestProto.TestAllTypes proto = + UnittestProto.TestAllTypes.newBuilder() + .setOptionalString(a) + .addRepeatedString(b) + .addRepeatedString(c) + .build(); // String should be the one we passed it. assertSame(a, proto.getOptionalString()); assertSame(b, proto.getRepeatedString(0)); assertSame(c, proto.getRepeatedString(1)); - // Ensure serialization keeps strings cached. proto.toByteString(); @@ -114,8 +110,7 @@ public class LazyStringEndToEndTest extends TestCase { } public void testNoStringCachingIfOnlyBytesAccessed() throws Exception { - UnittestProto.TestAllTypes proto = - UnittestProto.TestAllTypes.parseFrom(encodedTestAllTypes); + UnittestProto.TestAllTypes proto = UnittestProto.TestAllTypes.parseFrom(encodedTestAllTypes); ByteString optional = proto.getOptionalStringBytes(); assertSame(optional, proto.getOptionalStringBytes()); assertSame(optional, proto.toBuilder().getOptionalStringBytes()); diff --git a/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java b/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java index eac47448e0..9e5adb7039 100644 --- a/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java +++ b/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java @@ -46,9 +46,9 @@ import java.util.NoSuchElementException; import junit.framework.TestCase; /** - * Test {@code LiteralByteString} by setting up a reference string in {@link #setUp()}. - * This class is designed to be extended for testing extensions of {@code LiteralByteString} - * such as {@code BoundedByteString}, see {@link BoundedByteStringTest}. + * Test {@code LiteralByteString} by setting up a reference string in {@link #setUp()}. This class + * is designed to be extended for testing extensions of {@code LiteralByteString} such as {@code + * BoundedByteString}, see {@link BoundedByteStringTest}. * * @author carlanton@google.com (Carl Haverl) */ @@ -114,7 +114,9 @@ public class LiteralByteStringTest extends TestCase { } public void testSize() { - assertEquals(classUnderTest + " must have the expected size", referenceBytes.length, + assertEquals( + classUnderTest + " must have the expected size", + referenceBytes.length, stringUnderTest.size()); } @@ -146,10 +148,9 @@ public class LiteralByteStringTest extends TestCase { try { // Copy one too many bytes - stringUnderTest.copyTo(destination, stringUnderTest.size() + 1 - length, - destinationOffset, length); - fail("Should have thrown an exception when copying too many bytes of a " - + classUnderTest); + stringUnderTest.copyTo( + destination, stringUnderTest.size() + 1 - length, destinationOffset, length); + fail("Should have thrown an exception when copying too many bytes of a " + classUnderTest); } catch (IndexOutOfBoundsException expected) { // This is success } @@ -157,8 +158,9 @@ public class LiteralByteStringTest extends TestCase { try { // Copy with illegal negative sourceOffset stringUnderTest.copyTo(destination, -1, destinationOffset, length); - fail("Should have thrown an exception when given a negative sourceOffset in " - + classUnderTest); + fail( + "Should have thrown an exception when given a negative sourceOffset in " + + classUnderTest); } catch (IndexOutOfBoundsException expected) { // This is success } @@ -166,8 +168,9 @@ public class LiteralByteStringTest extends TestCase { try { // Copy with illegal negative destinationOffset stringUnderTest.copyTo(destination, 0, -1, length); - fail("Should have thrown an exception when given a negative destinationOffset in " - + classUnderTest); + fail( + "Should have thrown an exception when given a negative destinationOffset in " + + classUnderTest); } catch (IndexOutOfBoundsException expected) { // This is success } @@ -175,8 +178,7 @@ public class LiteralByteStringTest extends TestCase { try { // Copy with illegal negative size stringUnderTest.copyTo(destination, 0, 0, -1); - fail("Should have thrown an exception when given a negative size in " - + classUnderTest); + fail("Should have thrown an exception when given a negative size in " + classUnderTest); } catch (IndexOutOfBoundsException expected) { // This is success } @@ -184,8 +186,9 @@ public class LiteralByteStringTest extends TestCase { try { // Copy with illegal too-large sourceOffset stringUnderTest.copyTo(destination, 2 * stringUnderTest.size(), 0, length); - fail("Should have thrown an exception when the destinationOffset is too large in " - + classUnderTest); + fail( + "Should have thrown an exception when the destinationOffset is too large in " + + classUnderTest); } catch (IndexOutOfBoundsException expected) { // This is success } @@ -193,8 +196,9 @@ public class LiteralByteStringTest extends TestCase { try { // Copy with illegal too-large destinationOffset stringUnderTest.copyTo(destination, 0, 2 * destination.length, length); - fail("Should have thrown an exception when the destinationOffset is too large in " - + classUnderTest); + fail( + "Should have thrown an exception when the destinationOffset is too large in " + + classUnderTest); } catch (IndexOutOfBoundsException expected) { // This is success } @@ -203,7 +207,8 @@ public class LiteralByteStringTest extends TestCase { public void testCopyTo_ByteBuffer() { ByteBuffer myBuffer = ByteBuffer.allocate(referenceBytes.length); stringUnderTest.copyTo(myBuffer); - assertTrue(classUnderTest + ".copyTo(ByteBuffer) must give back the same bytes", + assertTrue( + classUnderTest + ".copyTo(ByteBuffer) must give back the same bytes", Arrays.equals(referenceBytes, myBuffer.array())); } @@ -233,17 +238,15 @@ public class LiteralByteStringTest extends TestCase { } /** - * Discards {@code n} bytes of data from the input stream. This method - * will block until the full amount has been skipped. Does not close the - * stream. + * Discards {@code n} bytes of data from the input stream. This method will block until the full + * amount has been skipped. Does not close the stream. + * *

Copied from com.google.common.io.ByteStreams to avoid adding dependency. * * @param in the input stream to read from * @param n the number of bytes to skip - * @throws EOFException if this stream reaches the end before skipping all - * the bytes - * @throws IOException if an I/O error occurs, or the stream does not - * support skipping + * @throws EOFException if this stream reaches the end before skipping all the bytes + * @throws IOException if an I/O error occurs, or the stream does not support skipping */ static void skipFully(InputStream in, long n) throws IOException { long toSkip = n; @@ -253,8 +256,12 @@ public class LiteralByteStringTest extends TestCase { // Force a blocking read to avoid infinite loop if (in.read() == -1) { long skipped = toSkip - n; - throw new EOFException("reached end of stream after skipping " - + skipped + " bytes; " + toSkip + " bytes expected"); + throw new EOFException( + "reached end of stream after skipping " + + skipped + + " bytes; " + + toSkip + + " bytes expected"); } n--; } else { @@ -269,7 +276,8 @@ public class LiteralByteStringTest extends TestCase { assertTrue(byteBuffer.remaining() == referenceBytes.length); assertTrue(byteBuffer.isReadOnly()); byteBuffer.get(roundTripBytes); - assertTrue(classUnderTest + ".asReadOnlyByteBuffer() must give back the same bytes", + assertTrue( + classUnderTest + ".asReadOnlyByteBuffer() must give back the same bytes", Arrays.equals(referenceBytes, roundTripBytes)); } @@ -285,13 +293,15 @@ public class LiteralByteStringTest extends TestCase { bytesSeen += thisLength; } assertTrue(bytesSeen == referenceBytes.length); - assertTrue(classUnderTest + ".asReadOnlyByteBufferTest() must give back the same bytes", + assertTrue( + classUnderTest + ".asReadOnlyByteBufferTest() must give back the same bytes", Arrays.equals(referenceBytes, roundTripBytes)); } public void testToByteArray() { byte[] roundTripBytes = stringUnderTest.toByteArray(); - assertTrue(classUnderTest + ".toByteArray() must give back the same bytes", + assertTrue( + classUnderTest + ".toByteArray() must give back the same bytes", Arrays.equals(referenceBytes, roundTripBytes)); } @@ -299,78 +309,85 @@ public class LiteralByteStringTest extends TestCase { ByteArrayOutputStream bos = new ByteArrayOutputStream(); stringUnderTest.writeTo(bos); byte[] roundTripBytes = bos.toByteArray(); - assertTrue(classUnderTest + ".writeTo() must give back the same bytes", + assertTrue( + classUnderTest + ".writeTo() must give back the same bytes", Arrays.equals(referenceBytes, roundTripBytes)); } public void testWriteToShouldNotExposeInternalBufferToOutputStream() throws IOException { - OutputStream os = new OutputStream() { - @Override - public void write(byte[] b, int off, int len) { - Arrays.fill(b, off, off + len, (byte) 0); - } - - @Override - public void write(int b) { - throw new UnsupportedOperationException(); - } - }; + OutputStream os = + new OutputStream() { + @Override + public void write(byte[] b, int off, int len) { + Arrays.fill(b, off, off + len, (byte) 0); + } + + @Override + public void write(int b) { + throw new UnsupportedOperationException(); + } + }; stringUnderTest.writeTo(os); - assertTrue(classUnderTest + ".writeTo() must not grant access to underlying array", + assertTrue( + classUnderTest + ".writeTo() must not grant access to underlying array", Arrays.equals(referenceBytes, stringUnderTest.toByteArray())); } public void testWriteToInternalShouldExposeInternalBufferToOutputStream() throws IOException { - OutputStream os = new OutputStream() { - @Override - public void write(byte[] b, int off, int len) { - Arrays.fill(b, off, off + len, (byte) 0); - } - - @Override - public void write(int b) { - throw new UnsupportedOperationException(); - } - }; + OutputStream os = + new OutputStream() { + @Override + public void write(byte[] b, int off, int len) { + Arrays.fill(b, off, off + len, (byte) 0); + } + + @Override + public void write(int b) { + throw new UnsupportedOperationException(); + } + }; stringUnderTest.writeToInternal(os, 0, stringUnderTest.size()); byte[] allZeros = new byte[stringUnderTest.size()]; - assertTrue(classUnderTest + ".writeToInternal() must grant access to underlying array", + assertTrue( + classUnderTest + ".writeToInternal() must grant access to underlying array", Arrays.equals(allZeros, stringUnderTest.toByteArray())); } public void testWriteToShouldExposeInternalBufferToByteOutput() throws IOException { - ByteOutput out = new ByteOutput() { - @Override - public void write(byte value) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public void write(byte[] value, int offset, int length) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public void writeLazy(byte[] value, int offset, int length) throws IOException { - Arrays.fill(value, offset, offset + length, (byte) 0); - } - - @Override - public void write(ByteBuffer value) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public void writeLazy(ByteBuffer value) throws IOException { - throw new UnsupportedOperationException(); - } - }; + ByteOutput out = + new ByteOutput() { + @Override + public void write(byte value) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void write(byte[] value, int offset, int length) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void writeLazy(byte[] value, int offset, int length) throws IOException { + Arrays.fill(value, offset, offset + length, (byte) 0); + } + + @Override + public void write(ByteBuffer value) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void writeLazy(ByteBuffer value) throws IOException { + throw new UnsupportedOperationException(); + } + }; stringUnderTest.writeTo(out); byte[] allZeros = new byte[stringUnderTest.size()]; - assertTrue(classUnderTest + ".writeToInternal() must grant access to underlying array", + assertTrue( + classUnderTest + ".writeToInternal() must grant access to underlying array", Arrays.equals(allZeros, stringUnderTest.toByteArray())); } @@ -378,21 +395,22 @@ public class LiteralByteStringTest extends TestCase { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteString.Output output = ByteString.newOutput(); stringUnderTest.writeTo(output); - assertEquals("Output Size returns correct result", - output.size(), stringUnderTest.size()); + assertEquals("Output Size returns correct result", output.size(), stringUnderTest.size()); output.writeTo(bos); - assertTrue("Output.writeTo() must give back the same bytes", + assertTrue( + "Output.writeTo() must give back the same bytes", Arrays.equals(referenceBytes, bos.toByteArray())); // write the output stream to itself! This should cause it to double output.writeTo(output); - assertEquals("Writing an output stream to itself is successful", - stringUnderTest.concat(stringUnderTest), output.toByteString()); + assertEquals( + "Writing an output stream to itself is successful", + stringUnderTest.concat(stringUnderTest), + output.toByteString()); output.reset(); assertEquals("Output.reset() resets the output", 0, output.size()); - assertEquals("Output.reset() resets the output", - ByteString.EMPTY, output.toByteString()); + assertEquals("Output.reset() resets the output", ByteString.EMPTY, output.toByteString()); } public void testToString() throws UnsupportedEncodingException { @@ -410,9 +428,10 @@ public class LiteralByteStringTest extends TestCase { } public void testToString_returnsCanonicalEmptyString() { - assertSame(classUnderTest + " must be the same string references", + assertSame( + classUnderTest + " must be the same string references", ByteString.EMPTY.toString(Internal.UTF_8), - ByteString.wrap(new byte[]{}).toString(Internal.UTF_8)); + ByteString.wrap(new byte[] {}).toString(Internal.UTF_8)); } public void testToString_raisesException() { @@ -434,17 +453,23 @@ public class LiteralByteStringTest extends TestCase { public void testEquals() { assertEquals(classUnderTest + " must not equal null", false, stringUnderTest.equals(null)); assertEquals(classUnderTest + " must equal self", stringUnderTest, stringUnderTest); - assertFalse(classUnderTest + " must not equal the empty string", + assertFalse( + classUnderTest + " must not equal the empty string", stringUnderTest.equals(ByteString.EMPTY)); - assertEquals(classUnderTest + " empty strings must be equal", - ByteString.wrap(new byte[]{}), stringUnderTest.substring(55, 55)); - assertEquals(classUnderTest + " must equal another string with the same value", - stringUnderTest, ByteString.wrap(referenceBytes)); + assertEquals( + classUnderTest + " empty strings must be equal", + ByteString.wrap(new byte[] {}), + stringUnderTest.substring(55, 55)); + assertEquals( + classUnderTest + " must equal another string with the same value", + stringUnderTest, + ByteString.wrap(referenceBytes)); byte[] mungedBytes = new byte[referenceBytes.length]; System.arraycopy(referenceBytes, 0, mungedBytes, 0, referenceBytes.length); mungedBytes[mungedBytes.length - 5] = (byte) (mungedBytes[mungedBytes.length - 5] ^ 0xFF); - assertFalse(classUnderTest + " must not equal every string with the same length", + assertFalse( + classUnderTest + " must not equal every string with the same length", stringUnderTest.equals(ByteString.wrap(mungedBytes))); } @@ -454,32 +479,35 @@ public class LiteralByteStringTest extends TestCase { } public void testPeekCachedHashCode() { - assertEquals(classUnderTest + ".peekCachedHashCode() should return zero at first", 0, + assertEquals( + classUnderTest + ".peekCachedHashCode() should return zero at first", + 0, stringUnderTest.peekCachedHashCode()); stringUnderTest.hashCode(); - assertEquals(classUnderTest + ".peekCachedHashCode should return zero at first", - expectedHashCode, stringUnderTest.peekCachedHashCode()); + assertEquals( + classUnderTest + ".peekCachedHashCode should return zero at first", + expectedHashCode, + stringUnderTest.peekCachedHashCode()); } public void testPartialHash() { // partialHash() is more strenuously tested elsewhere by testing hashes of substrings. // This test would fail if the expected hash were 1. It's not. int hash = stringUnderTest.partialHash(stringUnderTest.size(), 0, stringUnderTest.size()); - assertEquals(classUnderTest + ".partialHash() must yield expected hashCode", - expectedHashCode, hash); + assertEquals( + classUnderTest + ".partialHash() must yield expected hashCode", expectedHashCode, hash); } public void testNewInput() throws IOException { InputStream input = stringUnderTest.newInput(); - assertEquals("InputStream.available() returns correct value", - stringUnderTest.size(), input.available()); + assertEquals( + "InputStream.available() returns correct value", stringUnderTest.size(), input.available()); boolean stillEqual = true; for (byte referenceByte : referenceBytes) { int expectedInt = (referenceByte & 0xFF); stillEqual = (expectedInt == input.read()); } - assertEquals("InputStream.available() returns correct value", - 0, input.available()); + assertEquals("InputStream.available() returns correct value", 0, input.available()); assertTrue(classUnderTest + " must give the same bytes from the InputStream", stillEqual); assertEquals(classUnderTest + " InputStream must now be exhausted", -1, input.read()); } @@ -490,43 +518,44 @@ public class LiteralByteStringTest extends TestCase { int nearEndIndex = stringSize * 2 / 3; long skipped1 = input.skip(nearEndIndex); assertEquals("InputStream.skip()", skipped1, nearEndIndex); - assertEquals("InputStream.available()", - stringSize - skipped1, input.available()); + assertEquals("InputStream.available()", stringSize - skipped1, input.available()); assertTrue("InputStream.mark() is available", input.markSupported()); input.mark(0); - assertEquals("InputStream.skip(), read()", - stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read()); - assertEquals("InputStream.available()", - stringSize - skipped1 - 1, input.available()); + assertEquals( + "InputStream.skip(), read()", stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read()); + assertEquals("InputStream.available()", stringSize - skipped1 - 1, input.available()); long skipped2 = input.skip(stringSize); - assertEquals("InputStream.skip() incomplete", - skipped2, stringSize - skipped1 - 1); + assertEquals("InputStream.skip() incomplete", skipped2, stringSize - skipped1 - 1); assertEquals("InputStream.skip(), no more input", 0, input.available()); assertEquals("InputStream.skip(), no more input", -1, input.read()); input.reset(); - assertEquals("InputStream.reset() succeded", - stringSize - skipped1, input.available()); - assertEquals("InputStream.reset(), read()", - stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read()); + assertEquals("InputStream.reset() succeded", stringSize - skipped1, input.available()); + assertEquals( + "InputStream.reset(), read()", stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read()); } public void testNewCodedInput() throws IOException { CodedInputStream cis = stringUnderTest.newCodedInput(); byte[] roundTripBytes = cis.readRawBytes(referenceBytes.length); - assertTrue(classUnderTest + " must give the same bytes back from the CodedInputStream", + assertTrue( + classUnderTest + " must give the same bytes back from the CodedInputStream", Arrays.equals(referenceBytes, roundTripBytes)); assertTrue(classUnderTest + " CodedInputStream must now be exhausted", cis.isAtEnd()); } /** - * Make sure we keep things simple when concatenating with empty. See also - * {@link ByteStringTest#testConcat_empty()}. + * Make sure we keep things simple when concatenating with empty. See also {@link + * ByteStringTest#testConcat_empty()}. */ public void testConcat_empty() { - assertSame(classUnderTest + " concatenated with empty must give " + classUnderTest, - stringUnderTest.concat(ByteString.EMPTY), stringUnderTest); - assertSame("empty concatenated with " + classUnderTest + " must give " + classUnderTest, - ByteString.EMPTY.concat(stringUnderTest), stringUnderTest); + assertSame( + classUnderTest + " concatenated with empty must give " + classUnderTest, + stringUnderTest.concat(ByteString.EMPTY), + stringUnderTest); + assertSame( + "empty concatenated with " + classUnderTest + " must give " + classUnderTest, + ByteString.EMPTY.concat(stringUnderTest), + stringUnderTest); } public void testJavaSerialization() throws Exception { diff --git a/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java b/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java index 14a8e15975..4b5e6c78ce 100644 --- a/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java +++ b/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java @@ -45,10 +45,8 @@ import junit.framework.TestCase; */ public class LongArrayListTest extends TestCase { - private static final LongArrayList UNARY_LIST = - newImmutableLongArrayList(1); - private static final LongArrayList TERTIARY_LIST = - newImmutableLongArrayList(1, 2, 3); + private static final LongArrayList UNARY_LIST = newImmutableLongArrayList(1); + private static final LongArrayList TERTIARY_LIST = newImmutableLongArrayList(1, 2, 3); private LongArrayList list; @@ -225,9 +223,7 @@ public class LongArrayListTest extends TestCase { for (int i = 0; i < 6; i++) { list.add(Long.valueOf(5 + i)); } - assertEquals( - asList(0L, 1L, 4L, 2L, 3L, 5L, 6L, 7L, 8L, 9L, 10L), - list); + assertEquals(asList(0L, 1L, 4L, 2L, 3L, 5L, 6L, 7L, 8L, 9L, 10L), list); try { list.add(-1, 5L); @@ -299,16 +295,14 @@ public class LongArrayListTest extends TestCase { } public void testRemoveEndOfCapacity() { - LongList toRemove = - LongArrayList.emptyList().mutableCopyWithCapacity(1); + LongList toRemove = LongArrayList.emptyList().mutableCopyWithCapacity(1); toRemove.addLong(3); toRemove.remove(0); assertEquals(0, toRemove.size()); } public void testSublistRemoveEndOfCapacity() { - LongList toRemove = - LongArrayList.emptyList().mutableCopyWithCapacity(1); + LongList toRemove = LongArrayList.emptyList().mutableCopyWithCapacity(1); toRemove.addLong(3); toRemove.subList(0, 1).clear(); assertEquals(0, toRemove.size()); diff --git a/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java b/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java index da9195f933..41fef07368 100644 --- a/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java +++ b/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java @@ -43,9 +43,7 @@ import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; -/** - * Unit tests for map fields. - */ +/** Unit tests for map fields. */ public final class MapForProto2LiteTest extends TestCase { private void setMapValues(TestMap.Builder builder) { @@ -53,23 +51,18 @@ public final class MapForProto2LiteTest extends TestCase { .putInt32ToInt32Field(1, 11) .putInt32ToInt32Field(2, 22) .putInt32ToInt32Field(3, 33) - .putInt32ToStringField(1, "11") .putInt32ToStringField(2, "22") .putInt32ToStringField(3, "33") - .putInt32ToBytesField(1, TestUtil.toBytes("11")) .putInt32ToBytesField(2, TestUtil.toBytes("22")) .putInt32ToBytesField(3, TestUtil.toBytes("33")) - .putInt32ToEnumField(1, TestMap.EnumValue.FOO) .putInt32ToEnumField(2, TestMap.EnumValue.BAR) .putInt32ToEnumField(3, TestMap.EnumValue.BAZ) - .putInt32ToMessageField(1, MessageValue.newBuilder().setValue(11).build()) .putInt32ToMessageField(2, MessageValue.newBuilder().setValue(22).build()) .putInt32ToMessageField(3, MessageValue.newBuilder().setValue(33).build()) - .putStringToInt32Field("1", 11) .putStringToInt32Field("2", 22) .putStringToInt32Field("3", 33); @@ -129,23 +122,18 @@ public final class MapForProto2LiteTest extends TestCase { .putInt32ToInt32Field(1, 111) .removeInt32ToInt32Field(2) .putInt32ToInt32Field(4, 44) - .putInt32ToStringField(1, "111") .removeInt32ToStringField(2) .putInt32ToStringField(4, "44") - .putInt32ToBytesField(1, TestUtil.toBytes("111")) .removeInt32ToBytesField(2) .putInt32ToBytesField(4, TestUtil.toBytes("44")) - .putInt32ToEnumField(1, TestMap.EnumValue.BAR) .removeInt32ToEnumField(2) .putInt32ToEnumField(4, TestMap.EnumValue.QUX) - .putInt32ToMessageField(1, MessageValue.newBuilder().setValue(111).build()) .removeInt32ToMessageField(2) .putInt32ToMessageField(4, MessageValue.newBuilder().setValue(44).build()) - .putStringToInt32Field("1", 111) .removeStringToInt32Field("2") .putStringToInt32Field("4", 44); @@ -265,8 +253,7 @@ public final class MapForProto2LiteTest extends TestCase { } public void testMutableMapLifecycle() { - TestMap.Builder builder = TestMap.newBuilder() - .putInt32ToInt32Field(1, 2); + TestMap.Builder builder = TestMap.newBuilder().putInt32ToInt32Field(1, 2); assertEquals(newMap(1, 2), builder.build().getInt32ToInt32Field()); assertEquals(newMap(1, 2), builder.getInt32ToInt32Field()); builder.putInt32ToInt32Field(2, 3); @@ -277,8 +264,7 @@ public final class MapForProto2LiteTest extends TestCase { assertEquals(newMap(1, TestMap.EnumValue.BAR), builder.getInt32ToEnumField()); builder.putInt32ToEnumField(2, TestMap.EnumValue.FOO); assertEquals( - newMap(1, TestMap.EnumValue.BAR, 2, TestMap.EnumValue.FOO), - builder.getInt32ToEnumField()); + newMap(1, TestMap.EnumValue.BAR, 2, TestMap.EnumValue.FOO), builder.getInt32ToEnumField()); builder.putInt32ToStringField(1, "1"); assertEquals(newMap(1, "1"), builder.build().getInt32ToStringField()); @@ -287,14 +273,18 @@ public final class MapForProto2LiteTest extends TestCase { assertEquals(newMap(1, "1", 2, "2"), builder.getInt32ToStringField()); builder.putInt32ToMessageField(1, TestMap.MessageValue.getDefaultInstance()); - assertEquals(newMap(1, TestMap.MessageValue.getDefaultInstance()), + assertEquals( + newMap(1, TestMap.MessageValue.getDefaultInstance()), builder.build().getInt32ToMessageField()); - assertEquals(newMap(1, TestMap.MessageValue.getDefaultInstance()), - builder.getInt32ToMessageField()); + assertEquals( + newMap(1, TestMap.MessageValue.getDefaultInstance()), builder.getInt32ToMessageField()); builder.putInt32ToMessageField(2, TestMap.MessageValue.getDefaultInstance()); assertEquals( - newMap(1, TestMap.MessageValue.getDefaultInstance(), - 2, TestMap.MessageValue.getDefaultInstance()), + newMap( + 1, + TestMap.MessageValue.getDefaultInstance(), + 2, + TestMap.MessageValue.getDefaultInstance()), builder.getInt32ToMessageField()); } @@ -405,30 +395,22 @@ public final class MapForProto2LiteTest extends TestCase { ByteString bytes = TestUtil.toBytes("SOME BYTES"); String stringKey = "a string key"; - TestMap map = tryParseTestMap(BizarroTestMap.newBuilder() - .putInt32ToInt32Field(5, bytes) - .build()); + TestMap map = + tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToInt32Field(5, bytes).build()); assertEquals(0, map.getInt32ToInt32FieldOrDefault(5, -1)); - map = tryParseTestMap(BizarroTestMap.newBuilder() - .putInt32ToStringField(stringKey, 5) - .build()); + map = tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToStringField(stringKey, 5).build()); assertEquals("", map.getInt32ToStringFieldOrDefault(0, null)); - map = tryParseTestMap(BizarroTestMap.newBuilder() - .putInt32ToBytesField(stringKey, 5) - .build()); + map = tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToBytesField(stringKey, 5).build()); assertEquals(map.getInt32ToBytesFieldOrDefault(0, null), ByteString.EMPTY); - map = tryParseTestMap(BizarroTestMap.newBuilder() - .putInt32ToEnumField(stringKey, bytes) - .build()); + map = + tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToEnumField(stringKey, bytes).build()); assertEquals(TestMap.EnumValue.FOO, map.getInt32ToEnumFieldOrDefault(0, null)); try { - tryParseTestMap(BizarroTestMap.newBuilder() - .putInt32ToMessageField(stringKey, bytes) - .build()); + tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToMessageField(stringKey, bytes).build()); fail(); } catch (InvalidProtocolBufferException expected) { assertTrue(expected.getUnfinishedMessage() instanceof TestMap); @@ -436,9 +418,9 @@ public final class MapForProto2LiteTest extends TestCase { assertTrue(map.getInt32ToMessageField().isEmpty()); } - map = tryParseTestMap(BizarroTestMap.newBuilder() - .putStringToInt32Field(stringKey, bytes) - .build()); + map = + tryParseTestMap( + BizarroTestMap.newBuilder().putStringToInt32Field(stringKey, bytes).build()); assertEquals(0, map.getStringToInt32FieldOrDefault(stringKey, -1)); } @@ -458,16 +440,18 @@ public final class MapForProto2LiteTest extends TestCase { // We can't control the order of elements in a HashMap. The best we can do // here is to add elements in different order. - TestMap.Builder b1 = TestMap.newBuilder() - .putInt32ToInt32Field(1, 2) - .putInt32ToInt32Field(3, 4) - .putInt32ToInt32Field(5, 6); + TestMap.Builder b1 = + TestMap.newBuilder() + .putInt32ToInt32Field(1, 2) + .putInt32ToInt32Field(3, 4) + .putInt32ToInt32Field(5, 6); TestMap m1 = b1.build(); - TestMap.Builder b2 = TestMap.newBuilder() - .putInt32ToInt32Field(5, 6) - .putInt32ToInt32Field(1, 2) - .putInt32ToInt32Field(3, 4); + TestMap.Builder b2 = + TestMap.newBuilder() + .putInt32ToInt32Field(5, 6) + .putInt32ToInt32Field(1, 2) + .putInt32ToInt32Field(3, 4); TestMap m2 = b2.build(); assertEquals(m1, m2); @@ -482,9 +466,8 @@ public final class MapForProto2LiteTest extends TestCase { } public void testUnknownEnumValues() throws Exception { - TestUnknownEnumValue.Builder builder = TestUnknownEnumValue.newBuilder() - .putInt32ToInt32Field(1, 1) - .putInt32ToInt32Field(2, 54321); + TestUnknownEnumValue.Builder builder = + TestUnknownEnumValue.newBuilder().putInt32ToInt32Field(1, 1).putInt32ToInt32Field(2, 54321); ByteString data = builder.build().toByteString(); TestMap message = TestMap.parseFrom(data); @@ -494,8 +477,7 @@ public final class MapForProto2LiteTest extends TestCase { assertEquals(TestMap.EnumValue.BAR, message.getInt32ToEnumField().get(1)); // Serializing and parsing should preserve the unknown entry. data = message.toByteString(); - TestUnknownEnumValue messageWithUnknownEnums = - TestUnknownEnumValue.parseFrom(data); + TestUnknownEnumValue messageWithUnknownEnums = TestUnknownEnumValue.parseFrom(data); assertEquals(2, messageWithUnknownEnums.getInt32ToInt32Field().size()); assertEquals(1, messageWithUnknownEnums.getInt32ToInt32Field().get(1).intValue()); assertEquals(54321, messageWithUnknownEnums.getInt32ToInt32Field().get(2).intValue()); @@ -506,18 +488,19 @@ public final class MapForProto2LiteTest extends TestCase { setMapValues(builder); TestMap message = builder.build(); - assertEquals(Arrays.asList("1", "2", "3"), + assertEquals( + Arrays.asList("1", "2", "3"), new ArrayList(message.getStringToInt32Field().keySet())); } private static Map newMap(K key1, V value1) { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put(key1, value1); return map; } private static Map newMap(K key1, V value1, K key2, V value2) { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put(key1, value1); map.put(key2, value2); return map; @@ -527,18 +510,10 @@ public final class MapForProto2LiteTest extends TestCase { TestMap.Builder builder = TestMap.newBuilder(); setMapValues(builder); TestMap message = builder.build(); - assertEquals( - message.getStringToInt32Field(), - message.getStringToInt32FieldMap()); - assertEquals( - message.getInt32ToBytesField(), - message.getInt32ToBytesFieldMap()); - assertEquals( - message.getInt32ToEnumField(), - message.getInt32ToEnumFieldMap()); - assertEquals( - message.getInt32ToMessageField(), - message.getInt32ToMessageFieldMap()); + assertEquals(message.getStringToInt32Field(), message.getStringToInt32FieldMap()); + assertEquals(message.getInt32ToBytesField(), message.getInt32ToBytesFieldMap()); + assertEquals(message.getInt32ToEnumField(), message.getInt32ToEnumFieldMap()); + assertEquals(message.getInt32ToMessageField(), message.getInt32ToMessageFieldMap()); } public void testContains() { @@ -629,7 +604,8 @@ public final class MapForProto2LiteTest extends TestCase { assertEquals(TestMap.EnumValue.FOO, testMapOrBuilder.getInt32ToEnumFieldOrDefault(1, null)); assertNull(testMapOrBuilder.getInt32ToEnumFieldOrDefault(-1, null)); - assertEquals(MessageValue.newBuilder().setValue(11).build(), + assertEquals( + MessageValue.newBuilder().setValue(11).build(), testMapOrBuilder.getInt32ToMessageFieldOrDefault(1, null)); assertNull(testMapOrBuilder.getInt32ToMessageFieldOrDefault(-1, null)); @@ -687,7 +663,8 @@ public final class MapForProto2LiteTest extends TestCase { // expected } - assertEquals(MessageValue.newBuilder().setValue(11).build(), + assertEquals( + MessageValue.newBuilder().setValue(11).build(), testMapOrBuilder.getInt32ToMessageFieldOrThrow(1)); try { testMapOrBuilder.getInt32ToMessageFieldOrThrow(-1); diff --git a/java/core/src/test/java/com/google/protobuf/MapTest.java b/java/core/src/test/java/com/google/protobuf/MapTest.java index 58efce92c0..ef8b27e8d5 100644 --- a/java/core/src/test/java/com/google/protobuf/MapTest.java +++ b/java/core/src/test/java/com/google/protobuf/MapTest.java @@ -31,6 +31,7 @@ package com.google.protobuf; import static org.junit.Assert.assertArrayEquals; + import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.EnumDescriptor; import com.google.protobuf.Descriptors.EnumValueDescriptor; @@ -51,9 +52,7 @@ import java.util.List; import java.util.Map; import junit.framework.TestCase; -/** - * Unit tests for map fields. - */ +/** Unit tests for map fields. */ public class MapTest extends TestCase { private void setMapValuesUsingMutableMap(TestMap.Builder builder) { @@ -90,23 +89,18 @@ public class MapTest extends TestCase { .putInt32ToInt32Field(1, 11) .putInt32ToInt32Field(2, 22) .putInt32ToInt32Field(3, 33) - .putInt32ToStringField(1, "11") .putInt32ToStringField(2, "22") .putInt32ToStringField(3, "33") - .putInt32ToBytesField(1, TestUtil.toBytes("11")) .putInt32ToBytesField(2, TestUtil.toBytes("22")) .putInt32ToBytesField(3, TestUtil.toBytes("33")) - .putInt32ToEnumField(1, TestMap.EnumValue.FOO) .putInt32ToEnumField(2, TestMap.EnumValue.BAR) .putInt32ToEnumField(3, TestMap.EnumValue.BAZ) - .putInt32ToMessageField(1, MessageValue.newBuilder().setValue(11).build()) .putInt32ToMessageField(2, MessageValue.newBuilder().setValue(22).build()) .putInt32ToMessageField(3, MessageValue.newBuilder().setValue(33).build()) - .putStringToInt32Field("1", 11) .putStringToInt32Field("2", 22) .putStringToInt32Field("3", 33); @@ -201,23 +195,18 @@ public class MapTest extends TestCase { .putInt32ToInt32Field(1, 111) .removeInt32ToInt32Field(2) .putInt32ToInt32Field(4, 44) - .putInt32ToStringField(1, "111") .removeInt32ToStringField(2) .putInt32ToStringField(4, "44") - .putInt32ToBytesField(1, TestUtil.toBytes("111")) .removeInt32ToBytesField(2) .putInt32ToBytesField(4, TestUtil.toBytes("44")) - .putInt32ToEnumField(1, TestMap.EnumValue.BAR) .removeInt32ToEnumField(2) .putInt32ToEnumField(4, TestMap.EnumValue.QUX) - .putInt32ToMessageField(1, MessageValue.newBuilder().setValue(111).build()) .removeInt32ToMessageField(2) .putInt32ToMessageField(4, MessageValue.newBuilder().setValue(44).build()) - .putStringToInt32Field("1", 111) .removeStringToInt32Field("2") .putStringToInt32Field("4", 44); @@ -435,7 +424,6 @@ public class MapTest extends TestCase { assertEquals(newMap(1, 2), builder.build().getInt32ToInt32Field()); } - public void testGettersAndSetters() throws Exception { TestMap.Builder builder = TestMap.newBuilder(); TestMap message = builder.build(); @@ -470,16 +458,17 @@ public class MapTest extends TestCase { } public void testPutAllForUnknownEnumValues() throws Exception { - TestMap source = TestMap.newBuilder() - .putAllInt32ToEnumFieldValue(newMap( - 0, 0, - 1, 1, - 2, 1000)) // unknown value. - .build(); + TestMap source = + TestMap.newBuilder() + .putAllInt32ToEnumFieldValue( + newMap( + 0, 0, + 1, 1, + 2, 1000)) // unknown value. + .build(); - TestMap destination = TestMap.newBuilder() - .putAllInt32ToEnumFieldValue(source.getInt32ToEnumFieldValue()) - .build(); + TestMap destination = + TestMap.newBuilder().putAllInt32ToEnumFieldValue(source.getInt32ToEnumFieldValue()).build(); assertEquals(0, destination.getInt32ToEnumFieldValue().get(0).intValue()); assertEquals(1, destination.getInt32ToEnumFieldValue().get(1).intValue()); @@ -488,10 +477,11 @@ public class MapTest extends TestCase { } public void testPutForUnknownEnumValues() throws Exception { - TestMap.Builder builder = TestMap.newBuilder() - .putInt32ToEnumFieldValue(0, 0) - .putInt32ToEnumFieldValue(1, 1) - .putInt32ToEnumFieldValue(2, 1000); // unknown value. + TestMap.Builder builder = + TestMap.newBuilder() + .putInt32ToEnumFieldValue(0, 0) + .putInt32ToEnumFieldValue(1, 1) + .putInt32ToEnumFieldValue(2, 1000); // unknown value. TestMap message = builder.build(); assertEquals(0, message.getInt32ToEnumFieldValueOrThrow(0)); assertEquals(1, message.getInt32ToEnumFieldValueOrThrow(1)); @@ -573,30 +563,22 @@ public class MapTest extends TestCase { ByteString bytes = TestUtil.toBytes("SOME BYTES"); String stringKey = "a string key"; - TestMap map = tryParseTestMap(BizarroTestMap.newBuilder() - .putInt32ToInt32Field(5, bytes) - .build()); + TestMap map = + tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToInt32Field(5, bytes).build()); assertEquals(0, map.getInt32ToInt32FieldOrDefault(5, -1)); - map = tryParseTestMap(BizarroTestMap.newBuilder() - .putInt32ToStringField(stringKey, 5) - .build()); + map = tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToStringField(stringKey, 5).build()); assertEquals("", map.getInt32ToStringFieldOrDefault(0, null)); - map = tryParseTestMap(BizarroTestMap.newBuilder() - .putInt32ToBytesField(stringKey, 5) - .build()); + map = tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToBytesField(stringKey, 5).build()); assertEquals(map.getInt32ToBytesFieldOrDefault(0, null), ByteString.EMPTY); - map = tryParseTestMap(BizarroTestMap.newBuilder() - .putInt32ToEnumField(stringKey, bytes) - .build()); + map = + tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToEnumField(stringKey, bytes).build()); assertEquals(TestMap.EnumValue.FOO, map.getInt32ToEnumFieldOrDefault(0, null)); try { - tryParseTestMap(BizarroTestMap.newBuilder() - .putInt32ToMessageField(stringKey, bytes) - .build()); + tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToMessageField(stringKey, bytes).build()); fail(); } catch (InvalidProtocolBufferException expected) { assertTrue(expected.getUnfinishedMessage() instanceof TestMap); @@ -604,9 +586,9 @@ public class MapTest extends TestCase { assertTrue(map.getInt32ToMessageField().isEmpty()); } - map = tryParseTestMap(BizarroTestMap.newBuilder() - .putStringToInt32Field(stringKey, bytes) - .build()); + map = + tryParseTestMap( + BizarroTestMap.newBuilder().putStringToInt32Field(stringKey, bytes).build()); assertEquals(0, map.getStringToInt32FieldOrDefault(stringKey, -1)); } @@ -626,16 +608,18 @@ public class MapTest extends TestCase { // We can't control the order of elements in a HashMap. The best we can do // here is to add elements in different order. - TestMap.Builder b1 = TestMap.newBuilder() - .putInt32ToInt32Field(1, 2) - .putInt32ToInt32Field(3, 4) - .putInt32ToInt32Field(5, 6); + TestMap.Builder b1 = + TestMap.newBuilder() + .putInt32ToInt32Field(1, 2) + .putInt32ToInt32Field(3, 4) + .putInt32ToInt32Field(5, 6); TestMap m1 = b1.build(); - TestMap.Builder b2 = TestMap.newBuilder() - .putInt32ToInt32Field(5, 6) - .putInt32ToInt32Field(1, 2) - .putInt32ToInt32Field(3, 4); + TestMap.Builder b2 = + TestMap.newBuilder() + .putInt32ToInt32Field(5, 6) + .putInt32ToInt32Field(1, 2) + .putInt32ToInt32Field(3, 4); TestMap m2 = b2.build(); assertEquals(m1, m2); @@ -657,8 +641,7 @@ public class MapTest extends TestCase { } public void testNestedBuilderOnChangeEventPropagation() { - TestOnChangeEventPropagation.Builder parent = - TestOnChangeEventPropagation.newBuilder(); + TestOnChangeEventPropagation.Builder parent = TestOnChangeEventPropagation.newBuilder(); parent.getOptionalMessageBuilder().putInt32ToInt32Field(1, 2); TestOnChangeEventPropagation message = parent.build(); assertEquals(2, message.getOptionalMessage().getInt32ToInt32Field().get(1).intValue()); @@ -689,16 +672,14 @@ public class MapTest extends TestCase { public void testNestedBuilderOnChangeEventPropagationReflection() { FieldDescriptor intMapField = f("int32_to_int32_field"); // Create an outer message builder with nested builder. - TestOnChangeEventPropagation.Builder parentBuilder = - TestOnChangeEventPropagation.newBuilder(); + TestOnChangeEventPropagation.Builder parentBuilder = TestOnChangeEventPropagation.newBuilder(); TestMap.Builder testMapBuilder = parentBuilder.getOptionalMessageBuilder(); // Create a map entry message. TestMap.Builder entryBuilder = TestMap.newBuilder().putInt32ToInt32Field(1, 1); // Put the entry into the nested builder. - testMapBuilder.addRepeatedField( - intMapField, entryBuilder.getRepeatedField(intMapField, 0)); + testMapBuilder.addRepeatedField(intMapField, entryBuilder.getRepeatedField(intMapField, 0)); // Should be able to observe the change. TestOnChangeEventPropagation message = parentBuilder.build(); @@ -707,13 +688,11 @@ public class MapTest extends TestCase { // Change the entry value. entryBuilder.putInt32ToInt32Field(1, 4); testMapBuilder = parentBuilder.getOptionalMessageBuilder(); - testMapBuilder.setRepeatedField( - intMapField, 0, entryBuilder.getRepeatedField(intMapField, 0)); + testMapBuilder.setRepeatedField(intMapField, 0, entryBuilder.getRepeatedField(intMapField, 0)); // Should be able to observe the change. message = parentBuilder.build(); - assertEquals(4, - message.getOptionalMessage().getInt32ToInt32Field().get(1).intValue()); + assertEquals(4, message.getOptionalMessage().getInt32ToInt32Field().get(1).intValue()); // Clear the nested builder. testMapBuilder = parentBuilder.getOptionalMessageBuilder(); @@ -761,8 +740,7 @@ public class MapTest extends TestCase { } } - private static - Message newMapEntry(Message.Builder builder, String name, KeyType key, ValueType value) { + private static Message newMapEntry(Message.Builder builder, String name, K key, V value) { FieldDescriptor field = builder.getDescriptorForType().findFieldByName(name); Message.Builder entryBuilder = builder.newBuilderForField(field); FieldDescriptor keyField = entryBuilder.getDescriptorForType().findFieldByName("key"); @@ -781,10 +759,8 @@ public class MapTest extends TestCase { builder.setField(field, entryList); } - private static - Map mapForValues( - KeyType key1, ValueType value1, KeyType key2, ValueType value2) { - Map map = new HashMap(); + private static Map mapForValues(K key1, V value1, K key2, V value2) { + Map map = new HashMap(); map.put(key1, value1); map.put(key2, value2); return map; @@ -792,17 +768,19 @@ public class MapTest extends TestCase { public void testReflectionApi() throws Exception { // In reflection API, map fields are just repeated message fields. - TestMap.Builder builder = TestMap.newBuilder() - .putInt32ToInt32Field(1, 2) - .putInt32ToInt32Field(3, 4) - .putInt32ToMessageField(11, MessageValue.newBuilder().setValue(22).build()) - .putInt32ToMessageField(33, MessageValue.newBuilder().setValue(44).build()); + TestMap.Builder builder = + TestMap.newBuilder() + .putInt32ToInt32Field(1, 2) + .putInt32ToInt32Field(3, 4) + .putInt32ToMessageField(11, MessageValue.newBuilder().setValue(22).build()) + .putInt32ToMessageField(33, MessageValue.newBuilder().setValue(44).build()); TestMap message = builder.build(); // Test getField(), getRepeatedFieldCount(), getRepeatedField(). - assertHasMapValues(message, "int32_to_int32_field", - mapForValues(1, 2, 3, 4)); - assertHasMapValues(message, "int32_to_message_field", + assertHasMapValues(message, "int32_to_int32_field", mapForValues(1, 2, 3, 4)); + assertHasMapValues( + message, + "int32_to_message_field", mapForValues( 11, MessageValue.newBuilder().setValue(22).build(), 33, MessageValue.newBuilder().setValue(44).build())); @@ -815,9 +793,10 @@ public class MapTest extends TestCase { assertEquals(0, message.getInt32ToMessageField().size()); // Test setField() - setMapValues(builder, "int32_to_int32_field", - mapForValues(11, 22, 33, 44)); - setMapValues(builder, "int32_to_message_field", + setMapValues(builder, "int32_to_int32_field", mapForValues(11, 22, 33, 44)); + setMapValues( + builder, + "int32_to_message_field", mapForValues( 111, MessageValue.newBuilder().setValue(222).build(), 333, MessageValue.newBuilder().setValue(444).build())); @@ -828,20 +807,28 @@ public class MapTest extends TestCase { assertEquals(444, message.getInt32ToMessageField().get(333).getValue()); // Test addRepeatedField - builder.addRepeatedField(f("int32_to_int32_field"), - newMapEntry(builder, "int32_to_int32_field", 55, 66)); - builder.addRepeatedField(f("int32_to_message_field"), - newMapEntry(builder, "int32_to_message_field", 555, + builder.addRepeatedField( + f("int32_to_int32_field"), newMapEntry(builder, "int32_to_int32_field", 55, 66)); + builder.addRepeatedField( + f("int32_to_message_field"), + newMapEntry( + builder, + "int32_to_message_field", + 555, MessageValue.newBuilder().setValue(666).build())); message = builder.build(); assertEquals(66, message.getInt32ToInt32Field().get(55).intValue()); assertEquals(666, message.getInt32ToMessageField().get(555).getValue()); // Test addRepeatedField (overriding existing values) - builder.addRepeatedField(f("int32_to_int32_field"), - newMapEntry(builder, "int32_to_int32_field", 55, 55)); - builder.addRepeatedField(f("int32_to_message_field"), - newMapEntry(builder, "int32_to_message_field", 555, + builder.addRepeatedField( + f("int32_to_int32_field"), newMapEntry(builder, "int32_to_int32_field", 55, 55)); + builder.addRepeatedField( + f("int32_to_message_field"), + newMapEntry( + builder, + "int32_to_message_field", + 555, MessageValue.newBuilder().setValue(555).build())); message = builder.build(); assertEquals(55, message.getInt32ToInt32Field().get(55).intValue()); @@ -884,10 +871,9 @@ public class MapTest extends TestCase { setMapValuesUsingAccessors(builder); TestMap message = builder.build(); - Message dynamicDefaultInstance = - DynamicMessage.getDefaultInstance(TestMap.getDescriptor()); - Message dynamicMessage = dynamicDefaultInstance - .newBuilderForType().mergeFrom(message.toByteString()).build(); + Message dynamicDefaultInstance = DynamicMessage.getDefaultInstance(TestMap.getDescriptor()); + Message dynamicMessage = + dynamicDefaultInstance.newBuilderForType().mergeFrom(message.toByteString()).build(); assertEquals(message, dynamicMessage); assertEquals(message.hashCode(), dynamicMessage.hashCode()); @@ -898,8 +884,7 @@ public class MapTest extends TestCase { public void testDynamicMessageUnsetKeyAndValue() throws Exception { FieldDescriptor field = f("int32_to_int32_field"); - Message dynamicDefaultInstance = - DynamicMessage.getDefaultInstance(TestMap.getDescriptor()); + Message dynamicDefaultInstance = DynamicMessage.getDefaultInstance(TestMap.getDescriptor()); Message.Builder builder = dynamicDefaultInstance.newBuilderForType(); // Add an entry without key and value. builder.addRepeatedField(field, builder.newBuilderForField(field).build()); @@ -916,8 +901,7 @@ public class MapTest extends TestCase { // of map entries when comparing/hashing map fields. // We use DynamicMessage to test reflection based equals()/hashCode(). - Message dynamicDefaultInstance = - DynamicMessage.getDefaultInstance(TestMap.getDescriptor()); + Message dynamicDefaultInstance = DynamicMessage.getDefaultInstance(TestMap.getDescriptor()); FieldDescriptor field = f("int32_to_int32_field"); Message.Builder b1 = dynamicDefaultInstance.newBuilderForType(); @@ -944,19 +928,18 @@ public class MapTest extends TestCase { } public void testUnknownEnumValues() throws Exception { - TestMap.Builder builder = TestMap.newBuilder() - .putAllInt32ToEnumFieldValue(newMap( - 0, 0, - 1, 1, - 2, 1000)); // unknown value. + TestMap.Builder builder = + TestMap.newBuilder() + .putAllInt32ToEnumFieldValue( + newMap( + 0, 0, + 1, 1, + 2, 1000)); // unknown value. TestMap message = builder.build(); - assertEquals(TestMap.EnumValue.FOO, - message.getInt32ToEnumField().get(0)); - assertEquals(TestMap.EnumValue.BAR, - message.getInt32ToEnumField().get(1)); - assertEquals(TestMap.EnumValue.UNRECOGNIZED, - message.getInt32ToEnumField().get(2)); + assertEquals(TestMap.EnumValue.FOO, message.getInt32ToEnumField().get(0)); + assertEquals(TestMap.EnumValue.BAR, message.getInt32ToEnumField().get(1)); + assertEquals(TestMap.EnumValue.UNRECOGNIZED, message.getInt32ToEnumField().get(2)); assertEquals(1000, message.getInt32ToEnumFieldValue().get(2).intValue()); // Unknown enum values should be preserved after: @@ -977,7 +960,7 @@ public class MapTest extends TestCase { assertFalse(message.equals(message2)); // Unknown values will be converted to UNRECOGNIZED so the resulted enum map // should be the same. - assertTrue(message.getInt32ToEnumField().equals(message2.getInt32ToEnumField())); + assertEquals(message2.getInt32ToEnumField(), message.getInt32ToEnumField()); } public void testUnknownEnumValuesInReflectionApi() throws Exception { @@ -985,13 +968,13 @@ public class MapTest extends TestCase { EnumDescriptor enumDescriptor = TestMap.EnumValue.getDescriptor(); FieldDescriptor field = descriptor.findFieldByName("int32_to_enum_field"); - Map data = newMap( - 0, 0, - 1, 1, - 2, 1000); // unknown value + Map data = + newMap( + 0, 0, + 1, 1, + 2, 1000); // unknown value - TestMap.Builder builder = TestMap.newBuilder() - .putAllInt32ToEnumFieldValue(data); + TestMap.Builder builder = TestMap.newBuilder().putAllInt32ToEnumFieldValue(data); // Try to read unknown enum values using reflection API. for (int i = 0; i < builder.getRepeatedFieldCount(field); i++) { @@ -1001,8 +984,8 @@ public class MapTest extends TestCase { assertEquals(data.get(key).intValue(), value); Message.Builder mapEntryBuilder = mapEntry.toBuilder(); // Increase the value by 1. - setFieldValue(mapEntryBuilder, "value", - enumDescriptor.findValueByNumberCreatingIfUnknown(value + 1)); + setFieldValue( + mapEntryBuilder, "value", enumDescriptor.findValueByNumberCreatingIfUnknown(value + 1)); builder.setRepeatedField(field, i, mapEntryBuilder.build()); } @@ -1018,7 +1001,8 @@ public class MapTest extends TestCase { setMapValuesUsingAccessors(builder); TestMap message = builder.build(); - assertEquals(Arrays.asList("1", "2", "3"), + assertEquals( + Arrays.asList("1", "2", "3"), new ArrayList(message.getStringToInt32Field().keySet())); } @@ -1026,21 +1010,11 @@ public class MapTest extends TestCase { TestMap.Builder builder = TestMap.newBuilder(); setMapValuesUsingAccessors(builder); TestMap message = builder.build(); - assertEquals( - message.getStringToInt32Field(), - message.getStringToInt32FieldMap()); - assertEquals( - message.getInt32ToBytesField(), - message.getInt32ToBytesFieldMap()); - assertEquals( - message.getInt32ToEnumField(), - message.getInt32ToEnumFieldMap()); - assertEquals( - message.getInt32ToEnumFieldValue(), - message.getInt32ToEnumFieldValueMap()); - assertEquals( - message.getInt32ToMessageField(), - message.getInt32ToMessageFieldMap()); + assertEquals(message.getStringToInt32Field(), message.getStringToInt32FieldMap()); + assertEquals(message.getInt32ToBytesField(), message.getInt32ToBytesFieldMap()); + assertEquals(message.getInt32ToEnumField(), message.getInt32ToEnumFieldMap()); + assertEquals(message.getInt32ToEnumFieldValue(), message.getInt32ToEnumFieldValueMap()); + assertEquals(message.getInt32ToMessageField(), message.getInt32ToMessageFieldMap()); } public void testContains() { @@ -1133,10 +1107,11 @@ public class MapTest extends TestCase { assertEquals( TestMap.EnumValue.BAR.getNumber(), - (int) testMapOrBuilder.getInt32ToEnumFieldValueOrDefault(2, -1)); + testMapOrBuilder.getInt32ToEnumFieldValueOrDefault(2, -1)); assertEquals(-1, testMapOrBuilder.getInt32ToEnumFieldValueOrDefault(-1000, -1)); - assertEquals(MessageValue.newBuilder().setValue(11).build(), + assertEquals( + MessageValue.newBuilder().setValue(11).build(), testMapOrBuilder.getInt32ToMessageFieldOrDefault(1, null)); assertNull(testMapOrBuilder.getInt32ToMessageFieldOrDefault(-1, null)); @@ -1203,7 +1178,8 @@ public class MapTest extends TestCase { // expected } - assertEquals(MessageValue.newBuilder().setValue(11).build(), + assertEquals( + MessageValue.newBuilder().setValue(11).build(), testMapOrBuilder.getInt32ToMessageFieldOrThrow(1)); try { testMapOrBuilder.getInt32ToMessageFieldOrThrow(-1); @@ -1261,8 +1237,7 @@ public class MapTest extends TestCase { } builder.putInt32ToEnumFieldValue(1, TestMap.EnumValue.BAR.getNumber()); - assertEquals( - TestMap.EnumValue.BAR.getNumber(), builder.getInt32ToEnumFieldValueOrThrow(1)); + assertEquals(TestMap.EnumValue.BAR.getNumber(), builder.getInt32ToEnumFieldValueOrThrow(1)); builder.putInt32ToEnumFieldValue(1, -1); assertEquals(-1, builder.getInt32ToEnumFieldValueOrThrow(1)); assertEquals(TestMap.EnumValue.UNRECOGNIZED, builder.getInt32ToEnumFieldOrThrow(1)); @@ -1391,18 +1366,10 @@ public class MapTest extends TestCase { } input.popLimit(oldLimit); } - assertEquals( - Arrays.asList(-2, 0, 1, 4, 5), - int32Keys); - assertEquals( - Arrays.asList(-2, 0, 1, 4, 5), - uint32Keys); - assertEquals( - Arrays.asList(-2L, 0L, 1L, 4L, 5L), - int64Keys); - assertEquals( - Arrays.asList("", "bar", "baz", "foo", "hello", "world"), - stringKeys); + assertEquals(Arrays.asList(-2, 0, 1, 4, 5), int32Keys); + assertEquals(Arrays.asList(-2, 0, 1, 4, 5), uint32Keys); + assertEquals(Arrays.asList(-2L, 0L, 1L, 4L, 5L), int64Keys); + assertEquals(Arrays.asList("", "bar", "baz", "foo", "hello", "world"), stringKeys); } public void testInitFromPartialDynamicMessage() { @@ -1525,8 +1492,7 @@ public class MapTest extends TestCase { } try { - builder.putAllInt32ToMessageField( - MapTest.newMap(4, null, 5, null)); + builder.putAllInt32ToMessageField(MapTest.newMap(4, null, 5, null)); fail(); } catch (NullPointerException expected) { } diff --git a/java/core/src/test/java/com/google/protobuf/MessageTest.java b/java/core/src/test/java/com/google/protobuf/MessageTest.java index 4fc8f78e03..760511b635 100644 --- a/java/core/src/test/java/com/google/protobuf/MessageTest.java +++ b/java/core/src/test/java/com/google/protobuf/MessageTest.java @@ -39,8 +39,7 @@ import java.util.List; import junit.framework.TestCase; /** - * Misc. unit tests for message operations that apply to both generated - * and dynamic messages. + * Misc. unit tests for message operations that apply to both generated and dynamic messages. * * @author kenton@google.com Kenton Varda */ @@ -49,30 +48,31 @@ public class MessageTest extends TestCase { // Message-merging tests. static final TestAllTypes MERGE_SOURCE = - TestAllTypes.newBuilder() - .setOptionalInt32(1) - .setOptionalString("foo") - .setOptionalForeignMessage(ForeignMessage.getDefaultInstance()) - .addRepeatedString("bar") - .build(); + TestAllTypes.newBuilder() + .setOptionalInt32(1) + .setOptionalString("foo") + .setOptionalForeignMessage(ForeignMessage.getDefaultInstance()) + .addRepeatedString("bar") + .build(); static final TestAllTypes MERGE_DEST = - TestAllTypes.newBuilder() - .setOptionalInt64(2) - .setOptionalString("baz") - .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(3).build()) - .addRepeatedString("qux") - .build(); + TestAllTypes.newBuilder() + .setOptionalInt64(2) + .setOptionalString("baz") + .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(3).build()) + .addRepeatedString("qux") + .build(); static final String MERGE_RESULT_TEXT = - "optional_int32: 1\n" + - "optional_int64: 2\n" + - "optional_string: \"foo\"\n" + - "optional_foreign_message {\n" + - " c: 3\n" + - "}\n" + - "repeated_string: \"qux\"\n" + - "repeated_string: \"bar\"\n"; + "" + + "optional_int32: 1\n" + + "optional_int64: 2\n" + + "optional_string: \"foo\"\n" + + "optional_foreign_message {\n" + + " c: 3\n" + + "}\n" + + "repeated_string: \"qux\"\n" + + "repeated_string: \"bar\"\n"; public void testParsingWithNullExtensionRegistry() throws Exception { try { @@ -83,23 +83,20 @@ public class MessageTest extends TestCase { } public void testMergeFrom() throws Exception { - TestAllTypes result = - TestAllTypes.newBuilder(MERGE_DEST) - .mergeFrom(MERGE_SOURCE).build(); + TestAllTypes result = TestAllTypes.newBuilder(MERGE_DEST).mergeFrom(MERGE_SOURCE).build(); assertEquals(MERGE_RESULT_TEXT, result.toString()); } /** - * Test merging a DynamicMessage into a GeneratedMessage. As long as they - * have the same descriptor, this should work, but it is an entirely different - * code path. + * Test merging a DynamicMessage into a GeneratedMessage. As long as they have the same + * descriptor, this should work, but it is an entirely different code path. */ public void testMergeFromDynamic() throws Exception { TestAllTypes result = - TestAllTypes.newBuilder(MERGE_DEST) - .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build()) - .build(); + TestAllTypes.newBuilder(MERGE_DEST) + .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build()) + .build(); assertEquals(MERGE_RESULT_TEXT, result.toString()); } @@ -107,9 +104,9 @@ public class MessageTest extends TestCase { /** Test merging two DynamicMessages. */ public void testDynamicMergeFrom() throws Exception { DynamicMessage result = - DynamicMessage.newBuilder(MERGE_DEST) - .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build()) - .build(); + DynamicMessage.newBuilder(MERGE_DEST) + .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build()) + .build(); assertEquals(MERGE_RESULT_TEXT, result.toString()); } @@ -117,10 +114,9 @@ public class MessageTest extends TestCase { // ================================================================= // Required-field-related tests. - private static final TestRequired TEST_REQUIRED_UNINITIALIZED = - TestRequired.getDefaultInstance(); + private static final TestRequired TEST_REQUIRED_UNINITIALIZED = TestRequired.getDefaultInstance(); private static final TestRequired TEST_REQUIRED_INITIALIZED = - TestRequired.newBuilder().setA(1).setB(2).setC(3).build(); + TestRequired.newBuilder().setA(1).setB(2).setC(3).build(); public void testRequired() throws Exception { TestRequired.Builder builder = TestRequired.newBuilder(); @@ -189,20 +185,18 @@ public class MessageTest extends TestCase { assertTrue(builder.isInitialized()); - builder.setField(descriptor.findFieldByName("optional_message"), - TEST_REQUIRED_UNINITIALIZED); + builder.setField(descriptor.findFieldByName("optional_message"), TEST_REQUIRED_UNINITIALIZED); assertFalse(builder.isInitialized()); - builder.setField(descriptor.findFieldByName("optional_message"), - TEST_REQUIRED_INITIALIZED); + builder.setField(descriptor.findFieldByName("optional_message"), TEST_REQUIRED_INITIALIZED); assertTrue(builder.isInitialized()); - builder.addRepeatedField(descriptor.findFieldByName("repeated_message"), - TEST_REQUIRED_UNINITIALIZED); + builder.addRepeatedField( + descriptor.findFieldByName("repeated_message"), TEST_REQUIRED_UNINITIALIZED); assertFalse(builder.isInitialized()); - builder.setRepeatedField(descriptor.findFieldByName("repeated_message"), 0, - TEST_REQUIRED_INITIALIZED); + builder.setRepeatedField( + descriptor.findFieldByName("repeated_message"), 0, TEST_REQUIRED_INITIALIZED); assertTrue(builder.isInitialized()); } @@ -224,35 +218,35 @@ public class MessageTest extends TestCase { public void testNestedUninitializedException() throws Exception { try { TestRequiredForeign.newBuilder() - .setOptionalMessage(TEST_REQUIRED_UNINITIALIZED) - .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED) - .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED) - .build(); + .setOptionalMessage(TEST_REQUIRED_UNINITIALIZED) + .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED) + .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED) + .build(); fail("Should have thrown an exception."); } catch (UninitializedMessageException e) { assertEquals( - "Message missing required fields: " + - "optional_message.a, " + - "optional_message.b, " + - "optional_message.c, " + - "repeated_message[0].a, " + - "repeated_message[0].b, " + - "repeated_message[0].c, " + - "repeated_message[1].a, " + - "repeated_message[1].b, " + - "repeated_message[1].c", - e.getMessage()); + "Message missing required fields: " + + "optional_message.a, " + + "optional_message.b, " + + "optional_message.c, " + + "repeated_message[0].a, " + + "repeated_message[0].b, " + + "repeated_message[0].c, " + + "repeated_message[1].a, " + + "repeated_message[1].b, " + + "repeated_message[1].c", + e.getMessage()); } } public void testBuildNestedPartial() throws Exception { // We're mostly testing that no exception is thrown. TestRequiredForeign message = - TestRequiredForeign.newBuilder() - .setOptionalMessage(TEST_REQUIRED_UNINITIALIZED) - .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED) - .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED) - .buildPartial(); + TestRequiredForeign.newBuilder() + .setOptionalMessage(TEST_REQUIRED_UNINITIALIZED) + .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED) + .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED) + .buildPartial(); assertFalse(message.isInitialized()); } @@ -267,28 +261,29 @@ public class MessageTest extends TestCase { public void testParseNestedUnititialized() throws Exception { ByteString data = - TestRequiredForeign.newBuilder() - .setOptionalMessage(TEST_REQUIRED_UNINITIALIZED) - .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED) - .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED) - .buildPartial().toByteString(); + TestRequiredForeign.newBuilder() + .setOptionalMessage(TEST_REQUIRED_UNINITIALIZED) + .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED) + .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED) + .buildPartial() + .toByteString(); try { TestRequiredForeign.parseFrom(data); fail("Should have thrown an exception."); } catch (InvalidProtocolBufferException e) { assertEquals( - "Message missing required fields: " + - "optional_message.a, " + - "optional_message.b, " + - "optional_message.c, " + - "repeated_message[0].a, " + - "repeated_message[0].b, " + - "repeated_message[0].c, " + - "repeated_message[1].a, " + - "repeated_message[1].b, " + - "repeated_message[1].c", - e.getMessage()); + "Message missing required fields: " + + "optional_message.a, " + + "optional_message.b, " + + "optional_message.c, " + + "repeated_message[0].a, " + + "repeated_message[0].b, " + + "repeated_message[0].c, " + + "repeated_message[1].a, " + + "repeated_message[1].b, " + + "repeated_message[1].c", + e.getMessage()); } } @@ -303,9 +298,7 @@ public class MessageTest extends TestCase { public void testDynamicBuildPartial() throws Exception { // We're mostly testing that no exception is thrown. - DynamicMessage message = - DynamicMessage.newBuilder(TestRequired.getDescriptor()) - .buildPartial(); + DynamicMessage message = DynamicMessage.newBuilder(TestRequired.getDescriptor()).buildPartial(); assertFalse(message.isInitialized()); } @@ -318,43 +311,44 @@ public class MessageTest extends TestCase { assertEquals("Message missing required fields: a, b, c", e.getMessage()); } } - + /** Test reading unset repeated message from DynamicMessage. */ public void testDynamicRepeatedMessageNull() throws Exception { - Descriptors.Descriptor descriptor = TestRequired.getDescriptor(); + TestRequired.getDescriptor(); DynamicMessage result = - DynamicMessage.newBuilder(TestAllTypes.getDescriptor()) - .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build()) - .build(); + DynamicMessage.newBuilder(TestAllTypes.getDescriptor()) + .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build()) + .build(); - assertTrue(result.getField(result.getDescriptorForType() - .findFieldByName("repeated_foreign_message")) instanceof List); + assertTrue( + result.getField(result.getDescriptorForType().findFieldByName("repeated_foreign_message")) + instanceof List); assertEquals( 0, result.getRepeatedFieldCount( result.getDescriptorForType().findFieldByName("repeated_foreign_message"))); } - + /** Test reading repeated message from DynamicMessage. */ public void testDynamicRepeatedMessageNotNull() throws Exception { - - TestAllTypes REPEATED_NESTED = - TestAllTypes.newBuilder() - .setOptionalInt32(1) - .setOptionalString("foo") - .setOptionalForeignMessage(ForeignMessage.getDefaultInstance()) - .addRepeatedString("bar") - .addRepeatedForeignMessage(ForeignMessage.getDefaultInstance()) - .addRepeatedForeignMessage(ForeignMessage.getDefaultInstance()) - .build(); - Descriptors.Descriptor descriptor = TestRequired.getDescriptor(); + TestAllTypes repeatedNested = + TestAllTypes.newBuilder() + .setOptionalInt32(1) + .setOptionalString("foo") + .setOptionalForeignMessage(ForeignMessage.getDefaultInstance()) + .addRepeatedString("bar") + .addRepeatedForeignMessage(ForeignMessage.getDefaultInstance()) + .addRepeatedForeignMessage(ForeignMessage.getDefaultInstance()) + .build(); + TestRequired.getDescriptor(); DynamicMessage result = - DynamicMessage.newBuilder(TestAllTypes.getDescriptor()) - .mergeFrom(DynamicMessage.newBuilder(REPEATED_NESTED).build()) - .build(); + DynamicMessage.newBuilder(TestAllTypes.getDescriptor()) + .mergeFrom(DynamicMessage.newBuilder(repeatedNested).build()) + .build(); - assertTrue(result.getField(result.getDescriptorForType() - .findFieldByName("repeated_foreign_message")) instanceof List); + assertTrue( + result.getField(result.getDescriptorForType().findFieldByName("repeated_foreign_message")) + instanceof List); assertEquals( 2, result.getRepeatedFieldCount( diff --git a/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java b/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java index 03ed65a550..7bfeaf17c4 100644 --- a/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java +++ b/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java @@ -37,8 +37,8 @@ import java.util.List; import junit.framework.TestCase; /** - * Test cases that exercise end-to-end use cases involving - * {@link SingleFieldBuilder} and {@link RepeatedFieldBuilder}. + * Test cases that exercise end-to-end use cases involving {@link SingleFieldBuilder} and {@link + * RepeatedFieldBuilder}. * * @author jonp@google.com (Jon Perlow) */ @@ -46,20 +46,11 @@ public class NestedBuildersTest extends TestCase { public void testMessagesAndBuilders() { Vehicle.Builder vehicleBuilder = Vehicle.newBuilder(); - vehicleBuilder.addWheelBuilder() - .setRadius(4) - .setWidth(1); - vehicleBuilder.addWheelBuilder() - .setRadius(4) - .setWidth(2); - vehicleBuilder.addWheelBuilder() - .setRadius(4) - .setWidth(3); - vehicleBuilder.addWheelBuilder() - .setRadius(4) - .setWidth(4); - vehicleBuilder.getEngineBuilder() - .setLiters(10); + vehicleBuilder.addWheelBuilder().setRadius(4).setWidth(1); + vehicleBuilder.addWheelBuilder().setRadius(4).setWidth(2); + vehicleBuilder.addWheelBuilder().setRadius(4).setWidth(3); + vehicleBuilder.addWheelBuilder().setRadius(4).setWidth(4); + vehicleBuilder.getEngineBuilder().setLiters(10); Vehicle vehicle = vehicleBuilder.build(); assertEquals(4, vehicle.getWheelCount()); @@ -71,9 +62,7 @@ public class NestedBuildersTest extends TestCase { assertEquals(10, vehicle.getEngine().getLiters()); for (int i = 0; i < 4; i++) { - vehicleBuilder.getWheelBuilder(i) - .setRadius(5) - .setWidth(i + 10); + vehicleBuilder.getWheelBuilder(i).setRadius(5).setWidth(i + 10); } vehicleBuilder.getEngineBuilder().setLiters(20); @@ -89,18 +78,10 @@ public class NestedBuildersTest extends TestCase { public void testMessagesAreCached() { Vehicle.Builder vehicleBuilder = Vehicle.newBuilder(); - vehicleBuilder.addWheelBuilder() - .setRadius(1) - .setWidth(2); - vehicleBuilder.addWheelBuilder() - .setRadius(3) - .setWidth(4); - vehicleBuilder.addWheelBuilder() - .setRadius(5) - .setWidth(6); - vehicleBuilder.addWheelBuilder() - .setRadius(7) - .setWidth(8); + vehicleBuilder.addWheelBuilder().setRadius(1).setWidth(2); + vehicleBuilder.addWheelBuilder().setRadius(3).setWidth(4); + vehicleBuilder.addWheelBuilder().setRadius(5).setWidth(6); + vehicleBuilder.addWheelBuilder().setRadius(7).setWidth(8); // Make sure messages are cached. List wheels = new ArrayList(vehicleBuilder.getWheelList()); @@ -117,8 +98,7 @@ public class NestedBuildersTest extends TestCase { } // Change just one - vehicleBuilder.getWheelBuilder(3) - .setRadius(20).setWidth(20); + vehicleBuilder.getWheelBuilder(3).setRadius(20).setWidth(20); // Now get wheels and check that only that one changed for (int i = 0; i < wheels.size(); i++) { @@ -132,12 +112,8 @@ public class NestedBuildersTest extends TestCase { public void testRemove_WithNestedBuilders() { Vehicle.Builder vehicleBuilder = Vehicle.newBuilder(); - vehicleBuilder.addWheelBuilder() - .setRadius(1) - .setWidth(1); - vehicleBuilder.addWheelBuilder() - .setRadius(2) - .setWidth(2); + vehicleBuilder.addWheelBuilder().setRadius(1).setWidth(1); + vehicleBuilder.addWheelBuilder().setRadius(2).setWidth(2); vehicleBuilder.removeWheel(0); assertEquals(1, vehicleBuilder.getWheelCount()); @@ -146,12 +122,8 @@ public class NestedBuildersTest extends TestCase { public void testRemove_WithNestedMessages() { Vehicle.Builder vehicleBuilder = Vehicle.newBuilder(); - vehicleBuilder.addWheel(Wheel.newBuilder() - .setRadius(1) - .setWidth(1)); - vehicleBuilder.addWheel(Wheel.newBuilder() - .setRadius(2) - .setWidth(2)); + vehicleBuilder.addWheel(Wheel.newBuilder().setRadius(1).setWidth(1)); + vehicleBuilder.addWheel(Wheel.newBuilder().setRadius(2).setWidth(2)); vehicleBuilder.removeWheel(0); assertEquals(1, vehicleBuilder.getWheelCount()); @@ -159,14 +131,13 @@ public class NestedBuildersTest extends TestCase { } public void testMerge() { - Vehicle vehicle1 = Vehicle.newBuilder() - .addWheel(Wheel.newBuilder().setRadius(1).build()) - .addWheel(Wheel.newBuilder().setRadius(2).build()) - .build(); - - Vehicle vehicle2 = Vehicle.newBuilder() - .mergeFrom(vehicle1) - .build(); + Vehicle vehicle1 = + Vehicle.newBuilder() + .addWheel(Wheel.newBuilder().setRadius(1).build()) + .addWheel(Wheel.newBuilder().setRadius(2).build()) + .build(); + + Vehicle vehicle2 = Vehicle.newBuilder().mergeFrom(vehicle1).build(); // List should be the same -- no allocation assertSame(vehicle1.getWheelList(), vehicle2.getWheelList()); diff --git a/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java b/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java index c388bd0561..4a68c8b8fe 100644 --- a/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java +++ b/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java @@ -48,9 +48,7 @@ import java.util.List; import java.util.NoSuchElementException; import junit.framework.TestCase; -/** - * Tests for {@link NioByteString}. - */ +/** Tests for {@link NioByteString}. */ public class NioByteStringTest extends TestCase { private static final ByteString EMPTY = new NioByteString(ByteBuffer.wrap(new byte[0])); private static final String CLASSNAME = NioByteString.class.getSimpleName(); @@ -108,8 +106,7 @@ public class NioByteStringTest extends TestCase { } public void testSize() { - assertEquals(CLASSNAME + " must have the expected size", BYTES.length, - testString.size()); + assertEquals(CLASSNAME + " must have the expected size", BYTES.length, testString.size()); } public void testGetTreeDepth() { @@ -140,10 +137,8 @@ public class NioByteStringTest extends TestCase { try { // Copy one too many bytes - testString.copyTo(destination, testString.size() + 1 - length, - destinationOffset, length); - fail("Should have thrown an exception when copying too many bytes of a " - + CLASSNAME); + testString.copyTo(destination, testString.size() + 1 - length, destinationOffset, length); + fail("Should have thrown an exception when copying too many bytes of a " + CLASSNAME); } catch (IndexOutOfBoundsException expected) { // This is success } @@ -151,8 +146,7 @@ public class NioByteStringTest extends TestCase { try { // Copy with illegal negative sourceOffset testString.copyTo(destination, -1, destinationOffset, length); - fail("Should have thrown an exception when given a negative sourceOffset in " - + CLASSNAME); + fail("Should have thrown an exception when given a negative sourceOffset in " + CLASSNAME); } catch (IndexOutOfBoundsException expected) { // This is success } @@ -160,8 +154,9 @@ public class NioByteStringTest extends TestCase { try { // Copy with illegal negative destinationOffset testString.copyTo(destination, 0, -1, length); - fail("Should have thrown an exception when given a negative destinationOffset in " - + CLASSNAME); + fail( + "Should have thrown an exception when given a negative destinationOffset in " + + CLASSNAME); } catch (IndexOutOfBoundsException expected) { // This is success } @@ -169,8 +164,7 @@ public class NioByteStringTest extends TestCase { try { // Copy with illegal negative size testString.copyTo(destination, 0, 0, -1); - fail("Should have thrown an exception when given a negative size in " - + CLASSNAME); + fail("Should have thrown an exception when given a negative size in " + CLASSNAME); } catch (IndexOutOfBoundsException expected) { // This is success } @@ -178,8 +172,9 @@ public class NioByteStringTest extends TestCase { try { // Copy with illegal too-large sourceOffset testString.copyTo(destination, 2 * testString.size(), 0, length); - fail("Should have thrown an exception when the destinationOffset is too large in " - + CLASSNAME); + fail( + "Should have thrown an exception when the destinationOffset is too large in " + + CLASSNAME); } catch (IndexOutOfBoundsException expected) { // This is success } @@ -187,8 +182,9 @@ public class NioByteStringTest extends TestCase { try { // Copy with illegal too-large destinationOffset testString.copyTo(destination, 0, 2 * destination.length, length); - fail("Should have thrown an exception when the destinationOffset is too large in " - + CLASSNAME); + fail( + "Should have thrown an exception when the destinationOffset is too large in " + + CLASSNAME); } catch (IndexOutOfBoundsException expected) { // This is success } @@ -199,8 +195,8 @@ public class NioByteStringTest extends TestCase { ByteBuffer myBuffer = ByteBuffer.allocate(BYTES.length); testString.copyTo(myBuffer); myBuffer.flip(); - assertEquals(CLASSNAME + ".copyTo(ByteBuffer) must give back the same bytes", - backingBuffer, myBuffer); + assertEquals( + CLASSNAME + ".copyTo(ByteBuffer) must give back the same bytes", backingBuffer, myBuffer); // Target buffer bigger than required. myBuffer = ByteBuffer.allocate(testString.size() + 1); @@ -241,30 +237,31 @@ public class NioByteStringTest extends TestCase { skipFully(stream, fraction); // Skip a large fraction, but not all. assertEquals( CLASSNAME + ": after skipping to the 'middle', half the bytes are available", - (testString.size() - fraction), stream.available()); + (testString.size() - fraction), + stream.available()); stream.reset(); assertEquals( CLASSNAME + ": after resetting, all bytes are available", - testString.size(), stream.available()); + testString.size(), + stream.available()); skipFully(stream, testString.size()); // Skip to the end. assertEquals( CLASSNAME + ": after skipping to the end, no more bytes are available", - 0, stream.available()); + 0, + stream.available()); } /** - * Discards {@code n} bytes of data from the input stream. This method - * will block until the full amount has been skipped. Does not close the - * stream. + * Discards {@code n} bytes of data from the input stream. This method will block until the full + * amount has been skipped. Does not close the stream. + * *

Copied from com.google.common.io.ByteStreams to avoid adding dependency. * * @param in the input stream to read from * @param n the number of bytes to skip - * @throws EOFException if this stream reaches the end before skipping all - * the bytes - * @throws IOException if an I/O error occurs, or the stream does not - * support skipping + * @throws EOFException if this stream reaches the end before skipping all the bytes + * @throws IOException if an I/O error occurs, or the stream does not support skipping */ static void skipFully(InputStream in, long n) throws IOException { long toSkip = n; @@ -274,8 +271,12 @@ public class NioByteStringTest extends TestCase { // Force a blocking read to avoid infinite loop if (in.read() == -1) { long skipped = toSkip - n; - throw new EOFException("reached end of stream after skipping " - + skipped + " bytes; " + toSkip + " bytes expected"); + throw new EOFException( + "reached end of stream after skipping " + + skipped + + " bytes; " + + toSkip + + " bytes expected"); } n--; } else { @@ -290,7 +291,8 @@ public class NioByteStringTest extends TestCase { assertTrue(byteBuffer.remaining() == BYTES.length); assertTrue(byteBuffer.isReadOnly()); byteBuffer.get(roundTripBytes); - assertTrue(CLASSNAME + ".asReadOnlyByteBuffer() must give back the same bytes", + assertTrue( + CLASSNAME + ".asReadOnlyByteBuffer() must give back the same bytes", Arrays.equals(BYTES, roundTripBytes)); } @@ -306,13 +308,15 @@ public class NioByteStringTest extends TestCase { bytesSeen += thisLength; } assertTrue(bytesSeen == BYTES.length); - assertTrue(CLASSNAME + ".asReadOnlyByteBufferTest() must give back the same bytes", + assertTrue( + CLASSNAME + ".asReadOnlyByteBufferTest() must give back the same bytes", Arrays.equals(BYTES, roundTripBytes)); } public void testToByteArray() { byte[] roundTripBytes = testString.toByteArray(); - assertTrue(CLASSNAME + ".toByteArray() must give back the same bytes", + assertTrue( + CLASSNAME + ".toByteArray() must give back the same bytes", Arrays.equals(BYTES, roundTripBytes)); } @@ -320,80 +324,87 @@ public class NioByteStringTest extends TestCase { ByteArrayOutputStream bos = new ByteArrayOutputStream(); testString.writeTo(bos); byte[] roundTripBytes = bos.toByteArray(); - assertTrue(CLASSNAME + ".writeTo() must give back the same bytes", + assertTrue( + CLASSNAME + ".writeTo() must give back the same bytes", Arrays.equals(BYTES, roundTripBytes)); } public void testWriteToShouldNotExposeInternalBufferToOutputStream() throws IOException { - OutputStream os = new OutputStream() { - @Override - public void write(byte[] b, int off, int len) { - Arrays.fill(b, off, off + len, (byte) 0); - } - - @Override - public void write(int b) { - throw new UnsupportedOperationException(); - } - }; + OutputStream os = + new OutputStream() { + @Override + public void write(byte[] b, int off, int len) { + Arrays.fill(b, off, off + len, (byte) 0); + } + + @Override + public void write(int b) { + throw new UnsupportedOperationException(); + } + }; byte[] original = Arrays.copyOf(BYTES, BYTES.length); testString.writeTo(os); - assertTrue(CLASSNAME + ".writeTo() must NOT grant access to underlying buffer", + assertTrue( + CLASSNAME + ".writeTo() must NOT grant access to underlying buffer", Arrays.equals(original, BYTES)); } public void testWriteToInternalShouldExposeInternalBufferToOutputStream() throws IOException { - OutputStream os = new OutputStream() { - @Override - public void write(byte[] b, int off, int len) { - Arrays.fill(b, off, off + len, (byte) 0); - } - - @Override - public void write(int b) { - throw new UnsupportedOperationException(); - } - }; + OutputStream os = + new OutputStream() { + @Override + public void write(byte[] b, int off, int len) { + Arrays.fill(b, off, off + len, (byte) 0); + } + + @Override + public void write(int b) { + throw new UnsupportedOperationException(); + } + }; testString.writeToInternal(os, 0, testString.size()); byte[] allZeros = new byte[testString.size()]; - assertTrue(CLASSNAME + ".writeToInternal() must grant access to underlying buffer", + assertTrue( + CLASSNAME + ".writeToInternal() must grant access to underlying buffer", Arrays.equals(allZeros, backingBuffer.array())); } public void testWriteToShouldExposeInternalBufferToByteOutput() throws IOException { - ByteOutput out = new ByteOutput() { - @Override - public void write(byte value) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public void write(byte[] value, int offset, int length) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public void writeLazy(byte[] value, int offset, int length) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public void write(ByteBuffer value) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public void writeLazy(ByteBuffer value) throws IOException { - Arrays.fill(value.array(), value.arrayOffset(), value.arrayOffset() + value.limit(), - (byte) 0); - } - }; + ByteOutput out = + new ByteOutput() { + @Override + public void write(byte value) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void write(byte[] value, int offset, int length) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void writeLazy(byte[] value, int offset, int length) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void write(ByteBuffer value) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void writeLazy(ByteBuffer value) throws IOException { + Arrays.fill( + value.array(), value.arrayOffset(), value.arrayOffset() + value.limit(), (byte) 0); + } + }; testString.writeTo(out); byte[] allZeros = new byte[testString.size()]; - assertTrue(CLASSNAME + ".writeTo() must grant access to underlying buffer", + assertTrue( + CLASSNAME + ".writeTo() must grant access to underlying buffer", Arrays.equals(allZeros, backingBuffer.array())); } @@ -401,21 +412,21 @@ public class NioByteStringTest extends TestCase { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteString.Output output = ByteString.newOutput(); testString.writeTo(output); - assertEquals("Output Size returns correct result", - output.size(), testString.size()); + assertEquals("Output Size returns correct result", output.size(), testString.size()); output.writeTo(bos); - assertTrue("Output.writeTo() must give back the same bytes", - Arrays.equals(BYTES, bos.toByteArray())); + assertTrue( + "Output.writeTo() must give back the same bytes", Arrays.equals(BYTES, bos.toByteArray())); // write the output stream to itself! This should cause it to double output.writeTo(output); - assertEquals("Writing an output stream to itself is successful", - testString.concat(testString), output.toByteString()); + assertEquals( + "Writing an output stream to itself is successful", + testString.concat(testString), + output.toByteString()); output.reset(); assertEquals("Output.reset() resets the output", 0, output.size()); - assertEquals("Output.reset() resets the output", - EMPTY, output.toByteString()); + assertEquals("Output.reset() resets the output", EMPTY, output.toByteString()); } public void testToString() { @@ -433,7 +444,8 @@ public class NioByteStringTest extends TestCase { } public void testToString_returnsCanonicalEmptyString() { - assertSame(CLASSNAME + " must be the same string references", + assertSame( + CLASSNAME + " must be the same string references", EMPTY.toString(UTF_8), new NioByteString(ByteBuffer.wrap(new byte[0])).toString(UTF_8)); } @@ -457,33 +469,34 @@ public class NioByteStringTest extends TestCase { public void testEquals() { assertEquals(CLASSNAME + " must not equal null", false, testString.equals(null)); assertEquals(CLASSNAME + " must equal self", testString, testString); - assertFalse(CLASSNAME + " must not equal the empty string", - testString.equals(EMPTY)); - assertEquals(CLASSNAME + " empty strings must be equal", - EMPTY, testString.substring(55, 55)); - assertEquals(CLASSNAME + " must equal another string with the same value", - testString, new NioByteString(backingBuffer)); + assertFalse(CLASSNAME + " must not equal the empty string", testString.equals(EMPTY)); + assertEquals(CLASSNAME + " empty strings must be equal", EMPTY, testString.substring(55, 55)); + assertEquals( + CLASSNAME + " must equal another string with the same value", + testString, + new NioByteString(backingBuffer)); byte[] mungedBytes = mungedBytes(); - assertFalse(CLASSNAME + " must not equal every string with the same length", + assertFalse( + CLASSNAME + " must not equal every string with the same length", testString.equals(new NioByteString(ByteBuffer.wrap(mungedBytes)))); } public void testEqualsLiteralByteString() { ByteString literal = ByteString.copyFrom(BYTES); - assertEquals(CLASSNAME + " must equal LiteralByteString with same value", literal, - testString); - assertEquals(CLASSNAME + " must equal LiteralByteString with same value", testString, - literal); - assertFalse(CLASSNAME + " must not equal the empty string", - testString.equals(ByteString.EMPTY)); - assertEquals(CLASSNAME + " empty strings must be equal", - ByteString.EMPTY, testString.substring(55, 55)); + assertEquals(CLASSNAME + " must equal LiteralByteString with same value", literal, testString); + assertEquals(CLASSNAME + " must equal LiteralByteString with same value", testString, literal); + assertFalse( + CLASSNAME + " must not equal the empty string", testString.equals(ByteString.EMPTY)); + assertEquals( + CLASSNAME + " empty strings must be equal", ByteString.EMPTY, testString.substring(55, 55)); literal = ByteString.copyFrom(mungedBytes()); - assertFalse(CLASSNAME + " must not equal every LiteralByteString with the same length", + assertFalse( + CLASSNAME + " must not equal every LiteralByteString with the same length", testString.equals(literal)); - assertFalse(CLASSNAME + " must not equal every LiteralByteString with the same length", + assertFalse( + CLASSNAME + " must not equal every LiteralByteString with the same length", literal.equals(testString)); } @@ -492,22 +505,25 @@ public class NioByteStringTest extends TestCase { ByteString p2 = ByteString.copyFrom(BYTES, 5, BYTES.length - 5); ByteString rope = p1.concat(p2); - assertEquals(CLASSNAME + " must equal RopeByteString with same value", rope, - testString); - assertEquals(CLASSNAME + " must equal RopeByteString with same value", testString, - rope); - assertFalse(CLASSNAME + " must not equal the empty string", + assertEquals(CLASSNAME + " must equal RopeByteString with same value", rope, testString); + assertEquals(CLASSNAME + " must equal RopeByteString with same value", testString, rope); + assertFalse( + CLASSNAME + " must not equal the empty string", testString.equals(ByteString.EMPTY.concat(ByteString.EMPTY))); - assertEquals(CLASSNAME + " empty strings must be equal", - ByteString.EMPTY.concat(ByteString.EMPTY), testString.substring(55, 55)); + assertEquals( + CLASSNAME + " empty strings must be equal", + ByteString.EMPTY.concat(ByteString.EMPTY), + testString.substring(55, 55)); byte[] mungedBytes = mungedBytes(); p1 = ByteString.copyFrom(mungedBytes, 0, 5); p2 = ByteString.copyFrom(mungedBytes, 5, mungedBytes.length - 5); rope = p1.concat(p2); - assertFalse(CLASSNAME + " must not equal every RopeByteString with the same length", + assertFalse( + CLASSNAME + " must not equal every RopeByteString with the same length", testString.equals(rope)); - assertFalse(CLASSNAME + " must not equal every RopeByteString with the same length", + assertFalse( + CLASSNAME + " must not equal every RopeByteString with the same length", rope.equals(testString)); } @@ -525,32 +541,34 @@ public class NioByteStringTest extends TestCase { public void testPeekCachedHashCode() { ByteString newString = new NioByteString(backingBuffer); - assertEquals(CLASSNAME + ".peekCachedHashCode() should return zero at first", 0, + assertEquals( + CLASSNAME + ".peekCachedHashCode() should return zero at first", + 0, newString.peekCachedHashCode()); newString.hashCode(); - assertEquals(CLASSNAME + ".peekCachedHashCode should return zero at first", - EXPECTED_HASH, newString.peekCachedHashCode()); + assertEquals( + CLASSNAME + ".peekCachedHashCode should return zero at first", + EXPECTED_HASH, + newString.peekCachedHashCode()); } public void testPartialHash() { // partialHash() is more strenuously tested elsewhere by testing hashes of substrings. // This test would fail if the expected hash were 1. It's not. int hash = testString.partialHash(testString.size(), 0, testString.size()); - assertEquals(CLASSNAME + ".partialHash() must yield expected hashCode", - EXPECTED_HASH, hash); + assertEquals(CLASSNAME + ".partialHash() must yield expected hashCode", EXPECTED_HASH, hash); } public void testNewInput() throws IOException { InputStream input = testString.newInput(); - assertEquals("InputStream.available() returns correct value", - testString.size(), input.available()); + assertEquals( + "InputStream.available() returns correct value", testString.size(), input.available()); boolean stillEqual = true; for (byte referenceByte : BYTES) { int expectedInt = (referenceByte & 0xFF); stillEqual = (expectedInt == input.read()); } - assertEquals("InputStream.available() returns correct value", - 0, input.available()); + assertEquals("InputStream.available() returns correct value", 0, input.available()); assertTrue(CLASSNAME + " must give the same bytes from the InputStream", stillEqual); assertEquals(CLASSNAME + " InputStream must now be exhausted", -1, input.read()); } @@ -561,43 +579,44 @@ public class NioByteStringTest extends TestCase { int nearEndIndex = stringSize * 2 / 3; long skipped1 = input.skip(nearEndIndex); assertEquals("InputStream.skip()", skipped1, nearEndIndex); - assertEquals("InputStream.available()", - stringSize - skipped1, input.available()); + assertEquals("InputStream.available()", stringSize - skipped1, input.available()); assertTrue("InputStream.mark() is available", input.markSupported()); input.mark(0); - assertEquals("InputStream.skip(), read()", - testString.byteAt(nearEndIndex) & 0xFF, input.read()); - assertEquals("InputStream.available()", - stringSize - skipped1 - 1, input.available()); + assertEquals( + "InputStream.skip(), read()", testString.byteAt(nearEndIndex) & 0xFF, input.read()); + assertEquals("InputStream.available()", stringSize - skipped1 - 1, input.available()); long skipped2 = input.skip(stringSize); - assertEquals("InputStream.skip() incomplete", - skipped2, stringSize - skipped1 - 1); + assertEquals("InputStream.skip() incomplete", skipped2, stringSize - skipped1 - 1); assertEquals("InputStream.skip(), no more input", 0, input.available()); assertEquals("InputStream.skip(), no more input", -1, input.read()); input.reset(); - assertEquals("InputStream.reset() succeded", - stringSize - skipped1, input.available()); - assertEquals("InputStream.reset(), read()", - testString.byteAt(nearEndIndex) & 0xFF, input.read()); + assertEquals("InputStream.reset() succeded", stringSize - skipped1, input.available()); + assertEquals( + "InputStream.reset(), read()", testString.byteAt(nearEndIndex) & 0xFF, input.read()); } public void testNewCodedInput() throws IOException { CodedInputStream cis = testString.newCodedInput(); byte[] roundTripBytes = cis.readRawBytes(BYTES.length); - assertTrue(CLASSNAME + " must give the same bytes back from the CodedInputStream", + assertTrue( + CLASSNAME + " must give the same bytes back from the CodedInputStream", Arrays.equals(BYTES, roundTripBytes)); assertTrue(CLASSNAME + " CodedInputStream must now be exhausted", cis.isAtEnd()); } /** - * Make sure we keep things simple when concatenating with empty. See also - * {@link ByteStringTest#testConcat_empty()}. + * Make sure we keep things simple when concatenating with empty. See also {@link + * ByteStringTest#testConcat_empty()}. */ public void testConcat_empty() { - assertSame(CLASSNAME + " concatenated with empty must give " + CLASSNAME, - testString.concat(EMPTY), testString); - assertSame("empty concatenated with " + CLASSNAME + " must give " + CLASSNAME, - EMPTY.concat(testString), testString); + assertSame( + CLASSNAME + " concatenated with empty must give " + CLASSNAME, + testString.concat(EMPTY), + testString); + assertSame( + "empty concatenated with " + CLASSNAME + " must give " + CLASSNAME, + EMPTY.concat(testString), + testString); } public void testJavaSerialization() throws Exception { diff --git a/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java b/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java index e376b1cd72..20b9380979 100644 --- a/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java +++ b/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java @@ -48,9 +48,9 @@ import org.junit.runners.JUnit4; /** * Tests the exceptions thrown when parsing from a stream. The methods on the {@link Parser} * interface are specified to only throw {@link InvalidProtocolBufferException}. But we really want - * to distinguish between invalid protos vs. actual I/O errors (like failures reading from a - * socket, etc.). So, when we're not using the parser directly, an {@link IOException} should be - * thrown where appropriate, instead of always an {@link InvalidProtocolBufferException}. + * to distinguish between invalid protos vs. actual I/O errors (like failures reading from a socket, + * etc.). So, when we're not using the parser directly, an {@link IOException} should be thrown + * where appropriate, instead of always an {@link InvalidProtocolBufferException}. * * @author jh@squareup.com (Joshua Humphries) */ @@ -61,7 +61,7 @@ public class ParseExceptionsTest { DescriptorProto parse(InputStream in) throws IOException; } - private byte serializedProto[]; + private byte[] serializedProto; private void setup() { serializedProto = DescriptorProto.getDescriptor().toProto().toByteArray(); @@ -77,7 +77,8 @@ public class ParseExceptionsTest { serializedProto = bos.toByteArray(); } - @Test public void message_parseFrom_InputStream() { + @Test + public void message_parseFrom_InputStream() { setup(); verifyExceptions( new ParseTester() { @@ -88,7 +89,8 @@ public class ParseExceptionsTest { }); } - @Test public void message_parseFrom_InputStreamAndExtensionRegistry() { + @Test + public void message_parseFrom_InputStreamAndExtensionRegistry() { setup(); verifyExceptions( new ParseTester() { @@ -99,7 +101,8 @@ public class ParseExceptionsTest { }); } - @Test public void message_parseFrom_CodedInputStream() { + @Test + public void message_parseFrom_CodedInputStream() { setup(); verifyExceptions( new ParseTester() { @@ -110,7 +113,8 @@ public class ParseExceptionsTest { }); } - @Test public void message_parseFrom_CodedInputStreamAndExtensionRegistry() { + @Test + public void message_parseFrom_CodedInputStreamAndExtensionRegistry() { setup(); verifyExceptions( new ParseTester() { @@ -122,7 +126,8 @@ public class ParseExceptionsTest { }); } - @Test public void message_parseDelimitedFrom_InputStream() { + @Test + public void message_parseDelimitedFrom_InputStream() { setupDelimited(); verifyExceptions( new ParseTester() { @@ -133,7 +138,8 @@ public class ParseExceptionsTest { }); } - @Test public void message_parseDelimitedFrom_InputStreamAndExtensionRegistry() { + @Test + public void message_parseDelimitedFrom_InputStreamAndExtensionRegistry() { setupDelimited(); verifyExceptions( new ParseTester() { @@ -144,7 +150,8 @@ public class ParseExceptionsTest { }); } - @Test public void messageBuilder_mergeFrom_InputStream() { + @Test + public void messageBuilder_mergeFrom_InputStream() { setup(); verifyExceptions( new ParseTester() { @@ -155,7 +162,8 @@ public class ParseExceptionsTest { }); } - @Test public void messageBuilder_mergeFrom_InputStreamAndExtensionRegistry() { + @Test + public void messageBuilder_mergeFrom_InputStreamAndExtensionRegistry() { setup(); verifyExceptions( new ParseTester() { @@ -168,7 +176,8 @@ public class ParseExceptionsTest { }); } - @Test public void messageBuilder_mergeFrom_CodedInputStream() { + @Test + public void messageBuilder_mergeFrom_CodedInputStream() { setup(); verifyExceptions( new ParseTester() { @@ -179,7 +188,8 @@ public class ParseExceptionsTest { }); } - @Test public void messageBuilder_mergeFrom_CodedInputStreamAndExtensionRegistry() { + @Test + public void messageBuilder_mergeFrom_CodedInputStreamAndExtensionRegistry() { setup(); verifyExceptions( new ParseTester() { @@ -192,7 +202,8 @@ public class ParseExceptionsTest { }); } - @Test public void messageBuilder_mergeDelimitedFrom_InputStream() { + @Test + public void messageBuilder_mergeDelimitedFrom_InputStream() { setupDelimited(); verifyExceptions( new ParseTester() { @@ -205,7 +216,8 @@ public class ParseExceptionsTest { }); } - @Test public void messageBuilder_mergeDelimitedFrom_InputStreamAndExtensionRegistry() { + @Test + public void messageBuilder_mergeDelimitedFrom_InputStreamAndExtensionRegistry() { setupDelimited(); verifyExceptions( new ParseTester() { @@ -221,7 +233,8 @@ public class ParseExceptionsTest { private void verifyExceptions(ParseTester parseTester) { // No exception try { - assertEquals(DescriptorProto.getDescriptor().toProto(), + assertEquals( + DescriptorProto.getDescriptor().toProto(), parseTester.parse(new ByteArrayInputStream(serializedProto))); } catch (IOException e) { fail("No exception expected: " + e); @@ -253,14 +266,16 @@ public class ParseExceptionsTest { return new FilterInputStream(i) { int count = 0; - @Override public int read() throws IOException { + @Override + public int read() throws IOException { if (count++ >= 50) { throw new IOException("I'm broken!"); } return super.read(); } - @Override public int read(byte b[], int off, int len) throws IOException { + @Override + public int read(byte[] b, int off, int len) throws IOException { if ((count += len) >= 50) { throw new IOException("I'm broken!"); } diff --git a/java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java b/java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java index 0a2c3e3728..67b2881a43 100644 --- a/java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java +++ b/java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java @@ -38,9 +38,7 @@ import java.util.Iterator; import java.util.List; import junit.framework.TestCase; -/** - * Tests for {@link ProtobufArrayList}. - */ +/** Tests for {@link ProtobufArrayList}. */ public class ProtobufArrayListTest extends TestCase { private static final ProtobufArrayList UNARY_LIST = newImmutableProtoArrayList(1); diff --git a/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java b/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java index edbd0afd75..c42813c808 100644 --- a/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java +++ b/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java @@ -37,9 +37,8 @@ import java.util.List; import junit.framework.TestCase; /** - * Tests for {@link RepeatedFieldBuilderV3}. This tests basic functionality. - * More extensive testing is provided via other tests that exercise the - * builder. + * Tests for {@link RepeatedFieldBuilderV3}. This tests basic functionality. More extensive testing is + * provided via other tests that exercise the builder. * * @author jonp@google.com (Jon Perlow) */ @@ -47,8 +46,8 @@ public class RepeatedFieldBuilderV3Test extends TestCase { public void testBasicUse() { TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent(); - RepeatedFieldBuilderV3 builder = newRepeatedFieldBuilderV3(mockParent); + RepeatedFieldBuilderV3 builder = + newRepeatedFieldBuilderV3(mockParent); builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build()); builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build()); assertEquals(0, builder.getMessage(0).getOptionalInt32()); @@ -68,8 +67,8 @@ public class RepeatedFieldBuilderV3Test extends TestCase { public void testGoingBackAndForth() { TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent(); - RepeatedFieldBuilderV3 builder = newRepeatedFieldBuilderV3(mockParent); + RepeatedFieldBuilderV3 builder = + newRepeatedFieldBuilderV3(mockParent); builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build()); builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build()); assertEquals(0, builder.getMessage(0).getOptionalInt32()); @@ -89,7 +88,7 @@ public class RepeatedFieldBuilderV3Test extends TestCase { list = builder.build(); assertEquals(2, list.size()); assertEquals(0, list.get(0).getOptionalInt32()); - assertEquals("foo", list.get(0).getOptionalString()); + assertEquals("foo", list.get(0).getOptionalString()); assertEquals(1, list.get(1).getOptionalInt32()); assertIsUnmodifiable(list); assertEquals(1, mockParent.getInvalidationCount()); @@ -97,12 +96,11 @@ public class RepeatedFieldBuilderV3Test extends TestCase { public void testVariousMethods() { TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent(); - RepeatedFieldBuilderV3 builder = newRepeatedFieldBuilderV3(mockParent); + RepeatedFieldBuilderV3 builder = + newRepeatedFieldBuilderV3(mockParent); builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build()); builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(2).build()); - builder.addBuilder(0, TestAllTypes.getDefaultInstance()) - .setOptionalInt32(0); + builder.addBuilder(0, TestAllTypes.getDefaultInstance()).setOptionalInt32(0); builder.addBuilder(TestAllTypes.getDefaultInstance()).setOptionalInt32(3); assertEquals(0, builder.getMessage(0).getOptionalInt32()); @@ -139,11 +137,10 @@ public class RepeatedFieldBuilderV3Test extends TestCase { public void testLists() { TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent(); - RepeatedFieldBuilderV3 builder = newRepeatedFieldBuilderV3(mockParent); + RepeatedFieldBuilderV3 builder = + newRepeatedFieldBuilderV3(mockParent); builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build()); - builder.addMessage(0, - TestAllTypes.newBuilder().setOptionalInt32(0).build()); + builder.addMessage(0, TestAllTypes.newBuilder().setOptionalInt32(0).build()); assertEquals(0, builder.getMessage(0).getOptionalInt32()); assertEquals(1, builder.getMessage(1).getOptionalInt32()); @@ -178,11 +175,9 @@ public class RepeatedFieldBuilderV3Test extends TestCase { } } - private RepeatedFieldBuilderV3 + private RepeatedFieldBuilderV3 newRepeatedFieldBuilderV3(GeneratedMessage.BuilderParent parent) { - return new RepeatedFieldBuilderV3(Collections.emptyList(), false, - parent, false); + return new RepeatedFieldBuilderV3( + Collections.emptyList(), false, parent, false); } } diff --git a/java/core/src/test/java/com/google/protobuf/RopeByteStringSubstringTest.java b/java/core/src/test/java/com/google/protobuf/RopeByteStringSubstringTest.java index dc56f2e9ac..d7262161dd 100644 --- a/java/core/src/test/java/com/google/protobuf/RopeByteStringSubstringTest.java +++ b/java/core/src/test/java/com/google/protobuf/RopeByteStringSubstringTest.java @@ -34,8 +34,8 @@ import java.io.UnsupportedEncodingException; import java.util.Iterator; /** - * This class tests {@link RopeByteString#substring(int, int)} by inheriting the tests from - * {@link LiteralByteStringTest}. Only a couple of methods are overridden. + * This class tests {@link RopeByteString#substring(int, int)} by inheriting the tests from {@link + * LiteralByteStringTest}. Only a couple of methods are overridden. * * @author carlanton@google.com (Carl Haverl) */ @@ -61,8 +61,8 @@ public class RopeByteStringSubstringTest extends LiteralByteStringTest { @Override public void testGetTreeDepth() { - assertEquals(classUnderTest + " must have the expected tree depth", - 3, stringUnderTest.getTreeDepth()); + assertEquals( + classUnderTest + " must have the expected tree depth", 3, stringUnderTest.getTreeDepth()); } @Override @@ -84,15 +84,18 @@ public class RopeByteStringSubstringTest extends LiteralByteStringTest { testString = testString.substring(2, testString.length() - 6); unicode = unicode.substring(2, unicode.size() - 6); - assertEquals(classUnderTest + " from string must have the expected type", - classUnderTest, getActualClassName(unicode)); + assertEquals( + classUnderTest + " from string must have the expected type", + classUnderTest, + getActualClassName(unicode)); String roundTripString = unicode.toString(UTF_8); - assertEquals(classUnderTest + " unicode bytes must match", - testString, roundTripString); + assertEquals(classUnderTest + " unicode bytes must match", testString, roundTripString); ByteString flatString = ByteString.copyFromUtf8(testString); assertEquals(classUnderTest + " string must equal the flat string", flatString, unicode); - assertEquals(classUnderTest + " string must must have same hashCode as the flat string", - flatString.hashCode(), unicode.hashCode()); + assertEquals( + classUnderTest + " string must must have same hashCode as the flat string", + flatString.hashCode(), + unicode.hashCode()); } @Override @@ -114,14 +117,17 @@ public class RopeByteStringSubstringTest extends LiteralByteStringTest { testString = testString.substring(2, testString.length() - 6); unicode = unicode.substring(2, unicode.size() - 6); - assertEquals(classUnderTest + " from string must have the expected type", - classUnderTest, getActualClassName(unicode)); + assertEquals( + classUnderTest + " from string must have the expected type", + classUnderTest, + getActualClassName(unicode)); String roundTripString = unicode.toString(Internal.UTF_8); - assertEquals(classUnderTest + " unicode bytes must match", - testString, roundTripString); + assertEquals(classUnderTest + " unicode bytes must match", testString, roundTripString); ByteString flatString = ByteString.copyFromUtf8(testString); assertEquals(classUnderTest + " string must equal the flat string", flatString, unicode); - assertEquals(classUnderTest + " string must must have same hashCode as the flat string", - flatString.hashCode(), unicode.hashCode()); + assertEquals( + classUnderTest + " string must must have same hashCode as the flat string", + flatString.hashCode(), + unicode.hashCode()); } } diff --git a/java/core/src/test/java/com/google/protobuf/RopeByteStringTest.java b/java/core/src/test/java/com/google/protobuf/RopeByteStringTest.java index 4ec3a40988..59e8ede1db 100644 --- a/java/core/src/test/java/com/google/protobuf/RopeByteStringTest.java +++ b/java/core/src/test/java/com/google/protobuf/RopeByteStringTest.java @@ -40,8 +40,8 @@ import java.util.Arrays; import java.util.Iterator; /** - * This class tests {@link RopeByteString} by inheriting the tests from - * {@link LiteralByteStringTest}. Only a couple of methods are overridden. + * This class tests {@link RopeByteString} by inheriting the tests from {@link + * LiteralByteStringTest}. Only a couple of methods are overridden. * *

A full test of the result of {@link RopeByteString#substring(int, int)} is found in the * separate class {@link RopeByteStringSubstringTest}. @@ -64,8 +64,8 @@ public class RopeByteStringTest extends LiteralByteStringTest { @Override public void testGetTreeDepth() { - assertEquals(classUnderTest + " must have the expected tree depth", - 4, stringUnderTest.getTreeDepth()); + assertEquals( + classUnderTest + " must have the expected tree depth", 4, stringUnderTest.getTreeDepth()); } public void testBalance() { @@ -79,17 +79,22 @@ public class RopeByteStringTest extends LiteralByteStringTest { concatenated = concatenated.concat(ByteString.copyFrom(testBytes, i * pieceSize, pieceSize)); } - assertEquals(classUnderTest + " from string must have the expected type", - classUnderTest, getActualClassName(concatenated)); - assertTrue(classUnderTest + " underlying bytes must match after balancing", + assertEquals( + classUnderTest + " from string must have the expected type", + classUnderTest, + getActualClassName(concatenated)); + assertTrue( + classUnderTest + " underlying bytes must match after balancing", Arrays.equals(testBytes, concatenated.toByteArray())); ByteString testString = ByteString.copyFrom(testBytes); - assertTrue(classUnderTest + " balanced string must equal flat string", - concatenated.equals(testString)); - assertTrue(classUnderTest + " flat string must equal balanced string", - testString.equals(concatenated)); - assertEquals(classUnderTest + " balanced string must have same hash code as flat string", - testString.hashCode(), concatenated.hashCode()); + assertEquals( + classUnderTest + " balanced string must equal flat string", testString, concatenated); + assertEquals( + classUnderTest + " flat string must equal balanced string", concatenated, testString); + assertEquals( + classUnderTest + " balanced string must have same hash code as flat string", + testString.hashCode(), + concatenated.hashCode()); } @Override @@ -107,15 +112,18 @@ public class RopeByteStringTest extends LiteralByteStringTest { } String testString = builder.toString(); - assertEquals(classUnderTest + " from string must have the expected type", - classUnderTest, getActualClassName(unicode)); + assertEquals( + classUnderTest + " from string must have the expected type", + classUnderTest, + getActualClassName(unicode)); String roundTripString = unicode.toString(UTF_8); - assertEquals(classUnderTest + " unicode bytes must match", - testString, roundTripString); + assertEquals(classUnderTest + " unicode bytes must match", testString, roundTripString); ByteString flatString = ByteString.copyFromUtf8(testString); assertEquals(classUnderTest + " string must equal the flat string", flatString, unicode); - assertEquals(classUnderTest + " string must must have same hashCode as the flat string", - flatString.hashCode(), unicode.hashCode()); + assertEquals( + classUnderTest + " string must must have same hashCode as the flat string", + flatString.hashCode(), + unicode.hashCode()); } @Override @@ -133,30 +141,34 @@ public class RopeByteStringTest extends LiteralByteStringTest { } String testString = builder.toString(); - assertEquals(classUnderTest + " from string must have the expected type", - classUnderTest, getActualClassName(unicode)); + assertEquals( + classUnderTest + " from string must have the expected type", + classUnderTest, + getActualClassName(unicode)); String roundTripString = unicode.toString(Internal.UTF_8); - assertEquals(classUnderTest + " unicode bytes must match", - testString, roundTripString); + assertEquals(classUnderTest + " unicode bytes must match", testString, roundTripString); ByteString flatString = ByteString.copyFromUtf8(testString); assertEquals(classUnderTest + " string must equal the flat string", flatString, unicode); - assertEquals(classUnderTest + " string must must have same hashCode as the flat string", - flatString.hashCode(), unicode.hashCode()); + assertEquals( + classUnderTest + " string must must have same hashCode as the flat string", + flatString.hashCode(), + unicode.hashCode()); } @Override public void testToString_returnsCanonicalEmptyString() { RopeByteString ropeByteString = RopeByteString.newInstanceForTest(ByteString.EMPTY, ByteString.EMPTY); - assertSame(classUnderTest + " must be the same string references", - ByteString.EMPTY.toString(Internal.UTF_8), ropeByteString.toString(Internal.UTF_8)); + assertSame( + classUnderTest + " must be the same string references", + ByteString.EMPTY.toString(Internal.UTF_8), + ropeByteString.toString(Internal.UTF_8)); } @Override public void testToString_raisesException() { try { - ByteString byteString = - RopeByteString.newInstanceForTest(ByteString.EMPTY, ByteString.EMPTY); + ByteString byteString = RopeByteString.newInstanceForTest(ByteString.EMPTY, ByteString.EMPTY); byteString.toString("invalid"); fail("Should have thrown an exception."); } catch (UnsupportedEncodingException expected) { @@ -164,8 +176,9 @@ public class RopeByteStringTest extends LiteralByteStringTest { } try { - ByteString byteString = RopeByteString.concatenate(ByteString.copyFromUtf8("foo"), - ByteString.copyFromUtf8("bar")); + ByteString byteString = + RopeByteString.concatenate( + ByteString.copyFromUtf8("foo"), ByteString.copyFromUtf8("bar")); byteString.toString("invalid"); fail("Should have thrown an exception."); } catch (UnsupportedEncodingException expected) { diff --git a/java/core/src/test/java/com/google/protobuf/ServiceTest.java b/java/core/src/test/java/com/google/protobuf/ServiceTest.java index b895ad8d36..1e58332982 100644 --- a/java/core/src/test/java/com/google/protobuf/ServiceTest.java +++ b/java/core/src/test/java/com/google/protobuf/ServiceTest.java @@ -41,7 +41,6 @@ import protobuf_unittest.UnittestProto.FooRequest; import protobuf_unittest.UnittestProto.FooResponse; import protobuf_unittest.UnittestProto.TestAllTypes; import protobuf_unittest.UnittestProto.TestService; - import java.util.HashSet; import java.util.Set; import junit.framework.TestCase; @@ -270,30 +269,27 @@ public class ServiceTest extends TestCase { } - // ================================================================= /** - * wrapsCallback() is an EasyMock argument predicate. wrapsCallback(c) - * matches a callback if calling that callback causes c to be called. - * In other words, c wraps the given callback. + * wrapsCallback() is an EasyMock argument predicate. wrapsCallback(c) matches a callback if + * calling that callback causes c to be called. In other words, c wraps the given callback. */ - private RpcCallback wrapsCallback( - MockCallback callback) { + private RpcCallback wrapsCallback(MockCallback callback) { EasyMock.reportMatcher(new WrapsCallback(callback)); return null; } /** The parameter to wrapsCallback() must be a MockCallback. */ - private static class MockCallback - implements RpcCallback { + private static class MockCallback implements RpcCallback { private boolean called = false; public boolean isCalled() { return called; } public void reset() { called = false; } + @Override - public void run(Type message) { + public void run(T message) { called = true; } } diff --git a/java/core/src/test/java/com/google/protobuf/SingleFieldBuilderV3Test.java b/java/core/src/test/java/com/google/protobuf/SingleFieldBuilderV3Test.java index e3a8d4f408..f2ae8f9bca 100644 --- a/java/core/src/test/java/com/google/protobuf/SingleFieldBuilderV3Test.java +++ b/java/core/src/test/java/com/google/protobuf/SingleFieldBuilderV3Test.java @@ -32,13 +32,11 @@ package com.google.protobuf; import protobuf_unittest.UnittestProto.TestAllTypes; import protobuf_unittest.UnittestProto.TestAllTypesOrBuilder; - import junit.framework.TestCase; /** - * Tests for {@link SingleFieldBuilderV3}. This tests basic functionality. - * More extensive testing is provided via other tests that exercise the - * builder. + * Tests for {@link SingleFieldBuilderV3}. This tests basic functionality. More extensive testing is + * provided via other tests that exercise the builder. * * @author jonp@google.com (Jon Perlow) */ @@ -46,16 +44,11 @@ public class SingleFieldBuilderV3Test extends TestCase { public void testBasicUseAndInvalidations() { TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent(); - SingleFieldBuilderV3 builder = - new SingleFieldBuilderV3( - TestAllTypes.getDefaultInstance(), - mockParent, - false); + SingleFieldBuilderV3 builder = + new SingleFieldBuilderV3( + TestAllTypes.getDefaultInstance(), mockParent, false); assertSame(TestAllTypes.getDefaultInstance(), builder.getMessage()); - assertEquals(TestAllTypes.getDefaultInstance(), - builder.getBuilder().buildPartial()); + assertEquals(TestAllTypes.getDefaultInstance(), builder.getBuilder().buildPartial()); assertEquals(0, mockParent.getInvalidationCount()); builder.getBuilder().setOptionalInt32(10); @@ -71,18 +64,13 @@ public class SingleFieldBuilderV3Test extends TestCase { // Test that we don't keep getting invalidations on every change builder.getBuilder().setOptionalInt32(30); assertEquals(1, mockParent.getInvalidationCount()); - } public void testSetMessage() { TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent(); - SingleFieldBuilderV3 builder = - new SingleFieldBuilderV3( - TestAllTypes.getDefaultInstance(), - mockParent, - false); + SingleFieldBuilderV3 builder = + new SingleFieldBuilderV3( + TestAllTypes.getDefaultInstance(), mockParent, false); builder.setMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build()); assertEquals(0, builder.getMessage().getOptionalInt32()); @@ -102,13 +90,9 @@ public class SingleFieldBuilderV3Test extends TestCase { public void testClear() { TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent(); - SingleFieldBuilderV3 builder = - new SingleFieldBuilderV3( - TestAllTypes.getDefaultInstance(), - mockParent, - false); + SingleFieldBuilderV3 builder = + new SingleFieldBuilderV3( + TestAllTypes.getDefaultInstance(), mockParent, false); builder.setMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build()); assertNotSame(TestAllTypes.getDefaultInstance(), builder.getMessage()); builder.clear(); @@ -122,13 +106,9 @@ public class SingleFieldBuilderV3Test extends TestCase { public void testMerge() { TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent(); - SingleFieldBuilderV3 builder = - new SingleFieldBuilderV3( - TestAllTypes.getDefaultInstance(), - mockParent, - false); + SingleFieldBuilderV3 builder = + new SingleFieldBuilderV3( + TestAllTypes.getDefaultInstance(), mockParent, false); // Merge into default field. builder.mergeFrom(TestAllTypes.getDefaultInstance()); @@ -136,20 +116,14 @@ public class SingleFieldBuilderV3Test extends TestCase { // Merge into non-default field on existing builder. builder.getBuilder().setOptionalInt32(2); - builder.mergeFrom(TestAllTypes.newBuilder() - .setOptionalDouble(4.0) - .buildPartial()); + builder.mergeFrom(TestAllTypes.newBuilder().setOptionalDouble(4.0).buildPartial()); assertEquals(2, builder.getMessage().getOptionalInt32()); - assertEquals(4.0, builder.getMessage().getOptionalDouble()); + assertEquals(4.0, builder.getMessage().getOptionalDouble(), 0.0); // Merge into non-default field on existing message - builder.setMessage(TestAllTypes.newBuilder() - .setOptionalInt32(10) - .buildPartial()); - builder.mergeFrom(TestAllTypes.newBuilder() - .setOptionalDouble(5.0) - .buildPartial()); + builder.setMessage(TestAllTypes.newBuilder().setOptionalInt32(10).buildPartial()); + builder.mergeFrom(TestAllTypes.newBuilder().setOptionalDouble(5.0).buildPartial()); assertEquals(10, builder.getMessage().getOptionalInt32()); - assertEquals(5.0, builder.getMessage().getOptionalDouble()); + assertEquals(5.0, builder.getMessage().getOptionalDouble(), 0.0); } } diff --git a/java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java b/java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java index a7f8342d13..a1a7194b43 100644 --- a/java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java +++ b/java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java @@ -40,9 +40,7 @@ import java.util.Set; import java.util.TreeSet; import junit.framework.TestCase; -/** - * @author darick@google.com Darick Tong - */ +/** @author darick@google.com Darick Tong */ public class SmallSortedMapTest extends TestCase { // java.util.AbstractMap.SimpleEntry is private in JDK 1.5. We re-implement it // here for JDK 1.5 users. @@ -78,16 +76,16 @@ public class SmallSortedMapTest extends TestCase { @Override public boolean equals(Object o) { - if (!(o instanceof Map.Entry)) + if (!(o instanceof Map.Entry)) { return false; + } Map.Entry e = (Map.Entry) o; return eq(key, e.getKey()) && eq(value, e.getValue()); } @Override public int hashCode() { - return ((key == null) ? 0 : key.hashCode()) ^ - ((value == null) ? 0 : value.hashCode()); + return ((key == null) ? 0 : key.hashCode()) ^ ((value == null) ? 0 : value.hashCode()); } } @@ -101,14 +99,10 @@ public class SmallSortedMapTest extends TestCase { private void runPutAndGetTest(int numElements) { // Test with even and odd arraySize - SmallSortedMap map1 = - SmallSortedMap.newInstanceForTest(3); - SmallSortedMap map2 = - SmallSortedMap.newInstanceForTest(4); - SmallSortedMap map3 = - SmallSortedMap.newInstanceForTest(3); - SmallSortedMap map4 = - SmallSortedMap.newInstanceForTest(4); + SmallSortedMap map1 = SmallSortedMap.newInstanceForTest(3); + SmallSortedMap map2 = SmallSortedMap.newInstanceForTest(4); + SmallSortedMap map3 = SmallSortedMap.newInstanceForTest(3); + SmallSortedMap map4 = SmallSortedMap.newInstanceForTest(4); // Test with puts in ascending order. for (int i = 0; i < numElements; i++) { @@ -136,7 +130,7 @@ public class SmallSortedMapTest extends TestCase { for (SmallSortedMap map : allMaps) { assertEquals(numElements, map.size()); for (int i = 0; i < numElements; i++) { - assertEquals(new Integer(i + 1), map.get(i)); + assertEquals(Integer.valueOf(i + 1), map.get(i)); } } @@ -152,7 +146,7 @@ public class SmallSortedMapTest extends TestCase { assertNull(map.remove(i + 1)); } for (int i = 0; i < 6; i++) { - assertEquals(new Integer(i + 1), map.put(i, i + 2)); + assertEquals(Integer.valueOf(i + 1), map.put(i, i + 2)); } } @@ -165,22 +159,22 @@ public class SmallSortedMapTest extends TestCase { assertEquals(3, map.getNumArrayEntries()); assertEquals(3, map.getNumOverflowEntries()); - assertEquals(6, map.size()); + assertEquals(6, map.size()); assertEquals(makeSortedKeySet(0, 1, 2, 3, 4, 5), map.keySet()); - assertEquals(new Integer(2), map.remove(1)); + assertEquals(Integer.valueOf(2), map.remove(1)); assertEquals(3, map.getNumArrayEntries()); assertEquals(2, map.getNumOverflowEntries()); - assertEquals(5, map.size()); + assertEquals(5, map.size()); assertEquals(makeSortedKeySet(0, 2, 3, 4, 5), map.keySet()); - assertEquals(new Integer(5), map.remove(4)); + assertEquals(Integer.valueOf(5), map.remove(4)); assertEquals(3, map.getNumArrayEntries()); assertEquals(1, map.getNumOverflowEntries()); - assertEquals(4, map.size()); + assertEquals(4, map.size()); assertEquals(makeSortedKeySet(0, 2, 3, 5), map.keySet()); - assertEquals(new Integer(4), map.remove(3)); + assertEquals(Integer.valueOf(4), map.remove(3)); assertEquals(3, map.getNumArrayEntries()); assertEquals(0, map.getNumOverflowEntries()); assertEquals(3, map.size()); @@ -191,7 +185,7 @@ public class SmallSortedMapTest extends TestCase { assertEquals(0, map.getNumOverflowEntries()); assertEquals(3, map.size()); - assertEquals(new Integer(1), map.remove(0)); + assertEquals(Integer.valueOf(1), map.remove(0)); assertEquals(2, map.getNumArrayEntries()); assertEquals(0, map.getNumOverflowEntries()); assertEquals(2, map.size()); @@ -216,16 +210,15 @@ public class SmallSortedMapTest extends TestCase { assertEquals(3, map.getNumArrayEntries()); for (int i = 0; i < 3; i++) { Map.Entry entry = map.getArrayEntryAt(i); - assertEquals(new Integer(i), entry.getKey()); - assertEquals(new Integer(i + 1), entry.getValue()); + assertEquals(Integer.valueOf(i), entry.getKey()); + assertEquals(Integer.valueOf(i + 1), entry.getValue()); } - Iterator> it = - map.getOverflowEntries().iterator(); + Iterator> it = map.getOverflowEntries().iterator(); for (int i = 3; i < 6; i++) { assertTrue(it.hasNext()); Map.Entry entry = it.next(); - assertEquals(new Integer(i), entry.getKey()); - assertEquals(new Integer(i + 1), entry.getValue()); + assertEquals(Integer.valueOf(i), entry.getKey()); + assertEquals(Integer.valueOf(i + 1), entry.getValue()); } assertFalse(it.hasNext()); } @@ -237,10 +230,8 @@ public class SmallSortedMapTest extends TestCase { } Set> entrySet = map.entrySet(); for (int i = 0; i < 6; i++) { - assertTrue( - entrySet.contains(new SimpleEntry(i, i + 1))); - assertFalse( - entrySet.contains(new SimpleEntry(i, i))); + assertTrue(entrySet.contains(new SimpleEntry(i, i + 1))); + assertFalse(entrySet.contains(new SimpleEntry(i, i))); } } @@ -248,13 +239,12 @@ public class SmallSortedMapTest extends TestCase { SmallSortedMap map = SmallSortedMap.newInstanceForTest(3); Set> entrySet = map.entrySet(); for (int i = 0; i < 6; i++) { - Map.Entry entry = - new SimpleEntry(i, i + 1); + Map.Entry entry = new SimpleEntry(i, i + 1); assertTrue(entrySet.add(entry)); assertFalse(entrySet.add(entry)); } for (int i = 0; i < 6; i++) { - assertEquals(new Integer(i + 1), map.get(i)); + assertEquals(Integer.valueOf(i + 1), map.get(i)); } assertEquals(3, map.getNumArrayEntries()); assertEquals(3, map.getNumOverflowEntries()); @@ -268,8 +258,7 @@ public class SmallSortedMapTest extends TestCase { assertNull(map.put(i, i + 1)); } for (int i = 0; i < 6; i++) { - Map.Entry entry = - new SimpleEntry(i, i + 1); + Map.Entry entry = new SimpleEntry(i, i + 1); assertTrue(entrySet.remove(entry)); assertFalse(entrySet.remove(entry)); } @@ -284,7 +273,7 @@ public class SmallSortedMapTest extends TestCase { for (int i = 0; i < 6; i++) { assertNull(map.put(i, i + 1)); } - map.entrySet().clear(); + map.clear(); assertTrue(map.isEmpty()); assertEquals(0, map.getNumArrayEntries()); assertEquals(0, map.getNumOverflowEntries()); @@ -300,8 +289,8 @@ public class SmallSortedMapTest extends TestCase { for (int i = 0; i < 6; i++) { assertTrue(it.hasNext()); Map.Entry entry = it.next(); - assertEquals(new Integer(i), entry.getKey()); - assertEquals(new Integer(i + 1), entry.getValue()); + assertEquals(Integer.valueOf(i), entry.getKey()); + assertEquals(Integer.valueOf(i + 1), entry.getValue()); } assertFalse(it.hasNext()); } @@ -332,7 +321,7 @@ public class SmallSortedMapTest extends TestCase { entry.setValue(i + 23); } for (int i = 0; i < 6; i++) { - assertEquals(new Integer(i + 23), map.get(i)); + assertEquals(Integer.valueOf(i + 23), map.get(i)); } } @@ -342,7 +331,7 @@ public class SmallSortedMapTest extends TestCase { assertNull(map.put(i, i + 1)); } map.makeImmutable(); - assertEquals(new Integer(1), map.get(0)); + assertEquals(Integer.valueOf(1), map.get(0)); assertEquals(6, map.size()); try { diff --git a/java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java b/java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java index 4af5542912..3d82c5f9af 100644 --- a/java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java +++ b/java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java @@ -33,9 +33,9 @@ package com.google.protobuf; import junit.framework.TestCase; /** - * Tests that proto2 api generation doesn't cause compile errors when - * compiling protocol buffers that have names that would otherwise conflict - * if not fully qualified (like @Deprecated and @Override). + * Tests that proto2 api generation doesn't cause compile errors when compiling protocol buffers + * that have names that would otherwise conflict if not fully qualified (like @Deprecated + * and @Override). * * @author jonp@google.com (Jon Perlow) */ @@ -48,17 +48,11 @@ public class TestBadIdentifiers extends TestCase { } public void testGetDescriptor() { - Descriptors.FileDescriptor fileDescriptor = - TestBadIdentifiersProto.getDescriptor(); - String descriptorField = TestBadIdentifiersProto.Descriptor - .getDefaultInstance().getDescriptor(); - Descriptors.Descriptor protoDescriptor = TestBadIdentifiersProto.Descriptor - .getDefaultInstance().getDescriptorForType(); - String nestedDescriptorField = TestBadIdentifiersProto.Descriptor - .NestedDescriptor.getDefaultInstance().getDescriptor(); - Descriptors.Descriptor nestedProtoDescriptor = TestBadIdentifiersProto - .Descriptor.NestedDescriptor.getDefaultInstance() - .getDescriptorForType(); + TestBadIdentifiersProto.getDescriptor(); + TestBadIdentifiersProto.Descriptor.getDefaultInstance().getDescriptor(); + TestBadIdentifiersProto.Descriptor.getDefaultInstance().getDescriptorForType(); + TestBadIdentifiersProto.Descriptor.NestedDescriptor.getDefaultInstance().getDescriptor(); + TestBadIdentifiersProto.Descriptor.NestedDescriptor.getDefaultInstance().getDescriptorForType(); } public void testConflictingFieldNames() throws Exception { @@ -87,10 +81,16 @@ public class TestBadIdentifiers extends TestCase { assertEquals(0, message.getInt32FieldList31()); assertEquals(0, message.getInt64FieldCount()); - assertEquals(0L, message.getExtension( - TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldCount).longValue()); - assertEquals(0L, message.getExtension( - TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldList).longValue()); + assertEquals( + 0L, + message + .getExtension(TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldCount) + .longValue()); + assertEquals( + 0L, + message + .getExtension(TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldList) + .longValue()); assertEquals("", message.getFieldName32()); assertEquals("", message.getFieldName33()); diff --git a/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java b/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java index 37f94c03bc..798d7ca612 100644 --- a/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java +++ b/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java @@ -75,9 +75,15 @@ public final class TestBadIdentifiersLite extends TestCase { assertEquals(0, message.getInt32FieldList31()); assertEquals(0, message.getInt64FieldCount()); - assertEquals(0L, message.getExtension( - TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldCount).longValue()); - assertEquals(0L, message.getExtension( - TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldList).longValue()); + assertEquals( + 0L, + message + .getExtension(TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldCount) + .longValue()); + assertEquals( + 0L, + message + .getExtension(TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldList) + .longValue()); } } diff --git a/java/core/src/test/java/com/google/protobuf/TestUtil.java b/java/core/src/test/java/com/google/protobuf/TestUtil.java index 8ec22d3f12..48ee9574dc 100644 --- a/java/core/src/test/java/com/google/protobuf/TestUtil.java +++ b/java/core/src/test/java/com/google/protobuf/TestUtil.java @@ -237,14 +237,12 @@ import java.io.RandomAccessFile; import junit.framework.Assert; /** - * Contains methods for setting all fields of {@code TestAllTypes} to - * some values as well as checking that all the fields are set to those values. - * These are useful for testing various protocol message features, e.g. - * set all fields of a message, serialize it, parse it, and check that all - * fields are set. + * Contains methods for setting all fields of {@code TestAllTypes} to some values as well as + * checking that all the fields are set to those values. These are useful for testing various + * protocol message features, e.g. set all fields of a message, serialize it, parse it, and check + * that all fields are set. * - *

This code is not to be used outside of {@code com.google.protobuf} and - * subpackages. + *

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

Normally {@code baseDescriptor} should be a descriptor for the type {@code TestAllTypes}, + * defined in {@code google/protobuf/unittest.proto}. However, if {@code extensionRegistry} + * is non-null, then {@code baseDescriptor} should be for {@code TestAllExtensions} instead, and + * instead of reading and writing normal fields, the tester will read and write extensions. All + * of {@code TestAllExtensions}' extensions must be registered in the registry. */ - public ReflectionTester(Descriptors.Descriptor baseDescriptor, - ExtensionRegistry extensionRegistry) { + public ReflectionTester( + Descriptors.Descriptor baseDescriptor, ExtensionRegistry extensionRegistry) { this.baseDescriptor = baseDescriptor; this.extensionRegistry = extensionRegistry; @@ -2724,39 +2713,34 @@ public final class TestUtil { // Use testAllTypes, rather than baseDescriptor, to allow // initialization using TestPackedTypes descriptors. These objects // won't be used by the methods for packed fields. - this.optionalGroup = - testAllTypes.findNestedTypeByName("OptionalGroup"); - this.repeatedGroup = - testAllTypes.findNestedTypeByName("RepeatedGroup"); + this.optionalGroup = testAllTypes.findNestedTypeByName("OptionalGroup"); + this.repeatedGroup = testAllTypes.findNestedTypeByName("RepeatedGroup"); } else { - this.optionalGroup = - file.findMessageTypeByName("OptionalGroup_extension"); - this.repeatedGroup = - file.findMessageTypeByName("RepeatedGroup_extension"); + this.optionalGroup = file.findMessageTypeByName("OptionalGroup_extension"); + this.repeatedGroup = file.findMessageTypeByName("RepeatedGroup_extension"); } this.nestedMessage = testAllTypes.findNestedTypeByName("NestedMessage"); this.foreignMessage = file.findMessageTypeByName("ForeignMessage"); this.importMessage = importFile.findMessageTypeByName("ImportMessage"); - this.publicImportMessage = publicImportFile.findMessageTypeByName( - "PublicImportMessage"); + this.publicImportMessage = publicImportFile.findMessageTypeByName("PublicImportMessage"); this.nestedEnum = testAllTypes.findEnumTypeByName("NestedEnum"); this.foreignEnum = file.findEnumTypeByName("ForeignEnum"); this.importEnum = importFile.findEnumTypeByName("ImportEnum"); - Assert.assertNotNull(optionalGroup ); - Assert.assertNotNull(repeatedGroup ); - Assert.assertNotNull(nestedMessage ); + Assert.assertNotNull(optionalGroup); + Assert.assertNotNull(repeatedGroup); + Assert.assertNotNull(nestedMessage); Assert.assertNotNull(foreignMessage); - Assert.assertNotNull(importMessage ); - Assert.assertNotNull(nestedEnum ); - Assert.assertNotNull(foreignEnum ); - Assert.assertNotNull(importEnum ); + Assert.assertNotNull(importMessage); + Assert.assertNotNull(nestedEnum); + Assert.assertNotNull(foreignEnum); + Assert.assertNotNull(importEnum); - this.nestedB = nestedMessage .findFieldByName("bb"); + this.nestedB = nestedMessage.findFieldByName("bb"); this.foreignC = foreignMessage.findFieldByName("c"); - this.importD = importMessage .findFieldByName("d"); - this.importE = publicImportMessage.findFieldByName("e"); + this.importD = importMessage.findFieldByName("d"); + this.importE = publicImportMessage.findFieldByName("e"); this.nestedFoo = nestedEnum.findValueByName("FOO"); this.nestedBar = nestedEnum.findValueByName("BAR"); this.nestedBaz = nestedEnum.findValueByName("BAZ"); @@ -2770,26 +2754,24 @@ public final class TestUtil { this.groupA = optionalGroup.findFieldByName("a"); this.repeatedGroupA = repeatedGroup.findFieldByName("a"); - Assert.assertNotNull(groupA ); + Assert.assertNotNull(groupA); Assert.assertNotNull(repeatedGroupA); - Assert.assertNotNull(nestedB ); - Assert.assertNotNull(foreignC ); - Assert.assertNotNull(importD ); - Assert.assertNotNull(importE ); - Assert.assertNotNull(nestedFoo ); - Assert.assertNotNull(nestedBar ); - Assert.assertNotNull(nestedBaz ); - Assert.assertNotNull(foreignFoo ); - Assert.assertNotNull(foreignBar ); - Assert.assertNotNull(foreignBaz ); - Assert.assertNotNull(importFoo ); - Assert.assertNotNull(importBar ); - Assert.assertNotNull(importBaz ); + Assert.assertNotNull(nestedB); + Assert.assertNotNull(foreignC); + Assert.assertNotNull(importD); + Assert.assertNotNull(importE); + Assert.assertNotNull(nestedFoo); + Assert.assertNotNull(nestedBar); + Assert.assertNotNull(nestedBaz); + Assert.assertNotNull(foreignFoo); + Assert.assertNotNull(foreignBar); + Assert.assertNotNull(foreignBaz); + Assert.assertNotNull(importFoo); + Assert.assertNotNull(importBar); + Assert.assertNotNull(importBaz); } - /** - * Shorthand to get a FieldDescriptor for a field of unittest::TestAllTypes. - */ + /** Shorthand to get a FieldDescriptor for a field of unittest::TestAllTypes. */ private Descriptors.FieldDescriptor f(String name) { Descriptors.FieldDescriptor result; if (extensionRegistry == null) { @@ -2802,9 +2784,8 @@ public final class TestUtil { } /** - * Calls {@code parent.newBuilderForField()} or uses the - * {@code ExtensionRegistry} to find an appropriate builder, depending - * on what type is being tested. + * Calls {@code parent.newBuilderForField()} or uses the {@code ExtensionRegistry} to find an + * appropriate builder, depending on what type is being tested. */ private Message.Builder newBuilderForField( Message.Builder parent, Descriptors.FieldDescriptor field) { @@ -2812,8 +2793,8 @@ public final class TestUtil { return parent.newBuilderForField(field); } else { ExtensionRegistry.ExtensionInfo extension = - extensionRegistry.findImmutableExtensionByNumber( - field.getContainingType(), field.getNumber()); + extensionRegistry.findImmutableExtensionByNumber( + field.getContainingType(), field.getNumber()); Assert.assertNotNull(extension); Assert.assertNotNull(extension.defaultInstance); return extension.defaultInstance.newBuilderForType(); @@ -2823,210 +2804,223 @@ public final class TestUtil { // ------------------------------------------------------------------- /** - * Set every field of {@code message} to the values expected by - * {@code assertAllFieldsSet()}, using the {@link Message.Builder} - * reflection interface. + * Set every field of {@code message} to the values expected by {@code assertAllFieldsSet()}, + * using the {@link Message.Builder} reflection interface. */ void setAllFieldsViaReflection(Message.Builder message) { - message.setField(f("optional_int32" ), 101 ); - message.setField(f("optional_int64" ), 102L); - message.setField(f("optional_uint32" ), 103 ); - message.setField(f("optional_uint64" ), 104L); - message.setField(f("optional_sint32" ), 105 ); - message.setField(f("optional_sint64" ), 106L); - message.setField(f("optional_fixed32" ), 107 ); - message.setField(f("optional_fixed64" ), 108L); - message.setField(f("optional_sfixed32"), 109 ); + message.setField(f("optional_int32"), 101); + message.setField(f("optional_int64"), 102L); + message.setField(f("optional_uint32"), 103); + message.setField(f("optional_uint64"), 104L); + message.setField(f("optional_sint32"), 105); + message.setField(f("optional_sint64"), 106L); + message.setField(f("optional_fixed32"), 107); + message.setField(f("optional_fixed64"), 108L); + message.setField(f("optional_sfixed32"), 109); message.setField(f("optional_sfixed64"), 110L); - message.setField(f("optional_float" ), 111F); - message.setField(f("optional_double" ), 112D); - message.setField(f("optional_bool" ), true); - message.setField(f("optional_string" ), "115"); - message.setField(f("optional_bytes" ), toBytes("116")); - - message.setField(f("optionalgroup"), - newBuilderForField(message, f("optionalgroup")) - .setField(groupA, 117).build()); - message.setField(f("optional_nested_message"), - newBuilderForField(message, f("optional_nested_message")) - .setField(nestedB, 118).build()); - message.setField(f("optional_foreign_message"), - newBuilderForField(message, f("optional_foreign_message")) - .setField(foreignC, 119).build()); - message.setField(f("optional_import_message"), - newBuilderForField(message, f("optional_import_message")) - .setField(importD, 120).build()); - message.setField(f("optional_public_import_message"), - newBuilderForField(message, f("optional_public_import_message")) - .setField(importE, 126).build()); - message.setField(f("optional_lazy_message"), - newBuilderForField(message, f("optional_lazy_message")) - .setField(nestedB, 127).build()); - - message.setField(f("optional_nested_enum" ), nestedBaz); + message.setField(f("optional_float"), 111F); + message.setField(f("optional_double"), 112D); + message.setField(f("optional_bool"), true); + message.setField(f("optional_string"), "115"); + message.setField(f("optional_bytes"), toBytes("116")); + + message.setField( + f("optionalgroup"), + newBuilderForField(message, f("optionalgroup")).setField(groupA, 117).build()); + message.setField( + f("optional_nested_message"), + newBuilderForField(message, f("optional_nested_message")).setField(nestedB, 118).build()); + message.setField( + f("optional_foreign_message"), + newBuilderForField(message, f("optional_foreign_message")) + .setField(foreignC, 119) + .build()); + message.setField( + f("optional_import_message"), + newBuilderForField(message, f("optional_import_message")).setField(importD, 120).build()); + message.setField( + f("optional_public_import_message"), + newBuilderForField(message, f("optional_public_import_message")) + .setField(importE, 126) + .build()); + message.setField( + f("optional_lazy_message"), + newBuilderForField(message, f("optional_lazy_message")).setField(nestedB, 127).build()); + + message.setField(f("optional_nested_enum"), nestedBaz); message.setField(f("optional_foreign_enum"), foreignBaz); - message.setField(f("optional_import_enum" ), importBaz); + message.setField(f("optional_import_enum"), importBaz); - message.setField(f("optional_string_piece" ), "124"); - message.setField(f("optional_cord" ), "125"); + message.setField(f("optional_string_piece"), "124"); + message.setField(f("optional_cord"), "125"); // ----------------------------------------------------------------- - message.addRepeatedField(f("repeated_int32" ), 201 ); - message.addRepeatedField(f("repeated_int64" ), 202L); - message.addRepeatedField(f("repeated_uint32" ), 203 ); - message.addRepeatedField(f("repeated_uint64" ), 204L); - message.addRepeatedField(f("repeated_sint32" ), 205 ); - message.addRepeatedField(f("repeated_sint64" ), 206L); - message.addRepeatedField(f("repeated_fixed32" ), 207 ); - message.addRepeatedField(f("repeated_fixed64" ), 208L); - message.addRepeatedField(f("repeated_sfixed32"), 209 ); + message.addRepeatedField(f("repeated_int32"), 201); + message.addRepeatedField(f("repeated_int64"), 202L); + message.addRepeatedField(f("repeated_uint32"), 203); + message.addRepeatedField(f("repeated_uint64"), 204L); + message.addRepeatedField(f("repeated_sint32"), 205); + message.addRepeatedField(f("repeated_sint64"), 206L); + message.addRepeatedField(f("repeated_fixed32"), 207); + message.addRepeatedField(f("repeated_fixed64"), 208L); + message.addRepeatedField(f("repeated_sfixed32"), 209); message.addRepeatedField(f("repeated_sfixed64"), 210L); - message.addRepeatedField(f("repeated_float" ), 211F); - message.addRepeatedField(f("repeated_double" ), 212D); - message.addRepeatedField(f("repeated_bool" ), true); - message.addRepeatedField(f("repeated_string" ), "215"); - message.addRepeatedField(f("repeated_bytes" ), toBytes("216")); - - message.addRepeatedField(f("repeatedgroup"), - newBuilderForField(message, f("repeatedgroup")) - .setField(repeatedGroupA, 217).build()); - message.addRepeatedField(f("repeated_nested_message"), - newBuilderForField(message, f("repeated_nested_message")) - .setField(nestedB, 218).build()); - message.addRepeatedField(f("repeated_foreign_message"), - newBuilderForField(message, f("repeated_foreign_message")) - .setField(foreignC, 219).build()); - message.addRepeatedField(f("repeated_import_message"), - newBuilderForField(message, f("repeated_import_message")) - .setField(importD, 220).build()); - message.addRepeatedField(f("repeated_lazy_message"), - newBuilderForField(message, f("repeated_lazy_message")) - .setField(nestedB, 227).build()); - - message.addRepeatedField(f("repeated_nested_enum" ), nestedBar); + message.addRepeatedField(f("repeated_float"), 211F); + message.addRepeatedField(f("repeated_double"), 212D); + message.addRepeatedField(f("repeated_bool"), true); + message.addRepeatedField(f("repeated_string"), "215"); + message.addRepeatedField(f("repeated_bytes"), toBytes("216")); + + message.addRepeatedField( + f("repeatedgroup"), + newBuilderForField(message, f("repeatedgroup")).setField(repeatedGroupA, 217).build()); + message.addRepeatedField( + f("repeated_nested_message"), + newBuilderForField(message, f("repeated_nested_message")).setField(nestedB, 218).build()); + message.addRepeatedField( + f("repeated_foreign_message"), + newBuilderForField(message, f("repeated_foreign_message")) + .setField(foreignC, 219) + .build()); + message.addRepeatedField( + f("repeated_import_message"), + newBuilderForField(message, f("repeated_import_message")).setField(importD, 220).build()); + message.addRepeatedField( + f("repeated_lazy_message"), + newBuilderForField(message, f("repeated_lazy_message")).setField(nestedB, 227).build()); + + message.addRepeatedField(f("repeated_nested_enum"), nestedBar); message.addRepeatedField(f("repeated_foreign_enum"), foreignBar); - message.addRepeatedField(f("repeated_import_enum" ), importBar); + message.addRepeatedField(f("repeated_import_enum"), importBar); - message.addRepeatedField(f("repeated_string_piece" ), "224"); - message.addRepeatedField(f("repeated_cord" ), "225"); + message.addRepeatedField(f("repeated_string_piece"), "224"); + message.addRepeatedField(f("repeated_cord"), "225"); // Add a second one of each field. - message.addRepeatedField(f("repeated_int32" ), 301 ); - message.addRepeatedField(f("repeated_int64" ), 302L); - message.addRepeatedField(f("repeated_uint32" ), 303 ); - message.addRepeatedField(f("repeated_uint64" ), 304L); - message.addRepeatedField(f("repeated_sint32" ), 305 ); - message.addRepeatedField(f("repeated_sint64" ), 306L); - message.addRepeatedField(f("repeated_fixed32" ), 307 ); - message.addRepeatedField(f("repeated_fixed64" ), 308L); - message.addRepeatedField(f("repeated_sfixed32"), 309 ); + message.addRepeatedField(f("repeated_int32"), 301); + message.addRepeatedField(f("repeated_int64"), 302L); + message.addRepeatedField(f("repeated_uint32"), 303); + message.addRepeatedField(f("repeated_uint64"), 304L); + message.addRepeatedField(f("repeated_sint32"), 305); + message.addRepeatedField(f("repeated_sint64"), 306L); + message.addRepeatedField(f("repeated_fixed32"), 307); + message.addRepeatedField(f("repeated_fixed64"), 308L); + message.addRepeatedField(f("repeated_sfixed32"), 309); message.addRepeatedField(f("repeated_sfixed64"), 310L); - message.addRepeatedField(f("repeated_float" ), 311F); - message.addRepeatedField(f("repeated_double" ), 312D); - message.addRepeatedField(f("repeated_bool" ), false); - message.addRepeatedField(f("repeated_string" ), "315"); - message.addRepeatedField(f("repeated_bytes" ), toBytes("316")); - - message.addRepeatedField(f("repeatedgroup"), - newBuilderForField(message, f("repeatedgroup")) - .setField(repeatedGroupA, 317).build()); - message.addRepeatedField(f("repeated_nested_message"), - newBuilderForField(message, f("repeated_nested_message")) - .setField(nestedB, 318).build()); - message.addRepeatedField(f("repeated_foreign_message"), - newBuilderForField(message, f("repeated_foreign_message")) - .setField(foreignC, 319).build()); - message.addRepeatedField(f("repeated_import_message"), - newBuilderForField(message, f("repeated_import_message")) - .setField(importD, 320).build()); - message.addRepeatedField(f("repeated_lazy_message"), - newBuilderForField(message, f("repeated_lazy_message")) - .setField(nestedB, 327).build()); - - message.addRepeatedField(f("repeated_nested_enum" ), nestedBaz); + message.addRepeatedField(f("repeated_float"), 311F); + message.addRepeatedField(f("repeated_double"), 312D); + message.addRepeatedField(f("repeated_bool"), false); + message.addRepeatedField(f("repeated_string"), "315"); + message.addRepeatedField(f("repeated_bytes"), toBytes("316")); + + message.addRepeatedField( + f("repeatedgroup"), + newBuilderForField(message, f("repeatedgroup")).setField(repeatedGroupA, 317).build()); + message.addRepeatedField( + f("repeated_nested_message"), + newBuilderForField(message, f("repeated_nested_message")).setField(nestedB, 318).build()); + message.addRepeatedField( + f("repeated_foreign_message"), + newBuilderForField(message, f("repeated_foreign_message")) + .setField(foreignC, 319) + .build()); + message.addRepeatedField( + f("repeated_import_message"), + newBuilderForField(message, f("repeated_import_message")).setField(importD, 320).build()); + message.addRepeatedField( + f("repeated_lazy_message"), + newBuilderForField(message, f("repeated_lazy_message")).setField(nestedB, 327).build()); + + message.addRepeatedField(f("repeated_nested_enum"), nestedBaz); message.addRepeatedField(f("repeated_foreign_enum"), foreignBaz); - message.addRepeatedField(f("repeated_import_enum" ), importBaz); + message.addRepeatedField(f("repeated_import_enum"), importBaz); - message.addRepeatedField(f("repeated_string_piece" ), "324"); - message.addRepeatedField(f("repeated_cord" ), "325"); + message.addRepeatedField(f("repeated_string_piece"), "324"); + message.addRepeatedField(f("repeated_cord"), "325"); // ----------------------------------------------------------------- - message.setField(f("default_int32" ), 401 ); - message.setField(f("default_int64" ), 402L); - message.setField(f("default_uint32" ), 403 ); - message.setField(f("default_uint64" ), 404L); - message.setField(f("default_sint32" ), 405 ); - message.setField(f("default_sint64" ), 406L); - message.setField(f("default_fixed32" ), 407 ); - message.setField(f("default_fixed64" ), 408L); - message.setField(f("default_sfixed32"), 409 ); + message.setField(f("default_int32"), 401); + message.setField(f("default_int64"), 402L); + message.setField(f("default_uint32"), 403); + message.setField(f("default_uint64"), 404L); + message.setField(f("default_sint32"), 405); + message.setField(f("default_sint64"), 406L); + message.setField(f("default_fixed32"), 407); + message.setField(f("default_fixed64"), 408L); + message.setField(f("default_sfixed32"), 409); message.setField(f("default_sfixed64"), 410L); - message.setField(f("default_float" ), 411F); - message.setField(f("default_double" ), 412D); - message.setField(f("default_bool" ), false); - message.setField(f("default_string" ), "415"); - message.setField(f("default_bytes" ), toBytes("416")); + message.setField(f("default_float"), 411F); + message.setField(f("default_double"), 412D); + message.setField(f("default_bool"), false); + message.setField(f("default_string"), "415"); + message.setField(f("default_bytes"), toBytes("416")); - message.setField(f("default_nested_enum" ), nestedFoo); + message.setField(f("default_nested_enum"), nestedFoo); message.setField(f("default_foreign_enum"), foreignFoo); - message.setField(f("default_import_enum" ), importFoo); + message.setField(f("default_import_enum"), importFoo); - message.setField(f("default_string_piece" ), "424"); - message.setField(f("default_cord" ), "425"); + message.setField(f("default_string_piece"), "424"); + message.setField(f("default_cord"), "425"); - message.setField(f("oneof_uint32" ), 601); - message.setField(f("oneof_nested_message"), - newBuilderForField(message, f("oneof_nested_message")) - .setField(nestedB, 602).build()); - message.setField(f("oneof_string" ), "603"); - message.setField(f("oneof_bytes" ), toBytes("604")); + message.setField(f("oneof_uint32"), 601); + message.setField( + f("oneof_nested_message"), + newBuilderForField(message, f("oneof_nested_message")).setField(nestedB, 602).build()); + message.setField(f("oneof_string"), "603"); + message.setField(f("oneof_bytes"), toBytes("604")); } // ------------------------------------------------------------------- /** - * Modify the repeated fields of {@code message} to contain the values - * expected by {@code assertRepeatedFieldsModified()}, using the - * {@link Message.Builder} reflection interface. + * Modify the repeated fields of {@code message} to contain the values expected by {@code + * assertRepeatedFieldsModified()}, using the {@link Message.Builder} reflection interface. */ void modifyRepeatedFieldsViaReflection(Message.Builder message) { - message.setRepeatedField(f("repeated_int32" ), 1, 501 ); - message.setRepeatedField(f("repeated_int64" ), 1, 502L); - message.setRepeatedField(f("repeated_uint32" ), 1, 503 ); - message.setRepeatedField(f("repeated_uint64" ), 1, 504L); - message.setRepeatedField(f("repeated_sint32" ), 1, 505 ); - message.setRepeatedField(f("repeated_sint64" ), 1, 506L); - message.setRepeatedField(f("repeated_fixed32" ), 1, 507 ); - message.setRepeatedField(f("repeated_fixed64" ), 1, 508L); - message.setRepeatedField(f("repeated_sfixed32"), 1, 509 ); + message.setRepeatedField(f("repeated_int32"), 1, 501); + message.setRepeatedField(f("repeated_int64"), 1, 502L); + message.setRepeatedField(f("repeated_uint32"), 1, 503); + message.setRepeatedField(f("repeated_uint64"), 1, 504L); + message.setRepeatedField(f("repeated_sint32"), 1, 505); + message.setRepeatedField(f("repeated_sint64"), 1, 506L); + message.setRepeatedField(f("repeated_fixed32"), 1, 507); + message.setRepeatedField(f("repeated_fixed64"), 1, 508L); + message.setRepeatedField(f("repeated_sfixed32"), 1, 509); message.setRepeatedField(f("repeated_sfixed64"), 1, 510L); - message.setRepeatedField(f("repeated_float" ), 1, 511F); - message.setRepeatedField(f("repeated_double" ), 1, 512D); - message.setRepeatedField(f("repeated_bool" ), 1, true); - message.setRepeatedField(f("repeated_string" ), 1, "515"); - message.setRepeatedField(f("repeated_bytes" ), 1, toBytes("516")); - - message.setRepeatedField(f("repeatedgroup"), 1, - newBuilderForField(message, f("repeatedgroup")) - .setField(repeatedGroupA, 517).build()); - message.setRepeatedField(f("repeated_nested_message"), 1, - newBuilderForField(message, f("repeated_nested_message")) - .setField(nestedB, 518).build()); - message.setRepeatedField(f("repeated_foreign_message"), 1, - newBuilderForField(message, f("repeated_foreign_message")) - .setField(foreignC, 519).build()); - message.setRepeatedField(f("repeated_import_message"), 1, - newBuilderForField(message, f("repeated_import_message")) - .setField(importD, 520).build()); - message.setRepeatedField(f("repeated_lazy_message"), 1, - newBuilderForField(message, f("repeated_lazy_message")) - .setField(nestedB, 527).build()); - - message.setRepeatedField(f("repeated_nested_enum" ), 1, nestedFoo); + message.setRepeatedField(f("repeated_float"), 1, 511F); + message.setRepeatedField(f("repeated_double"), 1, 512D); + message.setRepeatedField(f("repeated_bool"), 1, true); + message.setRepeatedField(f("repeated_string"), 1, "515"); + message.setRepeatedField(f("repeated_bytes"), 1, toBytes("516")); + + message.setRepeatedField( + f("repeatedgroup"), + 1, + newBuilderForField(message, f("repeatedgroup")).setField(repeatedGroupA, 517).build()); + message.setRepeatedField( + f("repeated_nested_message"), + 1, + newBuilderForField(message, f("repeated_nested_message")).setField(nestedB, 518).build()); + message.setRepeatedField( + f("repeated_foreign_message"), + 1, + newBuilderForField(message, f("repeated_foreign_message")) + .setField(foreignC, 519) + .build()); + message.setRepeatedField( + f("repeated_import_message"), + 1, + newBuilderForField(message, f("repeated_import_message")).setField(importD, 520).build()); + message.setRepeatedField( + f("repeated_lazy_message"), + 1, + newBuilderForField(message, f("repeated_lazy_message")).setField(nestedB, 527).build()); + + message.setRepeatedField(f("repeated_nested_enum"), 1, nestedFoo); message.setRepeatedField(f("repeated_foreign_enum"), 1, foreignFoo); - message.setRepeatedField(f("repeated_import_enum" ), 1, importFoo); + message.setRepeatedField(f("repeated_import_enum"), 1, importFoo); message.setRepeatedField(f("repeated_string_piece"), 1, "524"); message.setRepeatedField(f("repeated_cord"), 1, "525"); @@ -3035,244 +3029,235 @@ public final class TestUtil { // ------------------------------------------------------------------- /** - * Assert (using {@code junit.framework.Assert}} that all fields of - * {@code message} are set to the values assigned by {@code setAllFields}, - * using the {@link Message} reflection interface. + * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to + * the values assigned by {@code setAllFields}, using the {@link Message} reflection interface. */ public void assertAllFieldsSetViaReflection(MessageOrBuilder message) { - Assert.assertTrue(message.hasField(f("optional_int32" ))); - Assert.assertTrue(message.hasField(f("optional_int64" ))); - Assert.assertTrue(message.hasField(f("optional_uint32" ))); - Assert.assertTrue(message.hasField(f("optional_uint64" ))); - Assert.assertTrue(message.hasField(f("optional_sint32" ))); - Assert.assertTrue(message.hasField(f("optional_sint64" ))); - Assert.assertTrue(message.hasField(f("optional_fixed32" ))); - Assert.assertTrue(message.hasField(f("optional_fixed64" ))); + Assert.assertTrue(message.hasField(f("optional_int32"))); + Assert.assertTrue(message.hasField(f("optional_int64"))); + Assert.assertTrue(message.hasField(f("optional_uint32"))); + Assert.assertTrue(message.hasField(f("optional_uint64"))); + Assert.assertTrue(message.hasField(f("optional_sint32"))); + Assert.assertTrue(message.hasField(f("optional_sint64"))); + Assert.assertTrue(message.hasField(f("optional_fixed32"))); + Assert.assertTrue(message.hasField(f("optional_fixed64"))); Assert.assertTrue(message.hasField(f("optional_sfixed32"))); Assert.assertTrue(message.hasField(f("optional_sfixed64"))); - Assert.assertTrue(message.hasField(f("optional_float" ))); - Assert.assertTrue(message.hasField(f("optional_double" ))); - Assert.assertTrue(message.hasField(f("optional_bool" ))); - Assert.assertTrue(message.hasField(f("optional_string" ))); - Assert.assertTrue(message.hasField(f("optional_bytes" ))); - - Assert.assertTrue(message.hasField(f("optionalgroup" ))); - Assert.assertTrue(message.hasField(f("optional_nested_message" ))); + Assert.assertTrue(message.hasField(f("optional_float"))); + Assert.assertTrue(message.hasField(f("optional_double"))); + Assert.assertTrue(message.hasField(f("optional_bool"))); + Assert.assertTrue(message.hasField(f("optional_string"))); + Assert.assertTrue(message.hasField(f("optional_bytes"))); + + Assert.assertTrue(message.hasField(f("optionalgroup"))); + Assert.assertTrue(message.hasField(f("optional_nested_message"))); Assert.assertTrue(message.hasField(f("optional_foreign_message"))); - Assert.assertTrue(message.hasField(f("optional_import_message" ))); + Assert.assertTrue(message.hasField(f("optional_import_message"))); + Assert.assertTrue(((Message) message.getField(f("optionalgroup"))).hasField(groupA)); Assert.assertTrue( - ((Message)message.getField(f("optionalgroup"))).hasField(groupA)); + ((Message) message.getField(f("optional_nested_message"))).hasField(nestedB)); Assert.assertTrue( - ((Message)message.getField(f("optional_nested_message"))) - .hasField(nestedB)); + ((Message) message.getField(f("optional_foreign_message"))).hasField(foreignC)); Assert.assertTrue( - ((Message)message.getField(f("optional_foreign_message"))) - .hasField(foreignC)); - Assert.assertTrue( - ((Message)message.getField(f("optional_import_message"))) - .hasField(importD)); + ((Message) message.getField(f("optional_import_message"))).hasField(importD)); - Assert.assertTrue(message.hasField(f("optional_nested_enum" ))); + Assert.assertTrue(message.hasField(f("optional_nested_enum"))); Assert.assertTrue(message.hasField(f("optional_foreign_enum"))); - Assert.assertTrue(message.hasField(f("optional_import_enum" ))); + Assert.assertTrue(message.hasField(f("optional_import_enum"))); Assert.assertTrue(message.hasField(f("optional_string_piece"))); Assert.assertTrue(message.hasField(f("optional_cord"))); - Assert.assertEquals(101 , message.getField(f("optional_int32" ))); - Assert.assertEquals(102L , message.getField(f("optional_int64" ))); - Assert.assertEquals(103 , message.getField(f("optional_uint32" ))); - Assert.assertEquals(104L , message.getField(f("optional_uint64" ))); - Assert.assertEquals(105 , message.getField(f("optional_sint32" ))); - Assert.assertEquals(106L , message.getField(f("optional_sint64" ))); - Assert.assertEquals(107 , message.getField(f("optional_fixed32" ))); - Assert.assertEquals(108L , message.getField(f("optional_fixed64" ))); - Assert.assertEquals(109 , message.getField(f("optional_sfixed32"))); - Assert.assertEquals(110L , message.getField(f("optional_sfixed64"))); - Assert.assertEquals(111F , message.getField(f("optional_float" ))); - Assert.assertEquals(112D , message.getField(f("optional_double" ))); - Assert.assertEquals(true , message.getField(f("optional_bool" ))); - Assert.assertEquals("115", message.getField(f("optional_string" ))); + Assert.assertEquals(101, message.getField(f("optional_int32"))); + Assert.assertEquals(102L, message.getField(f("optional_int64"))); + Assert.assertEquals(103, message.getField(f("optional_uint32"))); + Assert.assertEquals(104L, message.getField(f("optional_uint64"))); + Assert.assertEquals(105, message.getField(f("optional_sint32"))); + Assert.assertEquals(106L, message.getField(f("optional_sint64"))); + Assert.assertEquals(107, message.getField(f("optional_fixed32"))); + Assert.assertEquals(108L, message.getField(f("optional_fixed64"))); + Assert.assertEquals(109, message.getField(f("optional_sfixed32"))); + Assert.assertEquals(110L, message.getField(f("optional_sfixed64"))); + Assert.assertEquals(111F, message.getField(f("optional_float"))); + Assert.assertEquals(112D, message.getField(f("optional_double"))); + Assert.assertEquals(true, message.getField(f("optional_bool"))); + Assert.assertEquals("115", message.getField(f("optional_string"))); Assert.assertEquals(toBytes("116"), message.getField(f("optional_bytes"))); - Assert.assertEquals(117, - ((Message)message.getField(f("optionalgroup"))).getField(groupA)); - Assert.assertEquals(118, - ((Message)message.getField(f("optional_nested_message"))) - .getField(nestedB)); - Assert.assertEquals(119, - ((Message)message.getField(f("optional_foreign_message"))) - .getField(foreignC)); - Assert.assertEquals(120, - ((Message)message.getField(f("optional_import_message"))) - .getField(importD)); - Assert.assertEquals(126, - ((Message)message.getField(f("optional_public_import_message"))) - .getField(importE)); - Assert.assertEquals(127, - ((Message)message.getField(f("optional_lazy_message"))) - .getField(nestedB)); - - Assert.assertEquals( nestedBaz, message.getField(f("optional_nested_enum" ))); + Assert.assertEquals(117, ((Message) message.getField(f("optionalgroup"))).getField(groupA)); + Assert.assertEquals( + 118, ((Message) message.getField(f("optional_nested_message"))).getField(nestedB)); + Assert.assertEquals( + 119, ((Message) message.getField(f("optional_foreign_message"))).getField(foreignC)); + Assert.assertEquals( + 120, ((Message) message.getField(f("optional_import_message"))).getField(importD)); + Assert.assertEquals( + 126, ((Message) message.getField(f("optional_public_import_message"))).getField(importE)); + Assert.assertEquals( + 127, ((Message) message.getField(f("optional_lazy_message"))).getField(nestedB)); + + Assert.assertEquals(nestedBaz, message.getField(f("optional_nested_enum"))); Assert.assertEquals(foreignBaz, message.getField(f("optional_foreign_enum"))); - Assert.assertEquals( importBaz, message.getField(f("optional_import_enum" ))); + Assert.assertEquals(importBaz, message.getField(f("optional_import_enum"))); Assert.assertEquals("124", message.getField(f("optional_string_piece"))); Assert.assertEquals("125", message.getField(f("optional_cord"))); // ----------------------------------------------------------------- - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int32" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int64" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint32" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint64" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint32" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint64" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed32" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed64" ))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed64"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed32"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed64"))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_float" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_double" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bool" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bytes" ))); - - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeatedgroup" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_message" ))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_float"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_double"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bool"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bytes"))); + + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeatedgroup"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_message"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_message"))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_message" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_lazy_message" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_enum" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_enum" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_enum" ))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_message"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_lazy_message"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_enum"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_enum"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_enum"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string_piece"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_cord"))); - Assert.assertEquals(201 , message.getRepeatedField(f("repeated_int32" ), 0)); - Assert.assertEquals(202L , message.getRepeatedField(f("repeated_int64" ), 0)); - Assert.assertEquals(203 , message.getRepeatedField(f("repeated_uint32" ), 0)); - Assert.assertEquals(204L , message.getRepeatedField(f("repeated_uint64" ), 0)); - Assert.assertEquals(205 , message.getRepeatedField(f("repeated_sint32" ), 0)); - Assert.assertEquals(206L , message.getRepeatedField(f("repeated_sint64" ), 0)); - Assert.assertEquals(207 , message.getRepeatedField(f("repeated_fixed32" ), 0)); - Assert.assertEquals(208L , message.getRepeatedField(f("repeated_fixed64" ), 0)); - Assert.assertEquals(209 , message.getRepeatedField(f("repeated_sfixed32"), 0)); - Assert.assertEquals(210L , message.getRepeatedField(f("repeated_sfixed64"), 0)); - Assert.assertEquals(211F , message.getRepeatedField(f("repeated_float" ), 0)); - Assert.assertEquals(212D , message.getRepeatedField(f("repeated_double" ), 0)); - Assert.assertEquals(true , message.getRepeatedField(f("repeated_bool" ), 0)); - Assert.assertEquals("215", message.getRepeatedField(f("repeated_string" ), 0)); + Assert.assertEquals(201, message.getRepeatedField(f("repeated_int32"), 0)); + Assert.assertEquals(202L, message.getRepeatedField(f("repeated_int64"), 0)); + Assert.assertEquals(203, message.getRepeatedField(f("repeated_uint32"), 0)); + Assert.assertEquals(204L, message.getRepeatedField(f("repeated_uint64"), 0)); + Assert.assertEquals(205, message.getRepeatedField(f("repeated_sint32"), 0)); + Assert.assertEquals(206L, message.getRepeatedField(f("repeated_sint64"), 0)); + Assert.assertEquals(207, message.getRepeatedField(f("repeated_fixed32"), 0)); + Assert.assertEquals(208L, message.getRepeatedField(f("repeated_fixed64"), 0)); + Assert.assertEquals(209, message.getRepeatedField(f("repeated_sfixed32"), 0)); + Assert.assertEquals(210L, message.getRepeatedField(f("repeated_sfixed64"), 0)); + Assert.assertEquals(211F, message.getRepeatedField(f("repeated_float"), 0)); + Assert.assertEquals(212D, message.getRepeatedField(f("repeated_double"), 0)); + Assert.assertEquals(true, message.getRepeatedField(f("repeated_bool"), 0)); + Assert.assertEquals("215", message.getRepeatedField(f("repeated_string"), 0)); Assert.assertEquals(toBytes("216"), message.getRepeatedField(f("repeated_bytes"), 0)); - Assert.assertEquals(217, - ((Message)message.getRepeatedField(f("repeatedgroup"), 0)) - .getField(repeatedGroupA)); - Assert.assertEquals(218, - ((Message)message.getRepeatedField(f("repeated_nested_message"), 0)) - .getField(nestedB)); - Assert.assertEquals(219, - ((Message)message.getRepeatedField(f("repeated_foreign_message"), 0)) - .getField(foreignC)); - Assert.assertEquals(220, - ((Message)message.getRepeatedField(f("repeated_import_message"), 0)) - .getField(importD)); - Assert.assertEquals(227, - ((Message)message.getRepeatedField(f("repeated_lazy_message"), 0)) - .getField(nestedB)); - - Assert.assertEquals( nestedBar, message.getRepeatedField(f("repeated_nested_enum" ),0)); - Assert.assertEquals(foreignBar, message.getRepeatedField(f("repeated_foreign_enum"),0)); - Assert.assertEquals( importBar, message.getRepeatedField(f("repeated_import_enum" ),0)); + Assert.assertEquals( + 217, + ((Message) message.getRepeatedField(f("repeatedgroup"), 0)).getField(repeatedGroupA)); + Assert.assertEquals( + 218, + ((Message) message.getRepeatedField(f("repeated_nested_message"), 0)).getField(nestedB)); + Assert.assertEquals( + 219, + ((Message) message.getRepeatedField(f("repeated_foreign_message"), 0)) + .getField(foreignC)); + Assert.assertEquals( + 220, + ((Message) message.getRepeatedField(f("repeated_import_message"), 0)).getField(importD)); + Assert.assertEquals( + 227, + ((Message) message.getRepeatedField(f("repeated_lazy_message"), 0)).getField(nestedB)); + + Assert.assertEquals(nestedBar, message.getRepeatedField(f("repeated_nested_enum"), 0)); + Assert.assertEquals(foreignBar, message.getRepeatedField(f("repeated_foreign_enum"), 0)); + Assert.assertEquals(importBar, message.getRepeatedField(f("repeated_import_enum"), 0)); Assert.assertEquals("224", message.getRepeatedField(f("repeated_string_piece"), 0)); Assert.assertEquals("225", message.getRepeatedField(f("repeated_cord"), 0)); - Assert.assertEquals(301 , message.getRepeatedField(f("repeated_int32" ), 1)); - Assert.assertEquals(302L , message.getRepeatedField(f("repeated_int64" ), 1)); - Assert.assertEquals(303 , message.getRepeatedField(f("repeated_uint32" ), 1)); - Assert.assertEquals(304L , message.getRepeatedField(f("repeated_uint64" ), 1)); - Assert.assertEquals(305 , message.getRepeatedField(f("repeated_sint32" ), 1)); - Assert.assertEquals(306L , message.getRepeatedField(f("repeated_sint64" ), 1)); - Assert.assertEquals(307 , message.getRepeatedField(f("repeated_fixed32" ), 1)); - Assert.assertEquals(308L , message.getRepeatedField(f("repeated_fixed64" ), 1)); - Assert.assertEquals(309 , message.getRepeatedField(f("repeated_sfixed32"), 1)); - Assert.assertEquals(310L , message.getRepeatedField(f("repeated_sfixed64"), 1)); - Assert.assertEquals(311F , message.getRepeatedField(f("repeated_float" ), 1)); - Assert.assertEquals(312D , message.getRepeatedField(f("repeated_double" ), 1)); - Assert.assertEquals(false, message.getRepeatedField(f("repeated_bool" ), 1)); - Assert.assertEquals("315", message.getRepeatedField(f("repeated_string" ), 1)); + Assert.assertEquals(301, message.getRepeatedField(f("repeated_int32"), 1)); + Assert.assertEquals(302L, message.getRepeatedField(f("repeated_int64"), 1)); + Assert.assertEquals(303, message.getRepeatedField(f("repeated_uint32"), 1)); + Assert.assertEquals(304L, message.getRepeatedField(f("repeated_uint64"), 1)); + Assert.assertEquals(305, message.getRepeatedField(f("repeated_sint32"), 1)); + Assert.assertEquals(306L, message.getRepeatedField(f("repeated_sint64"), 1)); + Assert.assertEquals(307, message.getRepeatedField(f("repeated_fixed32"), 1)); + Assert.assertEquals(308L, message.getRepeatedField(f("repeated_fixed64"), 1)); + Assert.assertEquals(309, message.getRepeatedField(f("repeated_sfixed32"), 1)); + Assert.assertEquals(310L, message.getRepeatedField(f("repeated_sfixed64"), 1)); + Assert.assertEquals(311F, message.getRepeatedField(f("repeated_float"), 1)); + Assert.assertEquals(312D, message.getRepeatedField(f("repeated_double"), 1)); + Assert.assertEquals(false, message.getRepeatedField(f("repeated_bool"), 1)); + Assert.assertEquals("315", message.getRepeatedField(f("repeated_string"), 1)); Assert.assertEquals(toBytes("316"), message.getRepeatedField(f("repeated_bytes"), 1)); - Assert.assertEquals(317, - ((Message)message.getRepeatedField(f("repeatedgroup"), 1)) - .getField(repeatedGroupA)); - Assert.assertEquals(318, - ((Message)message.getRepeatedField(f("repeated_nested_message"), 1)) - .getField(nestedB)); - Assert.assertEquals(319, - ((Message)message.getRepeatedField(f("repeated_foreign_message"), 1)) - .getField(foreignC)); - Assert.assertEquals(320, - ((Message)message.getRepeatedField(f("repeated_import_message"), 1)) - .getField(importD)); - Assert.assertEquals(327, - ((Message)message.getRepeatedField(f("repeated_lazy_message"), 1)) - .getField(nestedB)); - - Assert.assertEquals( nestedBaz, message.getRepeatedField(f("repeated_nested_enum" ),1)); - Assert.assertEquals(foreignBaz, message.getRepeatedField(f("repeated_foreign_enum"),1)); - Assert.assertEquals( importBaz, message.getRepeatedField(f("repeated_import_enum" ),1)); + Assert.assertEquals( + 317, + ((Message) message.getRepeatedField(f("repeatedgroup"), 1)).getField(repeatedGroupA)); + Assert.assertEquals( + 318, + ((Message) message.getRepeatedField(f("repeated_nested_message"), 1)).getField(nestedB)); + Assert.assertEquals( + 319, + ((Message) message.getRepeatedField(f("repeated_foreign_message"), 1)) + .getField(foreignC)); + Assert.assertEquals( + 320, + ((Message) message.getRepeatedField(f("repeated_import_message"), 1)).getField(importD)); + Assert.assertEquals( + 327, + ((Message) message.getRepeatedField(f("repeated_lazy_message"), 1)).getField(nestedB)); + + Assert.assertEquals(nestedBaz, message.getRepeatedField(f("repeated_nested_enum"), 1)); + Assert.assertEquals(foreignBaz, message.getRepeatedField(f("repeated_foreign_enum"), 1)); + Assert.assertEquals(importBaz, message.getRepeatedField(f("repeated_import_enum"), 1)); Assert.assertEquals("324", message.getRepeatedField(f("repeated_string_piece"), 1)); Assert.assertEquals("325", message.getRepeatedField(f("repeated_cord"), 1)); // ----------------------------------------------------------------- - Assert.assertTrue(message.hasField(f("default_int32" ))); - Assert.assertTrue(message.hasField(f("default_int64" ))); - Assert.assertTrue(message.hasField(f("default_uint32" ))); - Assert.assertTrue(message.hasField(f("default_uint64" ))); - Assert.assertTrue(message.hasField(f("default_sint32" ))); - Assert.assertTrue(message.hasField(f("default_sint64" ))); - Assert.assertTrue(message.hasField(f("default_fixed32" ))); - Assert.assertTrue(message.hasField(f("default_fixed64" ))); + Assert.assertTrue(message.hasField(f("default_int32"))); + Assert.assertTrue(message.hasField(f("default_int64"))); + Assert.assertTrue(message.hasField(f("default_uint32"))); + Assert.assertTrue(message.hasField(f("default_uint64"))); + Assert.assertTrue(message.hasField(f("default_sint32"))); + Assert.assertTrue(message.hasField(f("default_sint64"))); + Assert.assertTrue(message.hasField(f("default_fixed32"))); + Assert.assertTrue(message.hasField(f("default_fixed64"))); Assert.assertTrue(message.hasField(f("default_sfixed32"))); Assert.assertTrue(message.hasField(f("default_sfixed64"))); - Assert.assertTrue(message.hasField(f("default_float" ))); - Assert.assertTrue(message.hasField(f("default_double" ))); - Assert.assertTrue(message.hasField(f("default_bool" ))); - Assert.assertTrue(message.hasField(f("default_string" ))); - Assert.assertTrue(message.hasField(f("default_bytes" ))); + Assert.assertTrue(message.hasField(f("default_float"))); + Assert.assertTrue(message.hasField(f("default_double"))); + Assert.assertTrue(message.hasField(f("default_bool"))); + Assert.assertTrue(message.hasField(f("default_string"))); + Assert.assertTrue(message.hasField(f("default_bytes"))); - Assert.assertTrue(message.hasField(f("default_nested_enum" ))); + Assert.assertTrue(message.hasField(f("default_nested_enum"))); Assert.assertTrue(message.hasField(f("default_foreign_enum"))); - Assert.assertTrue(message.hasField(f("default_import_enum" ))); + Assert.assertTrue(message.hasField(f("default_import_enum"))); Assert.assertTrue(message.hasField(f("default_string_piece"))); Assert.assertTrue(message.hasField(f("default_cord"))); - Assert.assertEquals(401 , message.getField(f("default_int32" ))); - Assert.assertEquals(402L , message.getField(f("default_int64" ))); - Assert.assertEquals(403 , message.getField(f("default_uint32" ))); - Assert.assertEquals(404L , message.getField(f("default_uint64" ))); - Assert.assertEquals(405 , message.getField(f("default_sint32" ))); - Assert.assertEquals(406L , message.getField(f("default_sint64" ))); - Assert.assertEquals(407 , message.getField(f("default_fixed32" ))); - Assert.assertEquals(408L , message.getField(f("default_fixed64" ))); - Assert.assertEquals(409 , message.getField(f("default_sfixed32"))); - Assert.assertEquals(410L , message.getField(f("default_sfixed64"))); - Assert.assertEquals(411F , message.getField(f("default_float" ))); - Assert.assertEquals(412D , message.getField(f("default_double" ))); - Assert.assertEquals(false, message.getField(f("default_bool" ))); - Assert.assertEquals("415", message.getField(f("default_string" ))); + Assert.assertEquals(401, message.getField(f("default_int32"))); + Assert.assertEquals(402L, message.getField(f("default_int64"))); + Assert.assertEquals(403, message.getField(f("default_uint32"))); + Assert.assertEquals(404L, message.getField(f("default_uint64"))); + Assert.assertEquals(405, message.getField(f("default_sint32"))); + Assert.assertEquals(406L, message.getField(f("default_sint64"))); + Assert.assertEquals(407, message.getField(f("default_fixed32"))); + Assert.assertEquals(408L, message.getField(f("default_fixed64"))); + Assert.assertEquals(409, message.getField(f("default_sfixed32"))); + Assert.assertEquals(410L, message.getField(f("default_sfixed64"))); + Assert.assertEquals(411F, message.getField(f("default_float"))); + Assert.assertEquals(412D, message.getField(f("default_double"))); + Assert.assertEquals(false, message.getField(f("default_bool"))); + Assert.assertEquals("415", message.getField(f("default_string"))); Assert.assertEquals(toBytes("416"), message.getField(f("default_bytes"))); - Assert.assertEquals( nestedFoo, message.getField(f("default_nested_enum" ))); + Assert.assertEquals(nestedFoo, message.getField(f("default_nested_enum"))); Assert.assertEquals(foreignFoo, message.getField(f("default_foreign_enum"))); - Assert.assertEquals( importFoo, message.getField(f("default_import_enum" ))); + Assert.assertEquals(importFoo, message.getField(f("default_import_enum"))); Assert.assertEquals("424", message.getField(f("default_string_piece"))); Assert.assertEquals("425", message.getField(f("default_cord"))); @@ -3289,9 +3274,9 @@ public final class TestUtil { Assert.assertTrue(message.hasField(f("oneof_nested_message"))); Assert.assertTrue(message.hasField(f("oneof_string"))); Assert.assertEquals(601, message.getField(f("oneof_uint32"))); - Assert.assertEquals(602, - ((MessageOrBuilder) message.getField(f("oneof_nested_message"))) - .getField(nestedB)); + Assert.assertEquals( + 602, + ((MessageOrBuilder) message.getField(f("oneof_nested_message"))).getField(nestedB)); Assert.assertEquals("603", message.getField(f("oneof_string"))); } } @@ -3299,175 +3284,163 @@ public final class TestUtil { // ------------------------------------------------------------------- /** - * Assert (using {@code junit.framework.Assert}} that all fields of - * {@code message} are cleared, and that getting the fields returns their - * default values, using the {@link Message} reflection interface. + * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are cleared, + * and that getting the fields returns their default values, using the {@link Message} + * reflection interface. */ public void assertClearViaReflection(MessageOrBuilder message) { // has_blah() should initially be false for all optional fields. - Assert.assertFalse(message.hasField(f("optional_int32" ))); - Assert.assertFalse(message.hasField(f("optional_int64" ))); - Assert.assertFalse(message.hasField(f("optional_uint32" ))); - Assert.assertFalse(message.hasField(f("optional_uint64" ))); - Assert.assertFalse(message.hasField(f("optional_sint32" ))); - Assert.assertFalse(message.hasField(f("optional_sint64" ))); - Assert.assertFalse(message.hasField(f("optional_fixed32" ))); - Assert.assertFalse(message.hasField(f("optional_fixed64" ))); + Assert.assertFalse(message.hasField(f("optional_int32"))); + Assert.assertFalse(message.hasField(f("optional_int64"))); + Assert.assertFalse(message.hasField(f("optional_uint32"))); + Assert.assertFalse(message.hasField(f("optional_uint64"))); + Assert.assertFalse(message.hasField(f("optional_sint32"))); + Assert.assertFalse(message.hasField(f("optional_sint64"))); + Assert.assertFalse(message.hasField(f("optional_fixed32"))); + Assert.assertFalse(message.hasField(f("optional_fixed64"))); Assert.assertFalse(message.hasField(f("optional_sfixed32"))); Assert.assertFalse(message.hasField(f("optional_sfixed64"))); - Assert.assertFalse(message.hasField(f("optional_float" ))); - Assert.assertFalse(message.hasField(f("optional_double" ))); - Assert.assertFalse(message.hasField(f("optional_bool" ))); - Assert.assertFalse(message.hasField(f("optional_string" ))); - Assert.assertFalse(message.hasField(f("optional_bytes" ))); - - Assert.assertFalse(message.hasField(f("optionalgroup" ))); - Assert.assertFalse(message.hasField(f("optional_nested_message" ))); + Assert.assertFalse(message.hasField(f("optional_float"))); + Assert.assertFalse(message.hasField(f("optional_double"))); + Assert.assertFalse(message.hasField(f("optional_bool"))); + Assert.assertFalse(message.hasField(f("optional_string"))); + Assert.assertFalse(message.hasField(f("optional_bytes"))); + + Assert.assertFalse(message.hasField(f("optionalgroup"))); + Assert.assertFalse(message.hasField(f("optional_nested_message"))); Assert.assertFalse(message.hasField(f("optional_foreign_message"))); - Assert.assertFalse(message.hasField(f("optional_import_message" ))); + Assert.assertFalse(message.hasField(f("optional_import_message"))); - Assert.assertFalse(message.hasField(f("optional_nested_enum" ))); + Assert.assertFalse(message.hasField(f("optional_nested_enum"))); Assert.assertFalse(message.hasField(f("optional_foreign_enum"))); - Assert.assertFalse(message.hasField(f("optional_import_enum" ))); + Assert.assertFalse(message.hasField(f("optional_import_enum"))); Assert.assertFalse(message.hasField(f("optional_string_piece"))); Assert.assertFalse(message.hasField(f("optional_cord"))); // Optional fields without defaults are set to zero or something like it. - Assert.assertEquals(0 , message.getField(f("optional_int32" ))); - Assert.assertEquals(0L , message.getField(f("optional_int64" ))); - Assert.assertEquals(0 , message.getField(f("optional_uint32" ))); - Assert.assertEquals(0L , message.getField(f("optional_uint64" ))); - Assert.assertEquals(0 , message.getField(f("optional_sint32" ))); - Assert.assertEquals(0L , message.getField(f("optional_sint64" ))); - Assert.assertEquals(0 , message.getField(f("optional_fixed32" ))); - Assert.assertEquals(0L , message.getField(f("optional_fixed64" ))); - Assert.assertEquals(0 , message.getField(f("optional_sfixed32"))); - Assert.assertEquals(0L , message.getField(f("optional_sfixed64"))); - Assert.assertEquals(0F , message.getField(f("optional_float" ))); - Assert.assertEquals(0D , message.getField(f("optional_double" ))); - Assert.assertEquals(false, message.getField(f("optional_bool" ))); - Assert.assertEquals("" , message.getField(f("optional_string" ))); + Assert.assertEquals(0, message.getField(f("optional_int32"))); + Assert.assertEquals(0L, message.getField(f("optional_int64"))); + Assert.assertEquals(0, message.getField(f("optional_uint32"))); + Assert.assertEquals(0L, message.getField(f("optional_uint64"))); + Assert.assertEquals(0, message.getField(f("optional_sint32"))); + Assert.assertEquals(0L, message.getField(f("optional_sint64"))); + Assert.assertEquals(0, message.getField(f("optional_fixed32"))); + Assert.assertEquals(0L, message.getField(f("optional_fixed64"))); + Assert.assertEquals(0, message.getField(f("optional_sfixed32"))); + Assert.assertEquals(0L, message.getField(f("optional_sfixed64"))); + Assert.assertEquals(0F, message.getField(f("optional_float"))); + Assert.assertEquals(0D, message.getField(f("optional_double"))); + Assert.assertEquals(false, message.getField(f("optional_bool"))); + Assert.assertEquals("", message.getField(f("optional_string"))); Assert.assertEquals(ByteString.EMPTY, message.getField(f("optional_bytes"))); // Embedded messages should also be clear. + Assert.assertFalse(((Message) message.getField(f("optionalgroup"))).hasField(groupA)); Assert.assertFalse( - ((Message)message.getField(f("optionalgroup"))).hasField(groupA)); + ((Message) message.getField(f("optional_nested_message"))).hasField(nestedB)); Assert.assertFalse( - ((Message)message.getField(f("optional_nested_message"))) - .hasField(nestedB)); + ((Message) message.getField(f("optional_foreign_message"))).hasField(foreignC)); Assert.assertFalse( - ((Message)message.getField(f("optional_foreign_message"))) - .hasField(foreignC)); + ((Message) message.getField(f("optional_import_message"))).hasField(importD)); Assert.assertFalse( - ((Message)message.getField(f("optional_import_message"))) - .hasField(importD)); + ((Message) message.getField(f("optional_public_import_message"))).hasField(importE)); Assert.assertFalse( - ((Message)message.getField(f("optional_public_import_message"))) - .hasField(importE)); - Assert.assertFalse( - ((Message)message.getField(f("optional_lazy_message"))) - .hasField(nestedB)); - - Assert.assertEquals(0, - ((Message)message.getField(f("optionalgroup"))).getField(groupA)); - Assert.assertEquals(0, - ((Message)message.getField(f("optional_nested_message"))) - .getField(nestedB)); - Assert.assertEquals(0, - ((Message)message.getField(f("optional_foreign_message"))) - .getField(foreignC)); - Assert.assertEquals(0, - ((Message)message.getField(f("optional_import_message"))) - .getField(importD)); - Assert.assertEquals(0, - ((Message)message.getField(f("optional_public_import_message"))) - .getField(importE)); - Assert.assertEquals(0, - ((Message)message.getField(f("optional_lazy_message"))) - .getField(nestedB)); + ((Message) message.getField(f("optional_lazy_message"))).hasField(nestedB)); + + Assert.assertEquals(0, ((Message) message.getField(f("optionalgroup"))).getField(groupA)); + Assert.assertEquals( + 0, ((Message) message.getField(f("optional_nested_message"))).getField(nestedB)); + Assert.assertEquals( + 0, ((Message) message.getField(f("optional_foreign_message"))).getField(foreignC)); + Assert.assertEquals( + 0, ((Message) message.getField(f("optional_import_message"))).getField(importD)); + Assert.assertEquals( + 0, ((Message) message.getField(f("optional_public_import_message"))).getField(importE)); + Assert.assertEquals( + 0, ((Message) message.getField(f("optional_lazy_message"))).getField(nestedB)); // Enums without defaults are set to the first value in the enum. - Assert.assertEquals( nestedFoo, message.getField(f("optional_nested_enum" ))); + Assert.assertEquals(nestedFoo, message.getField(f("optional_nested_enum"))); Assert.assertEquals(foreignFoo, message.getField(f("optional_foreign_enum"))); - Assert.assertEquals( importFoo, message.getField(f("optional_import_enum" ))); + Assert.assertEquals(importFoo, message.getField(f("optional_import_enum"))); Assert.assertEquals("", message.getField(f("optional_string_piece"))); Assert.assertEquals("", message.getField(f("optional_cord"))); // Repeated fields are empty. - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_int32" ))); - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_int64" ))); - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_uint32" ))); - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_uint64" ))); - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sint32" ))); - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sint64" ))); - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_fixed32" ))); - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_fixed64" ))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_int32"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_int64"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_uint32"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_uint64"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sint32"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sint64"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_fixed32"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_fixed64"))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sfixed32"))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sfixed64"))); - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_float" ))); - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_double" ))); - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_bool" ))); - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_string" ))); - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_bytes" ))); - - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeatedgroup" ))); - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_nested_message" ))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_float"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_double"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_bool"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_string"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_bytes"))); + + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeatedgroup"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_nested_message"))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_foreign_message"))); - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_import_message" ))); - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_lazy_message" ))); - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_nested_enum" ))); - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_foreign_enum" ))); - Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_import_enum" ))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_import_message"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_lazy_message"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_nested_enum"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_foreign_enum"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_import_enum"))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_string_piece"))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_cord"))); // has_blah() should also be false for all default fields. - Assert.assertFalse(message.hasField(f("default_int32" ))); - Assert.assertFalse(message.hasField(f("default_int64" ))); - Assert.assertFalse(message.hasField(f("default_uint32" ))); - Assert.assertFalse(message.hasField(f("default_uint64" ))); - Assert.assertFalse(message.hasField(f("default_sint32" ))); - Assert.assertFalse(message.hasField(f("default_sint64" ))); - Assert.assertFalse(message.hasField(f("default_fixed32" ))); - Assert.assertFalse(message.hasField(f("default_fixed64" ))); + Assert.assertFalse(message.hasField(f("default_int32"))); + Assert.assertFalse(message.hasField(f("default_int64"))); + Assert.assertFalse(message.hasField(f("default_uint32"))); + Assert.assertFalse(message.hasField(f("default_uint64"))); + Assert.assertFalse(message.hasField(f("default_sint32"))); + Assert.assertFalse(message.hasField(f("default_sint64"))); + Assert.assertFalse(message.hasField(f("default_fixed32"))); + Assert.assertFalse(message.hasField(f("default_fixed64"))); Assert.assertFalse(message.hasField(f("default_sfixed32"))); Assert.assertFalse(message.hasField(f("default_sfixed64"))); - Assert.assertFalse(message.hasField(f("default_float" ))); - Assert.assertFalse(message.hasField(f("default_double" ))); - Assert.assertFalse(message.hasField(f("default_bool" ))); - Assert.assertFalse(message.hasField(f("default_string" ))); - Assert.assertFalse(message.hasField(f("default_bytes" ))); + Assert.assertFalse(message.hasField(f("default_float"))); + Assert.assertFalse(message.hasField(f("default_double"))); + Assert.assertFalse(message.hasField(f("default_bool"))); + Assert.assertFalse(message.hasField(f("default_string"))); + Assert.assertFalse(message.hasField(f("default_bytes"))); - Assert.assertFalse(message.hasField(f("default_nested_enum" ))); + Assert.assertFalse(message.hasField(f("default_nested_enum"))); Assert.assertFalse(message.hasField(f("default_foreign_enum"))); - Assert.assertFalse(message.hasField(f("default_import_enum" ))); + Assert.assertFalse(message.hasField(f("default_import_enum"))); - Assert.assertFalse(message.hasField(f("default_string_piece" ))); - Assert.assertFalse(message.hasField(f("default_cord" ))); + Assert.assertFalse(message.hasField(f("default_string_piece"))); + Assert.assertFalse(message.hasField(f("default_cord"))); // Fields with defaults have their default values (duh). - Assert.assertEquals( 41 , message.getField(f("default_int32" ))); - Assert.assertEquals( 42L , message.getField(f("default_int64" ))); - Assert.assertEquals( 43 , message.getField(f("default_uint32" ))); - Assert.assertEquals( 44L , message.getField(f("default_uint64" ))); - Assert.assertEquals(-45 , message.getField(f("default_sint32" ))); - Assert.assertEquals( 46L , message.getField(f("default_sint64" ))); - Assert.assertEquals( 47 , message.getField(f("default_fixed32" ))); - Assert.assertEquals( 48L , message.getField(f("default_fixed64" ))); - Assert.assertEquals( 49 , message.getField(f("default_sfixed32"))); - Assert.assertEquals(-50L , message.getField(f("default_sfixed64"))); - Assert.assertEquals( 51.5F , message.getField(f("default_float" ))); - Assert.assertEquals( 52e3D , message.getField(f("default_double" ))); - Assert.assertEquals(true , message.getField(f("default_bool" ))); - Assert.assertEquals("hello", message.getField(f("default_string" ))); + Assert.assertEquals(41, message.getField(f("default_int32"))); + Assert.assertEquals(42L, message.getField(f("default_int64"))); + Assert.assertEquals(43, message.getField(f("default_uint32"))); + Assert.assertEquals(44L, message.getField(f("default_uint64"))); + Assert.assertEquals(-45, message.getField(f("default_sint32"))); + Assert.assertEquals(46L, message.getField(f("default_sint64"))); + Assert.assertEquals(47, message.getField(f("default_fixed32"))); + Assert.assertEquals(48L, message.getField(f("default_fixed64"))); + Assert.assertEquals(49, message.getField(f("default_sfixed32"))); + Assert.assertEquals(-50L, message.getField(f("default_sfixed64"))); + Assert.assertEquals(51.5F, message.getField(f("default_float"))); + Assert.assertEquals(52e3D, message.getField(f("default_double"))); + Assert.assertEquals(true, message.getField(f("default_bool"))); + Assert.assertEquals("hello", message.getField(f("default_string"))); Assert.assertEquals(toBytes("world"), message.getField(f("default_bytes"))); - Assert.assertEquals( nestedBar, message.getField(f("default_nested_enum" ))); + Assert.assertEquals(nestedBar, message.getField(f("default_nested_enum"))); Assert.assertEquals(foreignBar, message.getField(f("default_foreign_enum"))); - Assert.assertEquals( importBar, message.getField(f("default_import_enum" ))); + Assert.assertEquals(importBar, message.getField(f("default_import_enum"))); Assert.assertEquals("abc", message.getField(f("default_string_piece"))); Assert.assertEquals("123", message.getField(f("default_cord"))); @@ -3482,205 +3455,204 @@ public final class TestUtil { Assert.assertEquals(toBytes(""), message.getField(f("oneof_bytes"))); } - // --------------------------------------------------------------- - public void assertRepeatedFieldsModifiedViaReflection( - MessageOrBuilder message) { + public void assertRepeatedFieldsModifiedViaReflection(MessageOrBuilder message) { // ModifyRepeatedFields only sets the second repeated element of each // field. In addition to verifying this, we also verify that the first // element and size were *not* modified. - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int32" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int64" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint32" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint64" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint32" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint64" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed32" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed64" ))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed64"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed32"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed64"))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_float" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_double" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bool" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bytes" ))); - - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeatedgroup" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_message" ))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_float"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_double"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bool"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bytes"))); + + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeatedgroup"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_message"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_message"))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_message" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_lazy_message" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_enum" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_enum" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_enum" ))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_message"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_lazy_message"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_enum"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_enum"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_enum"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string_piece"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_cord"))); - Assert.assertEquals(201 , message.getRepeatedField(f("repeated_int32" ), 0)); - Assert.assertEquals(202L , message.getRepeatedField(f("repeated_int64" ), 0)); - Assert.assertEquals(203 , message.getRepeatedField(f("repeated_uint32" ), 0)); - Assert.assertEquals(204L , message.getRepeatedField(f("repeated_uint64" ), 0)); - Assert.assertEquals(205 , message.getRepeatedField(f("repeated_sint32" ), 0)); - Assert.assertEquals(206L , message.getRepeatedField(f("repeated_sint64" ), 0)); - Assert.assertEquals(207 , message.getRepeatedField(f("repeated_fixed32" ), 0)); - Assert.assertEquals(208L , message.getRepeatedField(f("repeated_fixed64" ), 0)); - Assert.assertEquals(209 , message.getRepeatedField(f("repeated_sfixed32"), 0)); - Assert.assertEquals(210L , message.getRepeatedField(f("repeated_sfixed64"), 0)); - Assert.assertEquals(211F , message.getRepeatedField(f("repeated_float" ), 0)); - Assert.assertEquals(212D , message.getRepeatedField(f("repeated_double" ), 0)); - Assert.assertEquals(true , message.getRepeatedField(f("repeated_bool" ), 0)); - Assert.assertEquals("215", message.getRepeatedField(f("repeated_string" ), 0)); + Assert.assertEquals(201, message.getRepeatedField(f("repeated_int32"), 0)); + Assert.assertEquals(202L, message.getRepeatedField(f("repeated_int64"), 0)); + Assert.assertEquals(203, message.getRepeatedField(f("repeated_uint32"), 0)); + Assert.assertEquals(204L, message.getRepeatedField(f("repeated_uint64"), 0)); + Assert.assertEquals(205, message.getRepeatedField(f("repeated_sint32"), 0)); + Assert.assertEquals(206L, message.getRepeatedField(f("repeated_sint64"), 0)); + Assert.assertEquals(207, message.getRepeatedField(f("repeated_fixed32"), 0)); + Assert.assertEquals(208L, message.getRepeatedField(f("repeated_fixed64"), 0)); + Assert.assertEquals(209, message.getRepeatedField(f("repeated_sfixed32"), 0)); + Assert.assertEquals(210L, message.getRepeatedField(f("repeated_sfixed64"), 0)); + Assert.assertEquals(211F, message.getRepeatedField(f("repeated_float"), 0)); + Assert.assertEquals(212D, message.getRepeatedField(f("repeated_double"), 0)); + Assert.assertEquals(true, message.getRepeatedField(f("repeated_bool"), 0)); + Assert.assertEquals("215", message.getRepeatedField(f("repeated_string"), 0)); Assert.assertEquals(toBytes("216"), message.getRepeatedField(f("repeated_bytes"), 0)); - Assert.assertEquals(217, - ((Message)message.getRepeatedField(f("repeatedgroup"), 0)) - .getField(repeatedGroupA)); - Assert.assertEquals(218, - ((Message)message.getRepeatedField(f("repeated_nested_message"), 0)) - .getField(nestedB)); - Assert.assertEquals(219, - ((Message)message.getRepeatedField(f("repeated_foreign_message"), 0)) - .getField(foreignC)); - Assert.assertEquals(220, - ((Message)message.getRepeatedField(f("repeated_import_message"), 0)) - .getField(importD)); - Assert.assertEquals(227, - ((Message)message.getRepeatedField(f("repeated_lazy_message"), 0)) - .getField(nestedB)); - - Assert.assertEquals( nestedBar, message.getRepeatedField(f("repeated_nested_enum" ),0)); - Assert.assertEquals(foreignBar, message.getRepeatedField(f("repeated_foreign_enum"),0)); - Assert.assertEquals( importBar, message.getRepeatedField(f("repeated_import_enum" ),0)); + Assert.assertEquals( + 217, + ((Message) message.getRepeatedField(f("repeatedgroup"), 0)).getField(repeatedGroupA)); + Assert.assertEquals( + 218, + ((Message) message.getRepeatedField(f("repeated_nested_message"), 0)).getField(nestedB)); + Assert.assertEquals( + 219, + ((Message) message.getRepeatedField(f("repeated_foreign_message"), 0)) + .getField(foreignC)); + Assert.assertEquals( + 220, + ((Message) message.getRepeatedField(f("repeated_import_message"), 0)).getField(importD)); + Assert.assertEquals( + 227, + ((Message) message.getRepeatedField(f("repeated_lazy_message"), 0)).getField(nestedB)); + + Assert.assertEquals(nestedBar, message.getRepeatedField(f("repeated_nested_enum"), 0)); + Assert.assertEquals(foreignBar, message.getRepeatedField(f("repeated_foreign_enum"), 0)); + Assert.assertEquals(importBar, message.getRepeatedField(f("repeated_import_enum"), 0)); Assert.assertEquals("224", message.getRepeatedField(f("repeated_string_piece"), 0)); Assert.assertEquals("225", message.getRepeatedField(f("repeated_cord"), 0)); - Assert.assertEquals(501 , message.getRepeatedField(f("repeated_int32" ), 1)); - Assert.assertEquals(502L , message.getRepeatedField(f("repeated_int64" ), 1)); - Assert.assertEquals(503 , message.getRepeatedField(f("repeated_uint32" ), 1)); - Assert.assertEquals(504L , message.getRepeatedField(f("repeated_uint64" ), 1)); - Assert.assertEquals(505 , message.getRepeatedField(f("repeated_sint32" ), 1)); - Assert.assertEquals(506L , message.getRepeatedField(f("repeated_sint64" ), 1)); - Assert.assertEquals(507 , message.getRepeatedField(f("repeated_fixed32" ), 1)); - Assert.assertEquals(508L , message.getRepeatedField(f("repeated_fixed64" ), 1)); - Assert.assertEquals(509 , message.getRepeatedField(f("repeated_sfixed32"), 1)); - Assert.assertEquals(510L , message.getRepeatedField(f("repeated_sfixed64"), 1)); - Assert.assertEquals(511F , message.getRepeatedField(f("repeated_float" ), 1)); - Assert.assertEquals(512D , message.getRepeatedField(f("repeated_double" ), 1)); - Assert.assertEquals(true , message.getRepeatedField(f("repeated_bool" ), 1)); - Assert.assertEquals("515", message.getRepeatedField(f("repeated_string" ), 1)); + Assert.assertEquals(501, message.getRepeatedField(f("repeated_int32"), 1)); + Assert.assertEquals(502L, message.getRepeatedField(f("repeated_int64"), 1)); + Assert.assertEquals(503, message.getRepeatedField(f("repeated_uint32"), 1)); + Assert.assertEquals(504L, message.getRepeatedField(f("repeated_uint64"), 1)); + Assert.assertEquals(505, message.getRepeatedField(f("repeated_sint32"), 1)); + Assert.assertEquals(506L, message.getRepeatedField(f("repeated_sint64"), 1)); + Assert.assertEquals(507, message.getRepeatedField(f("repeated_fixed32"), 1)); + Assert.assertEquals(508L, message.getRepeatedField(f("repeated_fixed64"), 1)); + Assert.assertEquals(509, message.getRepeatedField(f("repeated_sfixed32"), 1)); + Assert.assertEquals(510L, message.getRepeatedField(f("repeated_sfixed64"), 1)); + Assert.assertEquals(511F, message.getRepeatedField(f("repeated_float"), 1)); + Assert.assertEquals(512D, message.getRepeatedField(f("repeated_double"), 1)); + Assert.assertEquals(true, message.getRepeatedField(f("repeated_bool"), 1)); + Assert.assertEquals("515", message.getRepeatedField(f("repeated_string"), 1)); Assert.assertEquals(toBytes("516"), message.getRepeatedField(f("repeated_bytes"), 1)); - Assert.assertEquals(517, - ((Message)message.getRepeatedField(f("repeatedgroup"), 1)) - .getField(repeatedGroupA)); - Assert.assertEquals(518, - ((Message)message.getRepeatedField(f("repeated_nested_message"), 1)) - .getField(nestedB)); - Assert.assertEquals(519, - ((Message)message.getRepeatedField(f("repeated_foreign_message"), 1)) - .getField(foreignC)); - Assert.assertEquals(520, - ((Message)message.getRepeatedField(f("repeated_import_message"), 1)) - .getField(importD)); - Assert.assertEquals(527, - ((Message)message.getRepeatedField(f("repeated_lazy_message"), 1)) - .getField(nestedB)); - - Assert.assertEquals( nestedFoo, message.getRepeatedField(f("repeated_nested_enum" ),1)); - Assert.assertEquals(foreignFoo, message.getRepeatedField(f("repeated_foreign_enum"),1)); - Assert.assertEquals( importFoo, message.getRepeatedField(f("repeated_import_enum" ),1)); + Assert.assertEquals( + 517, + ((Message) message.getRepeatedField(f("repeatedgroup"), 1)).getField(repeatedGroupA)); + Assert.assertEquals( + 518, + ((Message) message.getRepeatedField(f("repeated_nested_message"), 1)).getField(nestedB)); + Assert.assertEquals( + 519, + ((Message) message.getRepeatedField(f("repeated_foreign_message"), 1)) + .getField(foreignC)); + Assert.assertEquals( + 520, + ((Message) message.getRepeatedField(f("repeated_import_message"), 1)).getField(importD)); + Assert.assertEquals( + 527, + ((Message) message.getRepeatedField(f("repeated_lazy_message"), 1)).getField(nestedB)); + + Assert.assertEquals(nestedFoo, message.getRepeatedField(f("repeated_nested_enum"), 1)); + Assert.assertEquals(foreignFoo, message.getRepeatedField(f("repeated_foreign_enum"), 1)); + Assert.assertEquals(importFoo, message.getRepeatedField(f("repeated_import_enum"), 1)); Assert.assertEquals("524", message.getRepeatedField(f("repeated_string_piece"), 1)); Assert.assertEquals("525", message.getRepeatedField(f("repeated_cord"), 1)); } public void setPackedFieldsViaReflection(Message.Builder message) { - message.addRepeatedField(f("packed_int32" ), 601 ); - message.addRepeatedField(f("packed_int64" ), 602L); - message.addRepeatedField(f("packed_uint32" ), 603 ); - message.addRepeatedField(f("packed_uint64" ), 604L); - message.addRepeatedField(f("packed_sint32" ), 605 ); - message.addRepeatedField(f("packed_sint64" ), 606L); - message.addRepeatedField(f("packed_fixed32" ), 607 ); - message.addRepeatedField(f("packed_fixed64" ), 608L); - message.addRepeatedField(f("packed_sfixed32"), 609 ); + message.addRepeatedField(f("packed_int32"), 601); + message.addRepeatedField(f("packed_int64"), 602L); + message.addRepeatedField(f("packed_uint32"), 603); + message.addRepeatedField(f("packed_uint64"), 604L); + message.addRepeatedField(f("packed_sint32"), 605); + message.addRepeatedField(f("packed_sint64"), 606L); + message.addRepeatedField(f("packed_fixed32"), 607); + message.addRepeatedField(f("packed_fixed64"), 608L); + message.addRepeatedField(f("packed_sfixed32"), 609); message.addRepeatedField(f("packed_sfixed64"), 610L); - message.addRepeatedField(f("packed_float" ), 611F); - message.addRepeatedField(f("packed_double" ), 612D); - message.addRepeatedField(f("packed_bool" ), true); - message.addRepeatedField(f("packed_enum" ), foreignBar); + message.addRepeatedField(f("packed_float"), 611F); + message.addRepeatedField(f("packed_double"), 612D); + message.addRepeatedField(f("packed_bool"), true); + message.addRepeatedField(f("packed_enum"), foreignBar); // Add a second one of each field. - message.addRepeatedField(f("packed_int32" ), 701 ); - message.addRepeatedField(f("packed_int64" ), 702L); - message.addRepeatedField(f("packed_uint32" ), 703 ); - message.addRepeatedField(f("packed_uint64" ), 704L); - message.addRepeatedField(f("packed_sint32" ), 705 ); - message.addRepeatedField(f("packed_sint64" ), 706L); - message.addRepeatedField(f("packed_fixed32" ), 707 ); - message.addRepeatedField(f("packed_fixed64" ), 708L); - message.addRepeatedField(f("packed_sfixed32"), 709 ); + message.addRepeatedField(f("packed_int32"), 701); + message.addRepeatedField(f("packed_int64"), 702L); + message.addRepeatedField(f("packed_uint32"), 703); + message.addRepeatedField(f("packed_uint64"), 704L); + message.addRepeatedField(f("packed_sint32"), 705); + message.addRepeatedField(f("packed_sint64"), 706L); + message.addRepeatedField(f("packed_fixed32"), 707); + message.addRepeatedField(f("packed_fixed64"), 708L); + message.addRepeatedField(f("packed_sfixed32"), 709); message.addRepeatedField(f("packed_sfixed64"), 710L); - message.addRepeatedField(f("packed_float" ), 711F); - message.addRepeatedField(f("packed_double" ), 712D); - message.addRepeatedField(f("packed_bool" ), false); - message.addRepeatedField(f("packed_enum" ), foreignBaz); + message.addRepeatedField(f("packed_float"), 711F); + message.addRepeatedField(f("packed_double"), 712D); + message.addRepeatedField(f("packed_bool"), false); + message.addRepeatedField(f("packed_enum"), foreignBaz); } public void assertPackedFieldsSetViaReflection(MessageOrBuilder message) { - Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_int32" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_int64" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_uint32" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_uint64" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sint32" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sint64" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_fixed32" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_fixed64" ))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_int32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_int64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_uint32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_uint64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sint32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sint64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_fixed32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_fixed64"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sfixed32"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sfixed64"))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_float" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_double" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_bool" ))); - Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_enum" ))); - Assert.assertEquals(601 , message.getRepeatedField(f("packed_int32" ), 0)); - Assert.assertEquals(602L , message.getRepeatedField(f("packed_int64" ), 0)); - Assert.assertEquals(603 , message.getRepeatedField(f("packed_uint32" ), 0)); - Assert.assertEquals(604L , message.getRepeatedField(f("packed_uint64" ), 0)); - Assert.assertEquals(605 , message.getRepeatedField(f("packed_sint32" ), 0)); - Assert.assertEquals(606L , message.getRepeatedField(f("packed_sint64" ), 0)); - Assert.assertEquals(607 , message.getRepeatedField(f("packed_fixed32" ), 0)); - Assert.assertEquals(608L , message.getRepeatedField(f("packed_fixed64" ), 0)); - Assert.assertEquals(609 , message.getRepeatedField(f("packed_sfixed32"), 0)); - Assert.assertEquals(610L , message.getRepeatedField(f("packed_sfixed64"), 0)); - Assert.assertEquals(611F , message.getRepeatedField(f("packed_float" ), 0)); - Assert.assertEquals(612D , message.getRepeatedField(f("packed_double" ), 0)); - Assert.assertEquals(true , message.getRepeatedField(f("packed_bool" ), 0)); - Assert.assertEquals(foreignBar, message.getRepeatedField(f("packed_enum" ),0)); - Assert.assertEquals(701 , message.getRepeatedField(f("packed_int32" ), 1)); - Assert.assertEquals(702L , message.getRepeatedField(f("packed_int64" ), 1)); - Assert.assertEquals(703 , message.getRepeatedField(f("packed_uint32" ), 1)); - Assert.assertEquals(704L , message.getRepeatedField(f("packed_uint64" ), 1)); - Assert.assertEquals(705 , message.getRepeatedField(f("packed_sint32" ), 1)); - Assert.assertEquals(706L , message.getRepeatedField(f("packed_sint64" ), 1)); - Assert.assertEquals(707 , message.getRepeatedField(f("packed_fixed32" ), 1)); - Assert.assertEquals(708L , message.getRepeatedField(f("packed_fixed64" ), 1)); - Assert.assertEquals(709 , message.getRepeatedField(f("packed_sfixed32"), 1)); - Assert.assertEquals(710L , message.getRepeatedField(f("packed_sfixed64"), 1)); - Assert.assertEquals(711F , message.getRepeatedField(f("packed_float" ), 1)); - Assert.assertEquals(712D , message.getRepeatedField(f("packed_double" ), 1)); - Assert.assertEquals(false, message.getRepeatedField(f("packed_bool" ), 1)); - Assert.assertEquals(foreignBaz, message.getRepeatedField(f("packed_enum" ),1)); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_float"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_double"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_bool"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_enum"))); + Assert.assertEquals(601, message.getRepeatedField(f("packed_int32"), 0)); + Assert.assertEquals(602L, message.getRepeatedField(f("packed_int64"), 0)); + Assert.assertEquals(603, message.getRepeatedField(f("packed_uint32"), 0)); + Assert.assertEquals(604L, message.getRepeatedField(f("packed_uint64"), 0)); + Assert.assertEquals(605, message.getRepeatedField(f("packed_sint32"), 0)); + Assert.assertEquals(606L, message.getRepeatedField(f("packed_sint64"), 0)); + Assert.assertEquals(607, message.getRepeatedField(f("packed_fixed32"), 0)); + Assert.assertEquals(608L, message.getRepeatedField(f("packed_fixed64"), 0)); + Assert.assertEquals(609, message.getRepeatedField(f("packed_sfixed32"), 0)); + Assert.assertEquals(610L, message.getRepeatedField(f("packed_sfixed64"), 0)); + Assert.assertEquals(611F, message.getRepeatedField(f("packed_float"), 0)); + Assert.assertEquals(612D, message.getRepeatedField(f("packed_double"), 0)); + Assert.assertEquals(true, message.getRepeatedField(f("packed_bool"), 0)); + Assert.assertEquals(foreignBar, message.getRepeatedField(f("packed_enum"), 0)); + Assert.assertEquals(701, message.getRepeatedField(f("packed_int32"), 1)); + Assert.assertEquals(702L, message.getRepeatedField(f("packed_int64"), 1)); + Assert.assertEquals(703, message.getRepeatedField(f("packed_uint32"), 1)); + Assert.assertEquals(704L, message.getRepeatedField(f("packed_uint64"), 1)); + Assert.assertEquals(705, message.getRepeatedField(f("packed_sint32"), 1)); + Assert.assertEquals(706L, message.getRepeatedField(f("packed_sint64"), 1)); + Assert.assertEquals(707, message.getRepeatedField(f("packed_fixed32"), 1)); + Assert.assertEquals(708L, message.getRepeatedField(f("packed_fixed64"), 1)); + Assert.assertEquals(709, message.getRepeatedField(f("packed_sfixed32"), 1)); + Assert.assertEquals(710L, message.getRepeatedField(f("packed_sfixed64"), 1)); + Assert.assertEquals(711F, message.getRepeatedField(f("packed_float"), 1)); + Assert.assertEquals(712D, message.getRepeatedField(f("packed_double"), 1)); + Assert.assertEquals(false, message.getRepeatedField(f("packed_bool"), 1)); + Assert.assertEquals(foreignBaz, message.getRepeatedField(f("packed_enum"), 1)); } /** * Verifies that the reflection setters for the given.Builder object throw a - * NullPointerException if they are passed a null value. Uses Assert to throw an - * appropriate assertion failure, if the condition is not verified. + * NullPointerException if they are passed a null value. Uses Assert to throw an appropriate + * assertion failure, if the condition is not verified. */ - public void assertReflectionSettersRejectNull(Message.Builder builder) - throws Exception { + public void assertReflectionSettersRejectNull(Message.Builder builder) throws Exception { try { builder.setField(f("optional_string"), null); Assert.fail("Exception was not thrown"); @@ -3700,15 +3672,13 @@ public final class TestUtil { // We expect this exception. } try { - builder.setField(f("optional_nested_message"), - (TestAllTypes.NestedMessage) null); + builder.setField(f("optional_nested_message"), (TestAllTypes.NestedMessage) null); Assert.fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. } try { - builder.setField(f("optional_nested_message"), - (TestAllTypes.NestedMessage.Builder) null); + builder.setField(f("optional_nested_message"), (TestAllTypes.NestedMessage.Builder) null); Assert.fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. @@ -3742,7 +3712,7 @@ public final class TestUtil { /** * Verifies that the reflection repeated setters for the given Builder object throw a - * NullPointerException if they are passed a null value. Uses Assert to throw an appropriate + * NullPointerException if they are passed a null value. Uses Assert to throw an appropriate * assertion failure, if the condition is not verified. */ public void assertReflectionRepeatedSettersRejectNull(Message.Builder builder) @@ -3772,8 +3742,7 @@ public final class TestUtil { } builder.addRepeatedField( - f("repeated_nested_message"), - TestAllTypes.NestedMessage.newBuilder().setBb(218).build()); + f("repeated_nested_message"), TestAllTypes.NestedMessage.newBuilder().setBb(218).build()); try { builder.setRepeatedField(f("repeated_nested_message"), 0, null); Assert.fail("Exception was not thrown"); @@ -3783,10 +3752,7 @@ public final class TestUtil { } } - /** - * @param filePath The path relative to - * {@link #getTestDataDir}. - */ + /** @param filePath The path relative to {@link #getTestDataDir}. */ public static String readTextFromFile(String filePath) { return readBytesFromFile(filePath).toStringUtf8(); } @@ -3798,8 +3764,7 @@ public final class TestUtil { try { ancestor = ancestor.getCanonicalFile(); } catch (IOException e) { - throw new RuntimeException( - "Couldn't get canonical name of working directory.", e); + throw new RuntimeException("Couldn't get canonical name of working directory.", e); } while (ancestor != null && ancestor.exists()) { if (new File(ancestor, "src/google/protobuf").exists()) { @@ -3809,15 +3774,13 @@ public final class TestUtil { } throw new RuntimeException( - "Could not find golden files. This test must be run from within the " + - "protobuf source package so that it can read test data files from the " + - "C++ source tree: " + initialPath); + "Could not find golden files. This test must be run from within the " + + "protobuf source package so that it can read test data files from the " + + "C++ source tree: " + + initialPath); } - /** - * @param filename The path relative to - * {@link #getTestDataDir}. - */ + /** @param filename The path relative to {@link #getTestDataDir}. */ public static ByteString readBytesFromFile(String filename) { File fullPath = new File(getTestDataDir(), filename); try { @@ -3828,8 +3791,7 @@ public final class TestUtil { } catch (IOException e) { // Throw a RuntimeException here so that we can call this function from // static initializers. - throw new IllegalArgumentException( - "Couldn't read file: " + fullPath.getPath(), e); + throw new IllegalArgumentException("Couldn't read file: " + fullPath.getPath(), e); } } // END FULL-RUNTIME @@ -3844,27 +3806,26 @@ public final class TestUtil { } /** - * Get the bytes of the "golden message". This is a serialized TestAllTypes - * with all fields set as they would be by - * {@link #setAllFields(TestAllTypes.Builder)}, but it is loaded from a file - * on disk rather than generated dynamically. The file is actually generated - * by C++ code, so testing against it verifies compatibility with C++. + * Get the bytes of the "golden message". This is a serialized TestAllTypes with all fields set as + * they would be by {@link #setAllFields(TestAllTypes.Builder)}, but it is loaded from a file on + * disk rather than generated dynamically. The file is actually generated by C++ code, so testing + * against it verifies compatibility with C++. */ public static ByteString getGoldenMessage() { if (goldenMessage == null) { - goldenMessage = readBytesFromResource("/google/protobuf/testdata/golden_message_oneof_implemented"); + goldenMessage = + readBytesFromResource("/google/protobuf/testdata/golden_message_oneof_implemented"); } return goldenMessage; } + private static ByteString goldenMessage = null; /** - * Get the bytes of the "golden packed fields message". This is a serialized - * TestPackedTypes with all fields set as they would be by - * {@link #setPackedFields(TestPackedTypes.Builder)}, but it is loaded from a - * file on disk rather than generated dynamically. The file is actually - * generated by C++ code, so testing against it verifies compatibility with - * C++. + * Get the bytes of the "golden packed fields message". This is a serialized TestPackedTypes with + * all fields set as they would be by {@link #setPackedFields(TestPackedTypes.Builder)}, but it is + * loaded from a file on disk rather than generated dynamically. The file is actually generated by + * C++ code, so testing against it verifies compatibility with C++. */ public static ByteString getGoldenPackedFieldsMessage() { if (goldenPackedFieldsMessage == null) { @@ -3873,6 +3834,7 @@ public final class TestUtil { } return goldenPackedFieldsMessage; } + private static ByteString goldenPackedFieldsMessage = null; // BEGIN FULL-RUNTIME @@ -3881,8 +3843,7 @@ public final class TestUtil { * * @author jonp@google.com (Jon Perlow) */ - public static class MockBuilderParent - implements GeneratedMessage.BuilderParent { + public static class MockBuilderParent implements GeneratedMessage.BuilderParent { private int invalidations; diff --git a/java/core/src/test/java/com/google/protobuf/TestUtilLite.java b/java/core/src/test/java/com/google/protobuf/TestUtilLite.java index 8f33fa14ab..31565fc40a 100644 --- a/java/core/src/test/java/com/google/protobuf/TestUtilLite.java +++ b/java/core/src/test/java/com/google/protobuf/TestUtilLite.java @@ -30,8 +30,6 @@ package com.google.protobuf; -import static com.google.protobuf.UnittestLite.OptionalGroup_extension_lite; -import static com.google.protobuf.UnittestLite.RepeatedGroup_extension_lite; import static com.google.protobuf.UnittestLite.defaultBoolExtensionLite; import static com.google.protobuf.UnittestLite.defaultBytesExtensionLite; import static com.google.protobuf.UnittestLite.defaultCordExtensionLite; @@ -127,6 +125,8 @@ import com.google.protobuf.UnittestImportLite.ImportMessageLite; import com.google.protobuf.UnittestImportPublicLite.PublicImportMessageLite; import com.google.protobuf.UnittestLite.ForeignEnumLite; import com.google.protobuf.UnittestLite.ForeignMessageLite; +import com.google.protobuf.UnittestLite.OptionalGroup_extension_lite; +import com.google.protobuf.UnittestLite.RepeatedGroup_extension_lite; import com.google.protobuf.UnittestLite.TestAllExtensionsLite; import com.google.protobuf.UnittestLite.TestAllTypesLite; import com.google.protobuf.UnittestLite.TestPackedExtensionsLite; @@ -136,8 +136,7 @@ import com.google.protobuf.UnittestLite.TestPackedExtensionsLite; * and {@code TestPackedExtensionsLite}. This is analogous to the functionality in TestUtil.java but * does not depend on the presence of any non-lite protos. * - *

This code is not to be used outside of {@code com.google.protobuf} and - * subpackages. + *

This code is not to be used outside of {@code com.google.protobuf} and subpackages. */ public final class TestUtilLite { private TestUtilLite() {} @@ -148,8 +147,8 @@ public final class TestUtilLite { } /** - * Get a {@code TestAllTypesLite.Builder} with all fields set as they would be by - * {@link #setAllFields(TestAllTypesLite.Builder)}. + * Get a {@code TestAllTypesLite.Builder} with all fields set as they would be by {@link + * #setAllFields(TestAllTypesLite.Builder)}. */ public static TestAllTypesLite.Builder getAllLiteSetBuilder() { TestAllTypesLite.Builder builder = TestAllTypesLite.newBuilder(); @@ -158,8 +157,8 @@ public final class TestUtilLite { } /** - * Get a {@code TestAllExtensionsLite} with all fields set as they would be by - * {@link #setAllExtensions(TestAllExtensionsLite.Builder)}. + * Get a {@code TestAllExtensionsLite} with all fields set as they would be by {@link + * #setAllExtensions(TestAllExtensionsLite.Builder)}. */ public static TestAllExtensionsLite getAllLiteExtensionsSet() { TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.newBuilder(); @@ -172,154 +171,137 @@ public final class TestUtilLite { setPackedExtensions(builder); return builder.build(); } - - /** - * Set every field of {@code builder} to the values expected by - * {@code assertAllFieldsSet()}. - */ + + /** Set every field of {@code builder} to the values expected by {@code assertAllFieldsSet()}. */ public static void setAllFields(TestAllTypesLite.Builder builder) { - builder.setOptionalInt32 (101); - builder.setOptionalInt64 (102); - builder.setOptionalUint32 (103); - builder.setOptionalUint64 (104); - builder.setOptionalSint32 (105); - builder.setOptionalSint64 (106); - builder.setOptionalFixed32 (107); - builder.setOptionalFixed64 (108); + builder.setOptionalInt32(101); + builder.setOptionalInt64(102); + builder.setOptionalUint32(103); + builder.setOptionalUint64(104); + builder.setOptionalSint32(105); + builder.setOptionalSint64(106); + builder.setOptionalFixed32(107); + builder.setOptionalFixed64(108); builder.setOptionalSfixed32(109); builder.setOptionalSfixed64(110); - builder.setOptionalFloat (111); - builder.setOptionalDouble (112); - builder.setOptionalBool (true); - builder.setOptionalString ("115"); - builder.setOptionalBytes (toBytes("116")); - - builder.setOptionalGroup( - TestAllTypesLite.OptionalGroup.newBuilder().setA(117).build()); + builder.setOptionalFloat(111); + builder.setOptionalDouble(112); + builder.setOptionalBool(true); + builder.setOptionalString("115"); + builder.setOptionalBytes(toBytes("116")); + + builder.setOptionalGroup(TestAllTypesLite.OptionalGroup.newBuilder().setA(117).build()); builder.setOptionalNestedMessage( TestAllTypesLite.NestedMessage.newBuilder().setBb(118).build()); - builder.setOptionalForeignMessage( - ForeignMessageLite.newBuilder().setC(119).build()); - builder.setOptionalImportMessage( - ImportMessageLite.newBuilder().setD(120).build()); - builder.setOptionalPublicImportMessage( - PublicImportMessageLite.newBuilder().setE(126).build()); - builder.setOptionalLazyMessage( - TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build()); + builder.setOptionalForeignMessage(ForeignMessageLite.newBuilder().setC(119).build()); + builder.setOptionalImportMessage(ImportMessageLite.newBuilder().setD(120).build()); + builder.setOptionalPublicImportMessage(PublicImportMessageLite.newBuilder().setE(126).build()); + builder.setOptionalLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build()); - builder.setOptionalNestedEnum (TestAllTypesLite.NestedEnum.BAZ); + builder.setOptionalNestedEnum(TestAllTypesLite.NestedEnum.BAZ); builder.setOptionalForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAZ); - builder.setOptionalImportEnum (ImportEnumLite.IMPORT_LITE_BAZ); + builder.setOptionalImportEnum(ImportEnumLite.IMPORT_LITE_BAZ); builder.setOptionalStringPiece("124"); builder.setOptionalCord("125"); // ----------------------------------------------------------------- - builder.addRepeatedInt32 (201); - builder.addRepeatedInt64 (202); - builder.addRepeatedUint32 (203); - builder.addRepeatedUint64 (204); - builder.addRepeatedSint32 (205); - builder.addRepeatedSint64 (206); - builder.addRepeatedFixed32 (207); - builder.addRepeatedFixed64 (208); + builder.addRepeatedInt32(201); + builder.addRepeatedInt64(202); + builder.addRepeatedUint32(203); + builder.addRepeatedUint64(204); + builder.addRepeatedSint32(205); + builder.addRepeatedSint64(206); + builder.addRepeatedFixed32(207); + builder.addRepeatedFixed64(208); builder.addRepeatedSfixed32(209); builder.addRepeatedSfixed64(210); - builder.addRepeatedFloat (211); - builder.addRepeatedDouble (212); - builder.addRepeatedBool (true); - builder.addRepeatedString ("215"); - builder.addRepeatedBytes (toBytes("216")); - - builder.addRepeatedGroup( - TestAllTypesLite.RepeatedGroup.newBuilder().setA(217).build()); + builder.addRepeatedFloat(211); + builder.addRepeatedDouble(212); + builder.addRepeatedBool(true); + builder.addRepeatedString("215"); + builder.addRepeatedBytes(toBytes("216")); + + builder.addRepeatedGroup(TestAllTypesLite.RepeatedGroup.newBuilder().setA(217).build()); builder.addRepeatedNestedMessage( TestAllTypesLite.NestedMessage.newBuilder().setBb(218).build()); - builder.addRepeatedForeignMessage( - ForeignMessageLite.newBuilder().setC(219).build()); - builder.addRepeatedImportMessage( - ImportMessageLite.newBuilder().setD(220).build()); - builder.addRepeatedLazyMessage( - TestAllTypesLite.NestedMessage.newBuilder().setBb(227).build()); + builder.addRepeatedForeignMessage(ForeignMessageLite.newBuilder().setC(219).build()); + builder.addRepeatedImportMessage(ImportMessageLite.newBuilder().setD(220).build()); + builder.addRepeatedLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(227).build()); - builder.addRepeatedNestedEnum (TestAllTypesLite.NestedEnum.BAR); + builder.addRepeatedNestedEnum(TestAllTypesLite.NestedEnum.BAR); builder.addRepeatedForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR); - builder.addRepeatedImportEnum (ImportEnumLite.IMPORT_LITE_BAR); + builder.addRepeatedImportEnum(ImportEnumLite.IMPORT_LITE_BAR); builder.addRepeatedStringPiece("224"); builder.addRepeatedCord("225"); // Add a second one of each field. - builder.addRepeatedInt32 (301); - builder.addRepeatedInt64 (302); - builder.addRepeatedUint32 (303); - builder.addRepeatedUint64 (304); - builder.addRepeatedSint32 (305); - builder.addRepeatedSint64 (306); - builder.addRepeatedFixed32 (307); - builder.addRepeatedFixed64 (308); + builder.addRepeatedInt32(301); + builder.addRepeatedInt64(302); + builder.addRepeatedUint32(303); + builder.addRepeatedUint64(304); + builder.addRepeatedSint32(305); + builder.addRepeatedSint64(306); + builder.addRepeatedFixed32(307); + builder.addRepeatedFixed64(308); builder.addRepeatedSfixed32(309); builder.addRepeatedSfixed64(310); - builder.addRepeatedFloat (311); - builder.addRepeatedDouble (312); - builder.addRepeatedBool (false); - builder.addRepeatedString ("315"); - builder.addRepeatedBytes (toBytes("316")); - - builder.addRepeatedGroup( - TestAllTypesLite.RepeatedGroup.newBuilder().setA(317).build()); + builder.addRepeatedFloat(311); + builder.addRepeatedDouble(312); + builder.addRepeatedBool(false); + builder.addRepeatedString("315"); + builder.addRepeatedBytes(toBytes("316")); + + builder.addRepeatedGroup(TestAllTypesLite.RepeatedGroup.newBuilder().setA(317).build()); builder.addRepeatedNestedMessage( TestAllTypesLite.NestedMessage.newBuilder().setBb(318).build()); - builder.addRepeatedForeignMessage( - ForeignMessageLite.newBuilder().setC(319).build()); - builder.addRepeatedImportMessage( - ImportMessageLite.newBuilder().setD(320).build()); - builder.addRepeatedLazyMessage( - TestAllTypesLite.NestedMessage.newBuilder().setBb(327).build()); + builder.addRepeatedForeignMessage(ForeignMessageLite.newBuilder().setC(319).build()); + builder.addRepeatedImportMessage(ImportMessageLite.newBuilder().setD(320).build()); + builder.addRepeatedLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(327).build()); - builder.addRepeatedNestedEnum (TestAllTypesLite.NestedEnum.BAZ); + builder.addRepeatedNestedEnum(TestAllTypesLite.NestedEnum.BAZ); builder.addRepeatedForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAZ); - builder.addRepeatedImportEnum (ImportEnumLite.IMPORT_LITE_BAZ); + builder.addRepeatedImportEnum(ImportEnumLite.IMPORT_LITE_BAZ); builder.addRepeatedStringPiece("324"); builder.addRepeatedCord("325"); // ----------------------------------------------------------------- - builder.setDefaultInt32 (401); - builder.setDefaultInt64 (402); - builder.setDefaultUint32 (403); - builder.setDefaultUint64 (404); - builder.setDefaultSint32 (405); - builder.setDefaultSint64 (406); - builder.setDefaultFixed32 (407); - builder.setDefaultFixed64 (408); + builder.setDefaultInt32(401); + builder.setDefaultInt64(402); + builder.setDefaultUint32(403); + builder.setDefaultUint64(404); + builder.setDefaultSint32(405); + builder.setDefaultSint64(406); + builder.setDefaultFixed32(407); + builder.setDefaultFixed64(408); builder.setDefaultSfixed32(409); builder.setDefaultSfixed64(410); - builder.setDefaultFloat (411); - builder.setDefaultDouble (412); - builder.setDefaultBool (false); - builder.setDefaultString ("415"); - builder.setDefaultBytes (toBytes("416")); + builder.setDefaultFloat(411); + builder.setDefaultDouble(412); + builder.setDefaultBool(false); + builder.setDefaultString("415"); + builder.setDefaultBytes(toBytes("416")); - builder.setDefaultNestedEnum (TestAllTypesLite.NestedEnum.FOO); + builder.setDefaultNestedEnum(TestAllTypesLite.NestedEnum.FOO); builder.setDefaultForeignEnum(ForeignEnumLite.FOREIGN_LITE_FOO); - builder.setDefaultImportEnum (ImportEnumLite.IMPORT_LITE_FOO); + builder.setDefaultImportEnum(ImportEnumLite.IMPORT_LITE_FOO); builder.setDefaultStringPiece("424"); builder.setDefaultCord("425"); builder.setOneofUint32(601); - builder.setOneofNestedMessage( - TestAllTypesLite.NestedMessage.newBuilder().setBb(602).build()); + builder.setOneofNestedMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(602).build()); builder.setOneofString("603"); builder.setOneofBytes(toBytes("604")); } /** - * Get an unmodifiable {@link ExtensionRegistryLite} containing all the - * extensions of {@code TestAllExtensionsLite}. + * Get an unmodifiable {@link ExtensionRegistryLite} containing all the extensions of {@code + * TestAllExtensionsLite}. */ public static ExtensionRegistryLite getExtensionRegistryLite() { ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance(); @@ -328,8 +310,8 @@ public final class TestUtilLite { } /** - * Register all of {@code TestAllExtensionsLite}'s extensions with the - * given {@link ExtensionRegistryLite}. + * Register all of {@code TestAllExtensionsLite}'s extensions with the given {@link + * ExtensionRegistryLite}. */ public static void registerAllExtensionsLite(ExtensionRegistryLite registry) { UnittestLite.registerAllExtensions(registry); @@ -339,38 +321,40 @@ public final class TestUtilLite { // Lite extensions /** - * Set every field of {@code message} to the values expected by - * {@code assertAllExtensionsSet()}. + * Set every field of {@code message} to the values expected by {@code assertAllExtensionsSet()}. */ public static void setAllExtensions(TestAllExtensionsLite.Builder message) { - message.setExtension(optionalInt32ExtensionLite , 101); - message.setExtension(optionalInt64ExtensionLite , 102L); - message.setExtension(optionalUint32ExtensionLite , 103); - message.setExtension(optionalUint64ExtensionLite , 104L); - message.setExtension(optionalSint32ExtensionLite , 105); - message.setExtension(optionalSint64ExtensionLite , 106L); - message.setExtension(optionalFixed32ExtensionLite , 107); - message.setExtension(optionalFixed64ExtensionLite , 108L); + message.setExtension(optionalInt32ExtensionLite, 101); + message.setExtension(optionalInt64ExtensionLite, 102L); + message.setExtension(optionalUint32ExtensionLite, 103); + message.setExtension(optionalUint64ExtensionLite, 104L); + message.setExtension(optionalSint32ExtensionLite, 105); + message.setExtension(optionalSint64ExtensionLite, 106L); + message.setExtension(optionalFixed32ExtensionLite, 107); + message.setExtension(optionalFixed64ExtensionLite, 108L); message.setExtension(optionalSfixed32ExtensionLite, 109); message.setExtension(optionalSfixed64ExtensionLite, 110L); - message.setExtension(optionalFloatExtensionLite , 111F); - message.setExtension(optionalDoubleExtensionLite , 112D); - message.setExtension(optionalBoolExtensionLite , true); - message.setExtension(optionalStringExtensionLite , "115"); - message.setExtension(optionalBytesExtensionLite , toBytes("116")); - - message.setExtension(optionalGroupExtensionLite, - OptionalGroup_extension_lite.newBuilder().setA(117).build()); - message.setExtension(optionalNestedMessageExtensionLite, - TestAllTypesLite.NestedMessage.newBuilder().setBb(118).build()); - message.setExtension(optionalForeignMessageExtensionLite, - ForeignMessageLite.newBuilder().setC(119).build()); - message.setExtension(optionalImportMessageExtensionLite, - ImportMessageLite.newBuilder().setD(120).build()); - message.setExtension(optionalPublicImportMessageExtensionLite, - PublicImportMessageLite.newBuilder().setE(126).build()); - message.setExtension(optionalLazyMessageExtensionLite, - TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build()); + message.setExtension(optionalFloatExtensionLite, 111F); + message.setExtension(optionalDoubleExtensionLite, 112D); + message.setExtension(optionalBoolExtensionLite, true); + message.setExtension(optionalStringExtensionLite, "115"); + message.setExtension(optionalBytesExtensionLite, toBytes("116")); + + message.setExtension( + optionalGroupExtensionLite, OptionalGroup_extension_lite.newBuilder().setA(117).build()); + message.setExtension( + optionalNestedMessageExtensionLite, + TestAllTypesLite.NestedMessage.newBuilder().setBb(118).build()); + message.setExtension( + optionalForeignMessageExtensionLite, ForeignMessageLite.newBuilder().setC(119).build()); + message.setExtension( + optionalImportMessageExtensionLite, ImportMessageLite.newBuilder().setD(120).build()); + message.setExtension( + optionalPublicImportMessageExtensionLite, + PublicImportMessageLite.newBuilder().setE(126).build()); + message.setExtension( + optionalLazyMessageExtensionLite, + TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build()); message.setExtension(optionalNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ); message.setExtension(optionalForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ); @@ -381,32 +365,34 @@ public final class TestUtilLite { // ----------------------------------------------------------------- - message.addExtension(repeatedInt32ExtensionLite , 201); - message.addExtension(repeatedInt64ExtensionLite , 202L); - message.addExtension(repeatedUint32ExtensionLite , 203); - message.addExtension(repeatedUint64ExtensionLite , 204L); - message.addExtension(repeatedSint32ExtensionLite , 205); - message.addExtension(repeatedSint64ExtensionLite , 206L); - message.addExtension(repeatedFixed32ExtensionLite , 207); - message.addExtension(repeatedFixed64ExtensionLite , 208L); + message.addExtension(repeatedInt32ExtensionLite, 201); + message.addExtension(repeatedInt64ExtensionLite, 202L); + message.addExtension(repeatedUint32ExtensionLite, 203); + message.addExtension(repeatedUint64ExtensionLite, 204L); + message.addExtension(repeatedSint32ExtensionLite, 205); + message.addExtension(repeatedSint64ExtensionLite, 206L); + message.addExtension(repeatedFixed32ExtensionLite, 207); + message.addExtension(repeatedFixed64ExtensionLite, 208L); message.addExtension(repeatedSfixed32ExtensionLite, 209); message.addExtension(repeatedSfixed64ExtensionLite, 210L); - message.addExtension(repeatedFloatExtensionLite , 211F); - message.addExtension(repeatedDoubleExtensionLite , 212D); - message.addExtension(repeatedBoolExtensionLite , true); - message.addExtension(repeatedStringExtensionLite , "215"); - message.addExtension(repeatedBytesExtensionLite , toBytes("216")); - - message.addExtension(repeatedGroupExtensionLite, - RepeatedGroup_extension_lite.newBuilder().setA(217).build()); - message.addExtension(repeatedNestedMessageExtensionLite, - TestAllTypesLite.NestedMessage.newBuilder().setBb(218).build()); - message.addExtension(repeatedForeignMessageExtensionLite, - ForeignMessageLite.newBuilder().setC(219).build()); - message.addExtension(repeatedImportMessageExtensionLite, - ImportMessageLite.newBuilder().setD(220).build()); - message.addExtension(repeatedLazyMessageExtensionLite, - TestAllTypesLite.NestedMessage.newBuilder().setBb(227).build()); + message.addExtension(repeatedFloatExtensionLite, 211F); + message.addExtension(repeatedDoubleExtensionLite, 212D); + message.addExtension(repeatedBoolExtensionLite, true); + message.addExtension(repeatedStringExtensionLite, "215"); + message.addExtension(repeatedBytesExtensionLite, toBytes("216")); + + message.addExtension( + repeatedGroupExtensionLite, RepeatedGroup_extension_lite.newBuilder().setA(217).build()); + message.addExtension( + repeatedNestedMessageExtensionLite, + TestAllTypesLite.NestedMessage.newBuilder().setBb(218).build()); + message.addExtension( + repeatedForeignMessageExtensionLite, ForeignMessageLite.newBuilder().setC(219).build()); + message.addExtension( + repeatedImportMessageExtensionLite, ImportMessageLite.newBuilder().setD(220).build()); + message.addExtension( + repeatedLazyMessageExtensionLite, + TestAllTypesLite.NestedMessage.newBuilder().setBb(227).build()); message.addExtension(repeatedNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAR); message.addExtension(repeatedForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAR); @@ -416,32 +402,34 @@ public final class TestUtilLite { message.addExtension(repeatedCordExtensionLite, "225"); // Add a second one of each field. - message.addExtension(repeatedInt32ExtensionLite , 301); - message.addExtension(repeatedInt64ExtensionLite , 302L); - message.addExtension(repeatedUint32ExtensionLite , 303); - message.addExtension(repeatedUint64ExtensionLite , 304L); - message.addExtension(repeatedSint32ExtensionLite , 305); - message.addExtension(repeatedSint64ExtensionLite , 306L); - message.addExtension(repeatedFixed32ExtensionLite , 307); - message.addExtension(repeatedFixed64ExtensionLite , 308L); + message.addExtension(repeatedInt32ExtensionLite, 301); + message.addExtension(repeatedInt64ExtensionLite, 302L); + message.addExtension(repeatedUint32ExtensionLite, 303); + message.addExtension(repeatedUint64ExtensionLite, 304L); + message.addExtension(repeatedSint32ExtensionLite, 305); + message.addExtension(repeatedSint64ExtensionLite, 306L); + message.addExtension(repeatedFixed32ExtensionLite, 307); + message.addExtension(repeatedFixed64ExtensionLite, 308L); message.addExtension(repeatedSfixed32ExtensionLite, 309); message.addExtension(repeatedSfixed64ExtensionLite, 310L); - message.addExtension(repeatedFloatExtensionLite , 311F); - message.addExtension(repeatedDoubleExtensionLite , 312D); - message.addExtension(repeatedBoolExtensionLite , false); - message.addExtension(repeatedStringExtensionLite , "315"); - message.addExtension(repeatedBytesExtensionLite , toBytes("316")); - - message.addExtension(repeatedGroupExtensionLite, - RepeatedGroup_extension_lite.newBuilder().setA(317).build()); - message.addExtension(repeatedNestedMessageExtensionLite, - TestAllTypesLite.NestedMessage.newBuilder().setBb(318).build()); - message.addExtension(repeatedForeignMessageExtensionLite, - ForeignMessageLite.newBuilder().setC(319).build()); - message.addExtension(repeatedImportMessageExtensionLite, - ImportMessageLite.newBuilder().setD(320).build()); - message.addExtension(repeatedLazyMessageExtensionLite, - TestAllTypesLite.NestedMessage.newBuilder().setBb(327).build()); + message.addExtension(repeatedFloatExtensionLite, 311F); + message.addExtension(repeatedDoubleExtensionLite, 312D); + message.addExtension(repeatedBoolExtensionLite, false); + message.addExtension(repeatedStringExtensionLite, "315"); + message.addExtension(repeatedBytesExtensionLite, toBytes("316")); + + message.addExtension( + repeatedGroupExtensionLite, RepeatedGroup_extension_lite.newBuilder().setA(317).build()); + message.addExtension( + repeatedNestedMessageExtensionLite, + TestAllTypesLite.NestedMessage.newBuilder().setBb(318).build()); + message.addExtension( + repeatedForeignMessageExtensionLite, ForeignMessageLite.newBuilder().setC(319).build()); + message.addExtension( + repeatedImportMessageExtensionLite, ImportMessageLite.newBuilder().setD(320).build()); + message.addExtension( + repeatedLazyMessageExtensionLite, + TestAllTypesLite.NestedMessage.newBuilder().setBb(327).build()); message.addExtension(repeatedNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ); message.addExtension(repeatedForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ); @@ -452,21 +440,21 @@ public final class TestUtilLite { // ----------------------------------------------------------------- - message.setExtension(defaultInt32ExtensionLite , 401); - message.setExtension(defaultInt64ExtensionLite , 402L); - message.setExtension(defaultUint32ExtensionLite , 403); - message.setExtension(defaultUint64ExtensionLite , 404L); - message.setExtension(defaultSint32ExtensionLite , 405); - message.setExtension(defaultSint64ExtensionLite , 406L); - message.setExtension(defaultFixed32ExtensionLite , 407); - message.setExtension(defaultFixed64ExtensionLite , 408L); + message.setExtension(defaultInt32ExtensionLite, 401); + message.setExtension(defaultInt64ExtensionLite, 402L); + message.setExtension(defaultUint32ExtensionLite, 403); + message.setExtension(defaultUint64ExtensionLite, 404L); + message.setExtension(defaultSint32ExtensionLite, 405); + message.setExtension(defaultSint64ExtensionLite, 406L); + message.setExtension(defaultFixed32ExtensionLite, 407); + message.setExtension(defaultFixed64ExtensionLite, 408L); message.setExtension(defaultSfixed32ExtensionLite, 409); message.setExtension(defaultSfixed64ExtensionLite, 410L); - message.setExtension(defaultFloatExtensionLite , 411F); - message.setExtension(defaultDoubleExtensionLite , 412D); - message.setExtension(defaultBoolExtensionLite , false); - message.setExtension(defaultStringExtensionLite , "415"); - message.setExtension(defaultBytesExtensionLite , toBytes("416")); + message.setExtension(defaultFloatExtensionLite, 411F); + message.setExtension(defaultDoubleExtensionLite, 412D); + message.setExtension(defaultBoolExtensionLite, false); + message.setExtension(defaultStringExtensionLite, "415"); + message.setExtension(defaultBytesExtensionLite, toBytes("416")); message.setExtension(defaultNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.FOO); message.setExtension(defaultForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_FOO); @@ -476,8 +464,9 @@ public final class TestUtilLite { message.setExtension(defaultCordExtensionLite, "425"); message.setExtension(oneofUint32ExtensionLite, 601); - message.setExtension(oneofNestedMessageExtensionLite, - TestAllTypesLite.NestedMessage.newBuilder().setBb(602).build()); + message.setExtension( + oneofNestedMessageExtensionLite, + TestAllTypesLite.NestedMessage.newBuilder().setBb(602).build()); message.setExtension(oneofStringExtensionLite, "603"); message.setExtension(oneofBytesExtensionLite, toBytes("604")); } @@ -485,75 +474,78 @@ public final class TestUtilLite { // ------------------------------------------------------------------- /** - * Modify the repeated extensions of {@code message} to contain the values - * expected by {@code assertRepeatedExtensionsModified()}. + * Modify the repeated extensions of {@code message} to contain the values expected by {@code + * assertRepeatedExtensionsModified()}. */ - public static void modifyRepeatedExtensions( - TestAllExtensionsLite.Builder message) { - message.setExtension(repeatedInt32ExtensionLite , 1, 501); - message.setExtension(repeatedInt64ExtensionLite , 1, 502L); - message.setExtension(repeatedUint32ExtensionLite , 1, 503); - message.setExtension(repeatedUint64ExtensionLite , 1, 504L); - message.setExtension(repeatedSint32ExtensionLite , 1, 505); - message.setExtension(repeatedSint64ExtensionLite , 1, 506L); - message.setExtension(repeatedFixed32ExtensionLite , 1, 507); - message.setExtension(repeatedFixed64ExtensionLite , 1, 508L); + public static void modifyRepeatedExtensions(TestAllExtensionsLite.Builder message) { + message.setExtension(repeatedInt32ExtensionLite, 1, 501); + message.setExtension(repeatedInt64ExtensionLite, 1, 502L); + message.setExtension(repeatedUint32ExtensionLite, 1, 503); + message.setExtension(repeatedUint64ExtensionLite, 1, 504L); + message.setExtension(repeatedSint32ExtensionLite, 1, 505); + message.setExtension(repeatedSint64ExtensionLite, 1, 506L); + message.setExtension(repeatedFixed32ExtensionLite, 1, 507); + message.setExtension(repeatedFixed64ExtensionLite, 1, 508L); message.setExtension(repeatedSfixed32ExtensionLite, 1, 509); message.setExtension(repeatedSfixed64ExtensionLite, 1, 510L); - message.setExtension(repeatedFloatExtensionLite , 1, 511F); - message.setExtension(repeatedDoubleExtensionLite , 1, 512D); - message.setExtension(repeatedBoolExtensionLite , 1, true); - message.setExtension(repeatedStringExtensionLite , 1, "515"); - message.setExtension(repeatedBytesExtensionLite , 1, toBytes("516")); - - message.setExtension(repeatedGroupExtensionLite, 1, - RepeatedGroup_extension_lite.newBuilder().setA(517).build()); - message.setExtension(repeatedNestedMessageExtensionLite, 1, - TestAllTypesLite.NestedMessage.newBuilder().setBb(518).build()); - message.setExtension(repeatedForeignMessageExtensionLite, 1, - ForeignMessageLite.newBuilder().setC(519).build()); - message.setExtension(repeatedImportMessageExtensionLite, 1, - ImportMessageLite.newBuilder().setD(520).build()); - message.setExtension(repeatedLazyMessageExtensionLite, 1, - TestAllTypesLite.NestedMessage.newBuilder().setBb(527).build()); - - message.setExtension(repeatedNestedEnumExtensionLite , 1, TestAllTypesLite.NestedEnum.FOO); + message.setExtension(repeatedFloatExtensionLite, 1, 511F); + message.setExtension(repeatedDoubleExtensionLite, 1, 512D); + message.setExtension(repeatedBoolExtensionLite, 1, true); + message.setExtension(repeatedStringExtensionLite, 1, "515"); + message.setExtension(repeatedBytesExtensionLite, 1, toBytes("516")); + + message.setExtension( + repeatedGroupExtensionLite, 1, RepeatedGroup_extension_lite.newBuilder().setA(517).build()); + message.setExtension( + repeatedNestedMessageExtensionLite, + 1, + TestAllTypesLite.NestedMessage.newBuilder().setBb(518).build()); + message.setExtension( + repeatedForeignMessageExtensionLite, 1, ForeignMessageLite.newBuilder().setC(519).build()); + message.setExtension( + repeatedImportMessageExtensionLite, 1, ImportMessageLite.newBuilder().setD(520).build()); + message.setExtension( + repeatedLazyMessageExtensionLite, + 1, + TestAllTypesLite.NestedMessage.newBuilder().setBb(527).build()); + + message.setExtension(repeatedNestedEnumExtensionLite, 1, TestAllTypesLite.NestedEnum.FOO); message.setExtension(repeatedForeignEnumExtensionLite, 1, ForeignEnumLite.FOREIGN_LITE_FOO); - message.setExtension(repeatedImportEnumExtensionLite , 1, ImportEnumLite.IMPORT_LITE_FOO); + message.setExtension(repeatedImportEnumExtensionLite, 1, ImportEnumLite.IMPORT_LITE_FOO); message.setExtension(repeatedStringPieceExtensionLite, 1, "524"); message.setExtension(repeatedCordExtensionLite, 1, "525"); } public static void setPackedExtensions(TestPackedExtensionsLite.Builder message) { - message.addExtension(packedInt32ExtensionLite , 601); - message.addExtension(packedInt64ExtensionLite , 602L); - message.addExtension(packedUint32ExtensionLite , 603); - message.addExtension(packedUint64ExtensionLite , 604L); - message.addExtension(packedSint32ExtensionLite , 605); - message.addExtension(packedSint64ExtensionLite , 606L); - message.addExtension(packedFixed32ExtensionLite , 607); - message.addExtension(packedFixed64ExtensionLite , 608L); + message.addExtension(packedInt32ExtensionLite, 601); + message.addExtension(packedInt64ExtensionLite, 602L); + message.addExtension(packedUint32ExtensionLite, 603); + message.addExtension(packedUint64ExtensionLite, 604L); + message.addExtension(packedSint32ExtensionLite, 605); + message.addExtension(packedSint64ExtensionLite, 606L); + message.addExtension(packedFixed32ExtensionLite, 607); + message.addExtension(packedFixed64ExtensionLite, 608L); message.addExtension(packedSfixed32ExtensionLite, 609); message.addExtension(packedSfixed64ExtensionLite, 610L); - message.addExtension(packedFloatExtensionLite , 611F); - message.addExtension(packedDoubleExtensionLite , 612D); - message.addExtension(packedBoolExtensionLite , true); + message.addExtension(packedFloatExtensionLite, 611F); + message.addExtension(packedDoubleExtensionLite, 612D); + message.addExtension(packedBoolExtensionLite, true); message.addExtension(packedEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAR); // Add a second one of each field. - message.addExtension(packedInt32ExtensionLite , 701); - message.addExtension(packedInt64ExtensionLite , 702L); - message.addExtension(packedUint32ExtensionLite , 703); - message.addExtension(packedUint64ExtensionLite , 704L); - message.addExtension(packedSint32ExtensionLite , 705); - message.addExtension(packedSint64ExtensionLite , 706L); - message.addExtension(packedFixed32ExtensionLite , 707); - message.addExtension(packedFixed64ExtensionLite , 708L); + message.addExtension(packedInt32ExtensionLite, 701); + message.addExtension(packedInt64ExtensionLite, 702L); + message.addExtension(packedUint32ExtensionLite, 703); + message.addExtension(packedUint64ExtensionLite, 704L); + message.addExtension(packedSint32ExtensionLite, 705); + message.addExtension(packedSint64ExtensionLite, 706L); + message.addExtension(packedFixed32ExtensionLite, 707); + message.addExtension(packedFixed64ExtensionLite, 708L); message.addExtension(packedSfixed32ExtensionLite, 709); message.addExtension(packedSfixed64ExtensionLite, 710L); - message.addExtension(packedFloatExtensionLite , 711F); - message.addExtension(packedDoubleExtensionLite , 712D); - message.addExtension(packedBoolExtensionLite , false); + message.addExtension(packedFloatExtensionLite, 711F); + message.addExtension(packedDoubleExtensionLite, 712D); + message.addExtension(packedBoolExtensionLite, false); message.addExtension(packedEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ); } } diff --git a/java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java b/java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java index e338af2112..ff413720b7 100644 --- a/java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java +++ b/java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java @@ -33,12 +33,9 @@ package com.google.protobuf; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import protobuf_unittest.UnittestProto.TestAllTypes; - import junit.framework.TestCase; -/** - * Test @{link TextFormatParseInfoTree}. - */ +/** Test @{link TextFormatParseInfoTree}. */ public class TextFormatParseInfoTreeTest extends TestCase { private static final Descriptor DESCRIPTOR = TestAllTypes.getDescriptor(); @@ -75,7 +72,7 @@ public class TextFormatParseInfoTreeTest extends TestCase { TextFormatParseInfoTree root = rootBuilder.build(); assertEquals(LOC0, root.getLocation(OPTIONAL_INT32, 0)); assertEquals(1, root.getLocations(OPTIONAL_INT32).size()); - } + } public void testGetLocationsReturnsNoParseLocationsForUnknownField() { assertTrue(rootBuilder.build().getLocations(OPTIONAL_INT32).isEmpty()); diff --git a/java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java b/java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java index c42bfa6e71..19abc3f88f 100644 --- a/java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java +++ b/java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java @@ -32,9 +32,7 @@ package com.google.protobuf; import junit.framework.TestCase; -/** - * Test @{link TextFormatParseLocation}. - */ +/** Test @{link TextFormatParseLocation}. */ public class TextFormatParseLocationTest extends TestCase { public void testCreateEmpty() { diff --git a/java/core/src/test/java/com/google/protobuf/TextFormatTest.java b/java/core/src/test/java/com/google/protobuf/TextFormatTest.java index 24d5589f80..d240088cfe 100644 --- a/java/core/src/test/java/com/google/protobuf/TextFormatTest.java +++ b/java/core/src/test/java/com/google/protobuf/TextFormatTest.java @@ -54,7 +54,7 @@ import junit.framework.TestCase; /** * Test case for {@link TextFormat}. * - * TODO(wenboz): ExtensionTest and rest of text_format_unittest.cc. + *

TODO(wenboz): ExtensionTest and rest of text_format_unittest.cc. * * @author wenboz@google.com (Wenbo Zhu) */ @@ -62,76 +62,82 @@ public class TextFormatTest extends TestCase { // A basic string with different escapable characters for testing. private static final String ESCAPE_TEST_STRING = - "\"A string with ' characters \n and \r newlines and \t tabs and \001 " + "slashes \\"; + "\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\"; // A representation of the above string with all the characters escaped. private static final String ESCAPE_TEST_STRING_ESCAPED = "\\\"A string with \\' characters \\n and \\r newlines " + "and \\t tabs and \\001 slashes \\\\"; - private static String allFieldsSetText = TestUtil.readTextFromFile( - "text_format_unittest_data_oneof_implemented.txt"); - private static String allExtensionsSetText = TestUtil.readTextFromFile( - "text_format_unittest_extensions_data.txt"); + private static String allFieldsSetText = + TestUtil.readTextFromFile("text_format_unittest_data_oneof_implemented.txt"); + private static String allExtensionsSetText = + TestUtil.readTextFromFile("text_format_unittest_extensions_data.txt"); private static String exoticText = - "repeated_int32: -1\n" + - "repeated_int32: -2147483648\n" + - "repeated_int64: -1,\n" + - "repeated_int64: -9223372036854775808\n" + - "repeated_uint32: 4294967295\n" + - "repeated_uint32: 2147483648\n" + - "repeated_uint64: 18446744073709551615\n" + - "repeated_uint64: 9223372036854775808\n" + - "repeated_double: 123.0\n" + - "repeated_double: 123.5\n" + - "repeated_double: 0.125\n" + - "repeated_double: .125\n" + - "repeated_double: -.125\n" + - "repeated_double: 1.23E17\n" + - "repeated_double: 1.23E+17\n" + - "repeated_double: -1.23e-17\n" + - "repeated_double: .23e+17\n" + - "repeated_double: -.23E17\n" + - "repeated_double: 1.235E22\n" + - "repeated_double: 1.235E-18\n" + - "repeated_double: 123.456789\n" + - "repeated_double: Infinity\n" + - "repeated_double: -Infinity\n" + - "repeated_double: NaN\n" + - "repeated_string: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"" + - "\\341\\210\\264\"\n" + - "repeated_bytes: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\376\"\n"; + "" + + "repeated_int32: -1\n" + + "repeated_int32: -2147483648\n" + + "repeated_int64: -1,\n" + + "repeated_int64: -9223372036854775808\n" + + "repeated_uint32: 4294967295\n" + + "repeated_uint32: 2147483648\n" + + "repeated_uint64: 18446744073709551615\n" + + "repeated_uint64: 9223372036854775808\n" + + "repeated_double: 123.0\n" + + "repeated_double: 123.5\n" + + "repeated_double: 0.125\n" + + "repeated_double: .125\n" + + "repeated_double: -.125\n" + + "repeated_double: 1.23E17\n" + + "repeated_double: 1.23E+17\n" + + "repeated_double: -1.23e-17\n" + + "repeated_double: .23e+17\n" + + "repeated_double: -.23E17\n" + + "repeated_double: 1.235E22\n" + + "repeated_double: 1.235E-18\n" + + "repeated_double: 123.456789\n" + + "repeated_double: Infinity\n" + + "repeated_double: -Infinity\n" + + "repeated_double: NaN\n" + + "repeated_string: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"" + + "\\341\\210\\264\"\n" + + "repeated_bytes: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\376\"\n"; private static String canonicalExoticText = - exoticText.replace(": .", ": 0.").replace(": -.", ": -0.") // short-form double - .replace("23e", "23E").replace("E+", "E").replace("0.23E17", "2.3E16").replace(",", ""); + exoticText + .replace(": .", ": 0.") + .replace(": -.", ": -0.") // short-form double + .replace("23e", "23E") + .replace("E+", "E") + .replace("0.23E17", "2.3E16") + .replace(",", ""); private String messageSetText = - "[protobuf_unittest.TestMessageSetExtension1] {\n" + - " i: 123\n" + - "}\n" + - "[protobuf_unittest.TestMessageSetExtension2] {\n" + - " str: \"foo\"\n" + - "}\n"; + "" + + "[protobuf_unittest.TestMessageSetExtension1] {\n" + + " i: 123\n" + + "}\n" + + "[protobuf_unittest.TestMessageSetExtension2] {\n" + + " str: \"foo\"\n" + + "}\n"; private String messageSetTextWithRepeatedExtension = - "[protobuf_unittest.TestMessageSetExtension1] {\n" + - " i: 123\n" + - "}\n" + - "[protobuf_unittest.TestMessageSetExtension1] {\n" + - " i: 456\n" + - "}\n"; + "" + + "[protobuf_unittest.TestMessageSetExtension1] {\n" + + " i: 123\n" + + "}\n" + + "[protobuf_unittest.TestMessageSetExtension1] {\n" + + " i: 456\n" + + "}\n"; private final TextFormat.Parser parserWithOverwriteForbidden = TextFormat.Parser.newBuilder() - .setSingularOverwritePolicy( - SingularOverwritePolicy.FORBID_SINGULAR_OVERWRITES) + .setSingularOverwritePolicy(SingularOverwritePolicy.FORBID_SINGULAR_OVERWRITES) .build(); - private final TextFormat.Parser defaultParser = - TextFormat.Parser.newBuilder().build(); + private final TextFormat.Parser defaultParser = TextFormat.Parser.newBuilder().build(); /** Print TestAllTypes and compare with golden file. */ public void testPrintMessage() throws Exception { @@ -173,38 +179,32 @@ public class TextFormatTest extends TestCase { private UnknownFieldSet makeUnknownFieldSet() { return UnknownFieldSet.newBuilder() - .addField(5, + .addField( + 5, UnknownFieldSet.Field.newBuilder() - .addVarint(1) - .addFixed32(2) - .addFixed64(3) - .addLengthDelimited(ByteString.copyFromUtf8("4")) - .addLengthDelimited(UnknownFieldSet.newBuilder() - .addField(12, - UnknownFieldSet.Field.newBuilder() - .addVarint(6) + .addVarint(1) + .addFixed32(2) + .addFixed64(3) + .addLengthDelimited(ByteString.copyFromUtf8("4")) + .addLengthDelimited( + UnknownFieldSet.newBuilder() + .addField(12, UnknownFieldSet.Field.newBuilder().addVarint(6).build()) + .build() + .toByteString()) + .addGroup( + UnknownFieldSet.newBuilder() + .addField(10, UnknownFieldSet.Field.newBuilder().addVarint(5).build()) .build()) - .build().toByteString()) - .addGroup( - UnknownFieldSet.newBuilder() - .addField(10, - UnknownFieldSet.Field.newBuilder() - .addVarint(5) - .build()) .build()) - .build()) - .addField(8, - UnknownFieldSet.Field.newBuilder() - .addVarint(1) - .addVarint(2) - .addVarint(3) - .build()) - .addField(15, + .addField( + 8, UnknownFieldSet.Field.newBuilder().addVarint(1).addVarint(2).addVarint(3).build()) + .addField( + 15, UnknownFieldSet.Field.newBuilder() - .addVarint(0xABCDEF1234567890L) - .addFixed32(0xABCD1234) - .addFixed64(0xABCDEF1234567890L) - .build()) + .addVarint(0xABCDEF1234567890L) + .addFixed32(0xABCD1234) + .addFixed64(0xABCDEF1234567890L) + .build()) .build(); } @@ -212,9 +212,7 @@ public class TextFormatTest extends TestCase { // Test printing of unknown fields in a message. TestEmptyMessage message = - TestEmptyMessage.newBuilder() - .setUnknownFields(makeUnknownFieldSet()) - .build(); + TestEmptyMessage.newBuilder().setUnknownFields(makeUnknownFieldSet()).build(); assertEquals( "5: 1\n" @@ -237,34 +235,29 @@ public class TextFormatTest extends TestCase { } public void testPrintField() throws Exception { - final FieldDescriptor dataField = - OneString.getDescriptor().findFieldByName("data"); - assertEquals( - "data: \"test data\"\n", - TextFormat.printFieldToString(dataField, "test data")); + final FieldDescriptor dataField = OneString.getDescriptor().findFieldByName("data"); + assertEquals("data: \"test data\"\n", TextFormat.printFieldToString(dataField, "test data")); final FieldDescriptor optionalField = - TestAllTypes.getDescriptor().findFieldByName("optional_nested_message"); + TestAllTypes.getDescriptor().findFieldByName("optional_nested_message"); final Object value = NestedMessage.newBuilder().setBb(42).build(); assertEquals( - "optional_nested_message {\n bb: 42\n}\n", - TextFormat.printFieldToString(optionalField, value)); + "optional_nested_message {\n bb: 42\n}\n", + TextFormat.printFieldToString(optionalField, value)); } /** - * Helper to construct a ByteString from a String containing only 8-bit - * characters. The characters are converted directly to bytes, *not* - * encoded using UTF-8. + * Helper to construct a ByteString from a String containing only 8-bit characters. The characters + * are converted directly to bytes, *not* encoded using UTF-8. */ private ByteString bytes(String str) { return ByteString.copyFrom(str.getBytes(Internal.ISO_8859_1)); } /** - * Helper to construct a ByteString from a bunch of bytes. The inputs are - * actually ints so that I can use hex notation and not get stupid errors - * about precision. + * Helper to construct a ByteString from a bunch of bytes. The inputs are actually ints so that I + * can use hex notation and not get stupid errors about precision. */ private ByteString bytes(int... bytesAsInts) { byte[] bytes = new byte[bytesAsInts.length]; @@ -275,54 +268,54 @@ public class TextFormatTest extends TestCase { } public void testPrintExotic() throws Exception { - Message message = TestAllTypes.newBuilder() - // Signed vs. unsigned numbers. - .addRepeatedInt32 (-1) - .addRepeatedUint32(-1) - .addRepeatedInt64 (-1) - .addRepeatedUint64(-1) - - .addRepeatedInt32 (1 << 31) - .addRepeatedUint32(1 << 31) - .addRepeatedInt64 (1L << 63) - .addRepeatedUint64(1L << 63) - - // Floats of various precisions and exponents. - .addRepeatedDouble(123) - .addRepeatedDouble(123.5) - .addRepeatedDouble(0.125) - .addRepeatedDouble(.125) - .addRepeatedDouble(-.125) - .addRepeatedDouble(123e15) - .addRepeatedDouble(123e15) - .addRepeatedDouble(-1.23e-17) - .addRepeatedDouble(.23e17) - .addRepeatedDouble(-23e15) - .addRepeatedDouble(123.5e20) - .addRepeatedDouble(123.5e-20) - .addRepeatedDouble(123.456789) - .addRepeatedDouble(Double.POSITIVE_INFINITY) - .addRepeatedDouble(Double.NEGATIVE_INFINITY) - .addRepeatedDouble(Double.NaN) - - // Strings and bytes that needing escaping. - .addRepeatedString("\0\001\007\b\f\n\r\t\013\\\'\"\u1234") - .addRepeatedBytes(bytes("\0\001\007\b\f\n\r\t\013\\\'\"\u00fe")) - .build(); + Message message = + TestAllTypes.newBuilder() + // Signed vs. unsigned numbers. + .addRepeatedInt32(-1) + .addRepeatedUint32(-1) + .addRepeatedInt64(-1) + .addRepeatedUint64(-1) + .addRepeatedInt32(1 << 31) + .addRepeatedUint32(1 << 31) + .addRepeatedInt64(1L << 63) + .addRepeatedUint64(1L << 63) + + // Floats of various precisions and exponents. + .addRepeatedDouble(123) + .addRepeatedDouble(123.5) + .addRepeatedDouble(0.125) + .addRepeatedDouble(.125) + .addRepeatedDouble(-.125) + .addRepeatedDouble(123e15) + .addRepeatedDouble(123e15) + .addRepeatedDouble(-1.23e-17) + .addRepeatedDouble(.23e17) + .addRepeatedDouble(-23e15) + .addRepeatedDouble(123.5e20) + .addRepeatedDouble(123.5e-20) + .addRepeatedDouble(123.456789) + .addRepeatedDouble(Double.POSITIVE_INFINITY) + .addRepeatedDouble(Double.NEGATIVE_INFINITY) + .addRepeatedDouble(Double.NaN) + + // Strings and bytes that needing escaping. + .addRepeatedString("\0\001\007\b\f\n\r\t\013\\\'\"\u1234") + .addRepeatedBytes(bytes("\0\001\007\b\f\n\r\t\013\\\'\"\u00fe")) + .build(); assertEquals(canonicalExoticText, message.toString()); } public void testPrintMessageSet() throws Exception { TestMessageSet messageSet = - TestMessageSet.newBuilder() - .setExtension( - TestMessageSetExtension1.messageSetExtension, - TestMessageSetExtension1.newBuilder().setI(123).build()) - .setExtension( - TestMessageSetExtension2.messageSetExtension, - TestMessageSetExtension2.newBuilder().setStr("foo").build()) - .build(); + TestMessageSet.newBuilder() + .setExtension( + TestMessageSetExtension1.messageSetExtension, + TestMessageSetExtension1.newBuilder().setI(123).build()) + .setExtension( + TestMessageSetExtension2.messageSetExtension, + TestMessageSetExtension2.newBuilder().setStr("foo").build()) + .build(); assertEquals(messageSetText, messageSet.toString()); } @@ -336,22 +329,19 @@ public class TextFormatTest extends TestCase { } public void testParse() throws Exception { - TestUtil.assertAllFieldsSet( - TextFormat.parse(allFieldsSetText, TestAllTypes.class)); + TestUtil.assertAllFieldsSet(TextFormat.parse(allFieldsSetText, TestAllTypes.class)); } public void testMergeInitialized() throws Exception { TestRequired.Builder builder = TestRequired.newBuilder(); TextFormat.merge(TEST_REQUIRED_INITIALIZED.toString(), builder); - assertEquals(TEST_REQUIRED_INITIALIZED.toString(), - builder.buildPartial().toString()); + assertEquals(TEST_REQUIRED_INITIALIZED.toString(), builder.buildPartial().toString()); assertTrue(builder.isInitialized()); } public void testParseInitialized() throws Exception { TestRequired parsed = - TextFormat.parse(TEST_REQUIRED_INITIALIZED.toString(), - TestRequired.class); + TextFormat.parse(TEST_REQUIRED_INITIALIZED.toString(), TestRequired.class); assertEquals(TEST_REQUIRED_INITIALIZED.toString(), parsed.toString()); assertTrue(parsed.isInitialized()); } @@ -359,15 +349,13 @@ public class TextFormatTest extends TestCase { public void testMergeUninitialized() throws Exception { TestRequired.Builder builder = TestRequired.newBuilder(); TextFormat.merge(TEST_REQUIRED_UNINITIALIZED.toString(), builder); - assertEquals(TEST_REQUIRED_UNINITIALIZED.toString(), - builder.buildPartial().toString()); + assertEquals(TEST_REQUIRED_UNINITIALIZED.toString(), builder.buildPartial().toString()); assertFalse(builder.isInitialized()); } public void testParseUninitialized() throws Exception { try { - TextFormat.parse(TEST_REQUIRED_UNINITIALIZED.toString(), - TestRequired.class); + TextFormat.parse(TEST_REQUIRED_UNINITIALIZED.toString(), TestRequired.class); fail("Expected UninitializedMessageException."); } catch (UninitializedMessageException e) { assertEquals("Message missing required fields: b, c", e.getMessage()); @@ -393,30 +381,32 @@ public class TextFormatTest extends TestCase { } public void testMergeAndParseCompatibility() throws Exception { - String original = "repeated_float: inf\n" + - "repeated_float: -inf\n" + - "repeated_float: nan\n" + - "repeated_float: inff\n" + - "repeated_float: -inff\n" + - "repeated_float: nanf\n" + - "repeated_float: 1.0f\n" + - "repeated_float: infinityf\n" + - "repeated_float: -Infinityf\n" + - "repeated_double: infinity\n" + - "repeated_double: -infinity\n" + - "repeated_double: nan\n"; - String canonical = "repeated_float: Infinity\n" + - "repeated_float: -Infinity\n" + - "repeated_float: NaN\n" + - "repeated_float: Infinity\n" + - "repeated_float: -Infinity\n" + - "repeated_float: NaN\n" + - "repeated_float: 1.0\n" + - "repeated_float: Infinity\n" + - "repeated_float: -Infinity\n" + - "repeated_double: Infinity\n" + - "repeated_double: -Infinity\n" + - "repeated_double: NaN\n"; + String original = + "repeated_float: inf\n" + + "repeated_float: -inf\n" + + "repeated_float: nan\n" + + "repeated_float: inff\n" + + "repeated_float: -inff\n" + + "repeated_float: nanf\n" + + "repeated_float: 1.0f\n" + + "repeated_float: infinityf\n" + + "repeated_float: -Infinityf\n" + + "repeated_double: infinity\n" + + "repeated_double: -infinity\n" + + "repeated_double: nan\n"; + String canonical = + "repeated_float: Infinity\n" + + "repeated_float: -Infinity\n" + + "repeated_float: NaN\n" + + "repeated_float: Infinity\n" + + "repeated_float: -Infinity\n" + + "repeated_float: NaN\n" + + "repeated_float: 1.0\n" + + "repeated_float: Infinity\n" + + "repeated_float: -Infinity\n" + + "repeated_double: Infinity\n" + + "repeated_double: -Infinity\n" + + "repeated_double: NaN\n"; // Test merge(). TestAllTypes.Builder builder = TestAllTypes.newBuilder(); @@ -424,8 +414,7 @@ public class TextFormatTest extends TestCase { assertEquals(canonical, builder.build().toString()); // Test parse(). - assertEquals(canonical, - TextFormat.parse(original, TestAllTypes.class).toString()); + assertEquals(canonical, TextFormat.parse(original, TestAllTypes.class).toString()); } public void testMergeAndParseExotic() throws Exception { @@ -435,8 +424,7 @@ public class TextFormatTest extends TestCase { // Too lazy to check things individually. Don't try to debug this // if testPrintExotic() is failing. assertEquals(canonicalExoticText, builder.build().toString()); - assertEquals(canonicalExoticText, - TextFormat.parse(exoticText, TestAllTypes.class).toString()); + assertEquals(canonicalExoticText, TextFormat.parse(exoticText, TestAllTypes.class).toString()); } public void testMergeMessageSet() throws Exception { @@ -448,21 +436,16 @@ public class TextFormatTest extends TestCase { TextFormat.merge(messageSetText, extensionRegistry, builder); TestMessageSet messageSet = builder.build(); - assertTrue(messageSet.hasExtension( - TestMessageSetExtension1.messageSetExtension)); - assertEquals(123, messageSet.getExtension( - TestMessageSetExtension1.messageSetExtension).getI()); - assertTrue(messageSet.hasExtension( - TestMessageSetExtension2.messageSetExtension)); - assertEquals("foo", messageSet.getExtension( - TestMessageSetExtension2.messageSetExtension).getStr()); + assertTrue(messageSet.hasExtension(TestMessageSetExtension1.messageSetExtension)); + assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI()); + assertTrue(messageSet.hasExtension(TestMessageSetExtension2.messageSetExtension)); + assertEquals( + "foo", messageSet.getExtension(TestMessageSetExtension2.messageSetExtension).getStr()); builder = TestMessageSet.newBuilder(); - TextFormat.merge(messageSetTextWithRepeatedExtension, extensionRegistry, - builder); + TextFormat.merge(messageSetTextWithRepeatedExtension, extensionRegistry, builder); messageSet = builder.build(); - assertEquals(456, messageSet.getExtension( - TestMessageSetExtension1.messageSetExtension).getI()); + assertEquals(456, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI()); } public void testMergeMessageSetWithOverwriteForbidden() throws Exception { @@ -471,13 +454,11 @@ public class TextFormatTest extends TestCase { extensionRegistry.add(TestMessageSetExtension2.messageSetExtension); TestMessageSet.Builder builder = TestMessageSet.newBuilder(); - parserWithOverwriteForbidden.merge( - messageSetText, extensionRegistry, builder); + parserWithOverwriteForbidden.merge(messageSetText, extensionRegistry, builder); TestMessageSet messageSet = builder.build(); - assertEquals(123, messageSet.getExtension( - TestMessageSetExtension1.messageSetExtension).getI()); - assertEquals("foo", messageSet.getExtension( - TestMessageSetExtension2.messageSetExtension).getStr()); + assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI()); + assertEquals( + "foo", messageSet.getExtension(TestMessageSetExtension2.messageSetExtension).getStr()); builder = TestMessageSet.newBuilder(); try { @@ -485,9 +466,10 @@ public class TextFormatTest extends TestCase { messageSetTextWithRepeatedExtension, extensionRegistry, builder); fail("expected parse exception"); } catch (TextFormat.ParseException e) { - assertEquals("6:1: Non-repeated field " - + "\"protobuf_unittest.TestMessageSetExtension1.message_set_extension\"" - + " cannot be overwritten.", + assertEquals( + "6:1: Non-repeated field " + + "\"protobuf_unittest.TestMessageSetExtension1.message_set_extension\"" + + " cannot be overwritten.", e.getMessage()); } } @@ -508,10 +490,11 @@ public class TextFormatTest extends TestCase { public void testMergeComment() throws Exception { TestAllTypes.Builder builder = TestAllTypes.newBuilder(); TextFormat.merge( - "# this is a comment\n" + - "optional_int32: 1 # another comment\n" + - "optional_int64: 2\n" + - "# EOF comment", builder); + "# this is a comment\n" + + "optional_int32: 1 # another comment\n" + + "optional_int64: 2\n" + + "# EOF comment", + builder); assertEquals(1, builder.getOptionalInt32()); assertEquals(2, builder.getOptionalInt64()); } @@ -536,8 +519,7 @@ public class TextFormatTest extends TestCase { } - private void assertParseErrorWithOverwriteForbidden(String error, - String text) { + private void assertParseErrorWithOverwriteForbidden(String error, String text) { TestAllTypes.Builder builder = TestAllTypes.newBuilder(); try { parserWithOverwriteForbidden.merge(text, TestUtil.getFullExtensionRegistry(), builder); @@ -547,118 +529,91 @@ public class TextFormatTest extends TestCase { } } - private TestAllTypes assertParseSuccessWithOverwriteForbidden( - String text) throws TextFormat.ParseException { + private TestAllTypes assertParseSuccessWithOverwriteForbidden(String text) + throws TextFormat.ParseException { TestAllTypes.Builder builder = TestAllTypes.newBuilder(); parserWithOverwriteForbidden.merge(text, TestUtil.getFullExtensionRegistry(), builder); return builder.build(); } public void testParseErrors() throws Exception { + assertParseError("1:16: Expected \":\".", "optional_int32 123"); + assertParseError("1:23: Expected identifier. Found '?'", "optional_nested_enum: ?"); assertParseError( - "1:16: Expected \":\".", - "optional_int32 123"); - assertParseError( - "1:23: Expected identifier. Found '?'", - "optional_nested_enum: ?"); - assertParseError( - "1:18: Couldn't parse integer: Number must be positive: -1", - "optional_uint32: -1"); - assertParseError( - "1:17: Couldn't parse integer: Number out of range for 32-bit signed " + - "integer: 82301481290849012385230157", - "optional_int32: 82301481290849012385230157"); + "1:18: Couldn't parse integer: Number must be positive: -1", "optional_uint32: -1"); assertParseError( - "1:16: Expected \"true\" or \"false\". Found \"maybe\".", - "optional_bool: maybe"); + "1:17: Couldn't parse integer: Number out of range for 32-bit signed " + + "integer: 82301481290849012385230157", + "optional_int32: 82301481290849012385230157"); assertParseError( - "1:16: Expected \"true\" or \"false\". Found \"2\".", - "optional_bool: 2"); + "1:16: Expected \"true\" or \"false\". Found \"maybe\".", "optional_bool: maybe"); + assertParseError("1:16: Expected \"true\" or \"false\". Found \"2\".", "optional_bool: 2"); + assertParseError("1:18: Expected string.", "optional_string: 123"); + assertParseError("1:18: String missing ending quote.", "optional_string: \"ueoauaoe"); assertParseError( - "1:18: Expected string.", - "optional_string: 123"); + "1:18: String missing ending quote.", "optional_string: \"ueoauaoe\noptional_int32: 123"); + assertParseError("1:18: Invalid escape sequence: '\\z'", "optional_string: \"\\z\""); assertParseError( - "1:18: String missing ending quote.", - "optional_string: \"ueoauaoe"); + "1:18: String missing ending quote.", "optional_string: \"ueoauaoe\noptional_int32: 123"); assertParseError( - "1:18: String missing ending quote.", - "optional_string: \"ueoauaoe\n" + - "optional_int32: 123"); + "1:2: Input contains unknown fields and/or extensions:\n" + + "1:2:\tprotobuf_unittest.TestAllTypes.[nosuchext]", + "[nosuchext]: 123"); assertParseError( - "1:18: Invalid escape sequence: '\\z'", - "optional_string: \"\\z\""); + "1:20: Extension \"protobuf_unittest.optional_int32_extension\" does " + + "not extend message type \"protobuf_unittest.TestAllTypes\".", + "[protobuf_unittest.optional_int32_extension]: 123"); assertParseError( - "1:18: String missing ending quote.", - "optional_string: \"ueoauaoe\n" + - "optional_int32: 123"); + "1:1: Input contains unknown fields and/or extensions:\n" + + "1:1:\tprotobuf_unittest.TestAllTypes.nosuchfield", + "nosuchfield: 123"); + assertParseError("1:21: Expected \">\".", "OptionalGroup < a: 1"); assertParseError( - "1:2: Input contains unknown fields and/or extensions:\n" + - "1:2:\tprotobuf_unittest.TestAllTypes.[nosuchext]", - "[nosuchext]: 123"); + "1:23: Enum type \"protobuf_unittest.TestAllTypes.NestedEnum\" has no " + + "value named \"NO_SUCH_VALUE\".", + "optional_nested_enum: NO_SUCH_VALUE"); assertParseError( - "1:20: Extension \"protobuf_unittest.optional_int32_extension\" does " + - "not extend message type \"protobuf_unittest.TestAllTypes\".", - "[protobuf_unittest.optional_int32_extension]: 123"); - assertParseError( - "1:1: Input contains unknown fields and/or extensions:\n" + - "1:1:\tprotobuf_unittest.TestAllTypes.nosuchfield", - "nosuchfield: 123"); - assertParseError( - "1:21: Expected \">\".", - "OptionalGroup < a: 1"); - assertParseError( - "1:23: Enum type \"protobuf_unittest.TestAllTypes.NestedEnum\" has no " + - "value named \"NO_SUCH_VALUE\".", - "optional_nested_enum: NO_SUCH_VALUE"); - assertParseError( - "1:23: Enum type \"protobuf_unittest.TestAllTypes.NestedEnum\" has no " + - "value with number 123.", - "optional_nested_enum: 123"); + "1:23: Enum type \"protobuf_unittest.TestAllTypes.NestedEnum\" has no " + + "value with number 123.", + "optional_nested_enum: 123"); // Delimiters must match. - assertParseError( - "1:22: Expected identifier. Found '}'", - "OptionalGroup < a: 1 }"); - assertParseError( - "1:22: Expected identifier. Found '>'", - "OptionalGroup { a: 1 >"); + assertParseError("1:22: Expected identifier. Found '}'", "OptionalGroup < a: 1 }"); + assertParseError("1:22: Expected identifier. Found '>'", "OptionalGroup { a: 1 >"); } // ================================================================= public void testEscape() throws Exception { // Escape sequences. - assertEquals("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\177", - TextFormat.escapeBytes(bytes("\0\001\007\b\f\n\r\t\013\\\'\"\177"))); - assertEquals("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\177", - TextFormat.escapeText("\0\001\007\b\f\n\r\t\013\\\'\"\177")); - assertEquals(bytes("\0\001\007\b\f\n\r\t\013\\\'\""), - TextFormat.unescapeBytes("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"")); - assertEquals("\0\001\007\b\f\n\r\t\013\\\'\"", - TextFormat.unescapeText("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"")); + assertEquals( + "\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\177", + TextFormat.escapeBytes(bytes("\0\001\007\b\f\n\r\t\013\\\'\"\177"))); + assertEquals( + "\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\177", + TextFormat.escapeText("\0\001\007\b\f\n\r\t\013\\\'\"\177")); + assertEquals( + bytes("\0\001\007\b\f\n\r\t\013\\\'\""), + TextFormat.unescapeBytes("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"")); + assertEquals( + "\0\001\007\b\f\n\r\t\013\\\'\"", + TextFormat.unescapeText("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"")); assertEquals(ESCAPE_TEST_STRING_ESCAPED, TextFormat.escapeText(ESCAPE_TEST_STRING)); assertEquals(ESCAPE_TEST_STRING, TextFormat.unescapeText(ESCAPE_TEST_STRING_ESCAPED)); // Invariant - assertEquals("hello", - TextFormat.escapeBytes(bytes("hello"))); - assertEquals("hello", - TextFormat.escapeText("hello")); - assertEquals(bytes("hello"), - TextFormat.unescapeBytes("hello")); - assertEquals("hello", - TextFormat.unescapeText("hello")); + assertEquals("hello", TextFormat.escapeBytes(bytes("hello"))); + assertEquals("hello", TextFormat.escapeText("hello")); + assertEquals(bytes("hello"), TextFormat.unescapeBytes("hello")); + assertEquals("hello", TextFormat.unescapeText("hello")); // Unicode handling. assertEquals("\\341\\210\\264", TextFormat.escapeText("\u1234")); - assertEquals("\\341\\210\\264", - TextFormat.escapeBytes(bytes(0xe1, 0x88, 0xb4))); + assertEquals("\\341\\210\\264", TextFormat.escapeBytes(bytes(0xe1, 0x88, 0xb4))); assertEquals("\u1234", TextFormat.unescapeText("\\341\\210\\264")); - assertEquals(bytes(0xe1, 0x88, 0xb4), - TextFormat.unescapeBytes("\\341\\210\\264")); + assertEquals(bytes(0xe1, 0x88, 0xb4), TextFormat.unescapeBytes("\\341\\210\\264")); assertEquals("\u1234", TextFormat.unescapeText("\\xe1\\x88\\xb4")); - assertEquals(bytes(0xe1, 0x88, 0xb4), - TextFormat.unescapeBytes("\\xe1\\x88\\xb4")); + assertEquals(bytes(0xe1, 0x88, 0xb4), TextFormat.unescapeBytes("\\xe1\\x88\\xb4")); // Handling of strings with unescaped Unicode characters > 255. final String zh = "\u9999\u6e2f\u4e0a\u6d77\ud84f\udf80\u8c50\u9280\u884c"; @@ -689,53 +644,48 @@ public class TextFormatTest extends TestCase { } public void testParseInteger() throws Exception { - assertEquals( 0, TextFormat.parseInt32( "0")); - assertEquals( 1, TextFormat.parseInt32( "1")); - assertEquals( -1, TextFormat.parseInt32( "-1")); - assertEquals( 12345, TextFormat.parseInt32( "12345")); - assertEquals( -12345, TextFormat.parseInt32( "-12345")); - assertEquals( 2147483647, TextFormat.parseInt32( "2147483647")); + assertEquals(0, TextFormat.parseInt32("0")); + assertEquals(1, TextFormat.parseInt32("1")); + assertEquals(-1, TextFormat.parseInt32("-1")); + assertEquals(12345, TextFormat.parseInt32("12345")); + assertEquals(-12345, TextFormat.parseInt32("-12345")); + assertEquals(2147483647, TextFormat.parseInt32("2147483647")); assertEquals(-2147483648, TextFormat.parseInt32("-2147483648")); - assertEquals( 0, TextFormat.parseUInt32( "0")); - assertEquals( 1, TextFormat.parseUInt32( "1")); - assertEquals( 12345, TextFormat.parseUInt32( "12345")); - assertEquals( 2147483647, TextFormat.parseUInt32("2147483647")); + assertEquals(0, TextFormat.parseUInt32("0")); + assertEquals(1, TextFormat.parseUInt32("1")); + assertEquals(12345, TextFormat.parseUInt32("12345")); + assertEquals(2147483647, TextFormat.parseUInt32("2147483647")); assertEquals((int) 2147483648L, TextFormat.parseUInt32("2147483648")); assertEquals((int) 4294967295L, TextFormat.parseUInt32("4294967295")); - assertEquals( 0L, TextFormat.parseInt64( "0")); - assertEquals( 1L, TextFormat.parseInt64( "1")); - assertEquals( -1L, TextFormat.parseInt64( "-1")); - assertEquals( 12345L, TextFormat.parseInt64( "12345")); - assertEquals( -12345L, TextFormat.parseInt64( "-12345")); - assertEquals( 2147483647L, TextFormat.parseInt64( "2147483647")); + assertEquals(0L, TextFormat.parseInt64("0")); + assertEquals(1L, TextFormat.parseInt64("1")); + assertEquals(-1L, TextFormat.parseInt64("-1")); + assertEquals(12345L, TextFormat.parseInt64("12345")); + assertEquals(-12345L, TextFormat.parseInt64("-12345")); + assertEquals(2147483647L, TextFormat.parseInt64("2147483647")); assertEquals(-2147483648L, TextFormat.parseInt64("-2147483648")); - assertEquals( 4294967295L, TextFormat.parseInt64( "4294967295")); - assertEquals( 4294967296L, TextFormat.parseInt64( "4294967296")); - assertEquals(9223372036854775807L, - TextFormat.parseInt64("9223372036854775807")); - assertEquals(-9223372036854775808L, - TextFormat.parseInt64("-9223372036854775808")); - - assertEquals( 0L, TextFormat.parseUInt64( "0")); - assertEquals( 1L, TextFormat.parseUInt64( "1")); - assertEquals( 12345L, TextFormat.parseUInt64( "12345")); - assertEquals( 2147483647L, TextFormat.parseUInt64( "2147483647")); - assertEquals( 4294967295L, TextFormat.parseUInt64( "4294967295")); - assertEquals( 4294967296L, TextFormat.parseUInt64( "4294967296")); - assertEquals(9223372036854775807L, - TextFormat.parseUInt64("9223372036854775807")); - assertEquals(-9223372036854775808L, - TextFormat.parseUInt64("9223372036854775808")); + assertEquals(4294967295L, TextFormat.parseInt64("4294967295")); + assertEquals(4294967296L, TextFormat.parseInt64("4294967296")); + assertEquals(9223372036854775807L, TextFormat.parseInt64("9223372036854775807")); + assertEquals(-9223372036854775808L, TextFormat.parseInt64("-9223372036854775808")); + + assertEquals(0L, TextFormat.parseUInt64("0")); + assertEquals(1L, TextFormat.parseUInt64("1")); + assertEquals(12345L, TextFormat.parseUInt64("12345")); + assertEquals(2147483647L, TextFormat.parseUInt64("2147483647")); + assertEquals(4294967295L, TextFormat.parseUInt64("4294967295")); + assertEquals(4294967296L, TextFormat.parseUInt64("4294967296")); + assertEquals(9223372036854775807L, TextFormat.parseUInt64("9223372036854775807")); + assertEquals(-9223372036854775808L, TextFormat.parseUInt64("9223372036854775808")); assertEquals(-1L, TextFormat.parseUInt64("18446744073709551615")); // Hex assertEquals(0x1234abcd, TextFormat.parseInt32("0x1234abcd")); assertEquals(-0x1234abcd, TextFormat.parseInt32("-0x1234abcd")); assertEquals(-1, TextFormat.parseUInt64("0xffffffffffffffff")); - assertEquals(0x7fffffffffffffffL, - TextFormat.parseInt64("0x7fffffffffffffff")); + assertEquals(0x7fffffffffffffffL, TextFormat.parseInt64("0x7fffffffffffffff")); // Octal assertEquals(01234567, TextFormat.parseInt32("01234567")); @@ -815,26 +765,26 @@ public class TextFormatTest extends TestCase { public void testParseLongString() throws Exception { String longText = - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890"; + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890" + + "123456789012345678901234567890123456789012345678901234567890"; TestAllTypes.Builder builder = TestAllTypes.newBuilder(); TextFormat.merge("optional_string: \"" + longText + "\"", builder); @@ -843,16 +793,16 @@ public class TextFormatTest extends TestCase { public void testParseBoolean() throws Exception { String goodText = - "repeated_bool: t repeated_bool : 0\n" + - "repeated_bool :f repeated_bool:1\n" + - "repeated_bool: False repeated_bool: True"; + "repeated_bool: t repeated_bool : 0\n" + + "repeated_bool :f repeated_bool:1\n" + + "repeated_bool: False repeated_bool: True"; String goodTextCanonical = - "repeated_bool: true\n" + - "repeated_bool: false\n" + - "repeated_bool: false\n" + - "repeated_bool: true\n" + - "repeated_bool: false\n" + - "repeated_bool: true\n"; + "repeated_bool: true\n" + + "repeated_bool: false\n" + + "repeated_bool: false\n" + + "repeated_bool: true\n" + + "repeated_bool: false\n" + + "repeated_bool: true\n"; TestAllTypes.Builder builder = TestAllTypes.newBuilder(); TextFormat.merge(goodText, builder); assertEquals(goodTextCanonical, builder.build().toString()); @@ -881,83 +831,75 @@ public class TextFormatTest extends TestCase { public void testPrintFieldValue() throws Exception { assertPrintFieldValue("\"Hello\"", "Hello", "repeated_string"); - assertPrintFieldValue("123.0", 123f, "repeated_float"); - assertPrintFieldValue("123.0", 123d, "repeated_double"); - assertPrintFieldValue("123", 123, "repeated_int32"); - assertPrintFieldValue("123", 123L, "repeated_int64"); - assertPrintFieldValue("true", true, "repeated_bool"); + assertPrintFieldValue("123.0", 123f, "repeated_float"); + assertPrintFieldValue("123.0", 123d, "repeated_double"); + assertPrintFieldValue("123", 123, "repeated_int32"); + assertPrintFieldValue("123", 123L, "repeated_int64"); + assertPrintFieldValue("true", true, "repeated_bool"); assertPrintFieldValue("4294967295", 0xFFFFFFFF, "repeated_uint32"); - assertPrintFieldValue("18446744073709551615", 0xFFFFFFFFFFFFFFFFL, - "repeated_uint64"); - assertPrintFieldValue("\"\\001\\002\\003\"", - ByteString.copyFrom(new byte[] {1, 2, 3}), "repeated_bytes"); + assertPrintFieldValue("18446744073709551615", 0xFFFFFFFFFFFFFFFFL, "repeated_uint64"); + assertPrintFieldValue( + "\"\\001\\002\\003\"", ByteString.copyFrom(new byte[] {1, 2, 3}), "repeated_bytes"); } - private void assertPrintFieldValue(String expect, Object value, - String fieldName) throws Exception { + private void assertPrintFieldValue(String expect, Object value, String fieldName) + throws Exception { StringBuilder sb = new StringBuilder(); - TextFormat.printFieldValue( - TestAllTypes.getDescriptor().findFieldByName(fieldName), - value, sb); + TextFormat.printFieldValue(TestAllTypes.getDescriptor().findFieldByName(fieldName), value, sb); assertEquals(expect, sb.toString()); } public void testShortDebugString() { - assertEquals("optional_nested_message { bb: 42 } repeated_int32: 1" - + " repeated_uint32: 2", - TextFormat.shortDebugString(TestAllTypes.newBuilder() - .addRepeatedInt32(1) - .addRepeatedUint32(2) - .setOptionalNestedMessage( - NestedMessage.newBuilder().setBb(42).build()) - .build())); + assertEquals( + "optional_nested_message { bb: 42 } repeated_int32: 1 repeated_uint32: 2", + TextFormat.shortDebugString( + TestAllTypes.newBuilder() + .addRepeatedInt32(1) + .addRepeatedUint32(2) + .setOptionalNestedMessage(NestedMessage.newBuilder().setBb(42).build()) + .build())); } public void testShortDebugString_field() { - final FieldDescriptor dataField = - OneString.getDescriptor().findFieldByName("data"); - assertEquals( - "data: \"test data\"", - TextFormat.shortDebugString(dataField, "test data")); + final FieldDescriptor dataField = OneString.getDescriptor().findFieldByName("data"); + assertEquals("data: \"test data\"", TextFormat.shortDebugString(dataField, "test data")); final FieldDescriptor optionalField = - TestAllTypes.getDescriptor().findFieldByName("optional_nested_message"); + TestAllTypes.getDescriptor().findFieldByName("optional_nested_message"); final Object value = NestedMessage.newBuilder().setBb(42).build(); assertEquals( - "optional_nested_message { bb: 42 }", - TextFormat.shortDebugString(optionalField, value)); + "optional_nested_message { bb: 42 }", TextFormat.shortDebugString(optionalField, value)); } public void testShortDebugString_unknown() { - assertEquals("5: 1 5: 0x00000002 5: 0x0000000000000003 5: \"4\" 5: { 12: 6 } 5 { 10: 5 }" - + " 8: 1 8: 2 8: 3 15: 12379813812177893520 15: 0xabcd1234 15:" - + " 0xabcdef1234567890", + assertEquals( + "5: 1 5: 0x00000002 5: 0x0000000000000003 5: \"4\" 5: { 12: 6 } 5 { 10: 5 }" + + " 8: 1 8: 2 8: 3 15: 12379813812177893520 15: 0xabcd1234 15:" + + " 0xabcdef1234567890", TextFormat.shortDebugString(makeUnknownFieldSet())); } public void testPrintToUnicodeString() throws Exception { assertEquals( - "optional_string: \"abc\u3042efg\"\n" + - "optional_bytes: \"\\343\\201\\202\"\n" + - "repeated_string: \"\u3093XYZ\"\n", - TextFormat.printToUnicodeString(TestAllTypes.newBuilder() - .setOptionalString("abc\u3042efg") - .setOptionalBytes(bytes(0xe3, 0x81, 0x82)) - .addRepeatedString("\u3093XYZ") - .build())); + "optional_string: \"abc\u3042efg\"\n" + + "optional_bytes: \"\\343\\201\\202\"\n" + + "repeated_string: \"\u3093XYZ\"\n", + TextFormat.printToUnicodeString( + TestAllTypes.newBuilder() + .setOptionalString("abc\u3042efg") + .setOptionalBytes(bytes(0xe3, 0x81, 0x82)) + .addRepeatedString("\u3093XYZ") + .build())); // Double quotes and backslashes should be escaped assertEquals( "optional_string: \"a\\\\bc\\\"ef\\\"g\"\n", - TextFormat.printToUnicodeString(TestAllTypes.newBuilder() - .setOptionalString("a\\bc\"ef\"g") - .build())); + TextFormat.printToUnicodeString( + TestAllTypes.newBuilder().setOptionalString("a\\bc\"ef\"g").build())); // Test escaping roundtrip - TestAllTypes message = TestAllTypes.newBuilder() - .setOptionalString("a\\bc\\\"ef\"g") - .build(); + TestAllTypes message = TestAllTypes.newBuilder().setOptionalString("a\\bc\\\"ef\"g").build(); TestAllTypes.Builder builder = TestAllTypes.newBuilder(); TextFormat.merge(TextFormat.printToUnicodeString(message), builder); assertEquals(message.getOptionalString(), builder.getOptionalString()); @@ -965,35 +907,34 @@ public class TextFormatTest extends TestCase { public void testPrintToUnicodeStringWithNewlines() throws Exception { // No newlines at start and end - assertEquals("optional_string: \"test newlines\\n\\nin\\nstring\"\n", - TextFormat.printToUnicodeString(TestAllTypes.newBuilder() - .setOptionalString("test newlines\n\nin\nstring") - .build())); + assertEquals( + "optional_string: \"test newlines\\n\\nin\\nstring\"\n", + TextFormat.printToUnicodeString( + TestAllTypes.newBuilder().setOptionalString("test newlines\n\nin\nstring").build())); // Newlines at start and end - assertEquals("optional_string: \"\\ntest\\nnewlines\\n\\nin\\nstring\\n\"\n", - TextFormat.printToUnicodeString(TestAllTypes.newBuilder() - .setOptionalString("\ntest\nnewlines\n\nin\nstring\n") - .build())); + assertEquals( + "optional_string: \"\\ntest\\nnewlines\\n\\nin\\nstring\\n\"\n", + TextFormat.printToUnicodeString( + TestAllTypes.newBuilder() + .setOptionalString("\ntest\nnewlines\n\nin\nstring\n") + .build())); // Strings with 0, 1 and 2 newlines. - assertEquals("optional_string: \"\"\n", - TextFormat.printToUnicodeString(TestAllTypes.newBuilder() - .setOptionalString("") - .build())); - assertEquals("optional_string: \"\\n\"\n", - TextFormat.printToUnicodeString(TestAllTypes.newBuilder() - .setOptionalString("\n") - .build())); - assertEquals("optional_string: \"\\n\\n\"\n", - TextFormat.printToUnicodeString(TestAllTypes.newBuilder() - .setOptionalString("\n\n") - .build())); + assertEquals( + "optional_string: \"\"\n", + TextFormat.printToUnicodeString(TestAllTypes.newBuilder().setOptionalString("").build())); + assertEquals( + "optional_string: \"\\n\"\n", + TextFormat.printToUnicodeString(TestAllTypes.newBuilder().setOptionalString("\n").build())); + assertEquals( + "optional_string: \"\\n\\n\"\n", + TextFormat.printToUnicodeString( + TestAllTypes.newBuilder().setOptionalString("\n\n").build())); // Test escaping roundtrip - TestAllTypes message = TestAllTypes.newBuilder() - .setOptionalString("\ntest\nnewlines\n\nin\nstring\n") - .build(); + TestAllTypes message = + TestAllTypes.newBuilder().setOptionalString("\ntest\nnewlines\n\nin\nstring\n").build(); TestAllTypes.Builder builder = TestAllTypes.newBuilder(); TextFormat.merge(TextFormat.printToUnicodeString(message), builder); assertEquals(message.getOptionalString(), builder.getOptionalString()); @@ -1002,57 +943,51 @@ public class TextFormatTest extends TestCase { public void testPrintToUnicodeString_unknown() { assertEquals( "1: \"\\343\\201\\202\"\n", - TextFormat.printToUnicodeString(UnknownFieldSet.newBuilder() - .addField(1, - UnknownFieldSet.Field.newBuilder() - .addLengthDelimited(bytes(0xe3, 0x81, 0x82)).build()) - .build())); + TextFormat.printToUnicodeString( + UnknownFieldSet.newBuilder() + .addField( + 1, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited(bytes(0xe3, 0x81, 0x82)) + .build()) + .build())); } // See additional coverage in testOneofOverwriteForbidden and testMapOverwriteForbidden. public void testParseNonRepeatedFields() throws Exception { + assertParseSuccessWithOverwriteForbidden("repeated_int32: 1\nrepeated_int32: 2\n"); + assertParseSuccessWithOverwriteForbidden("RepeatedGroup { a: 1 }\nRepeatedGroup { a: 2 }\n"); assertParseSuccessWithOverwriteForbidden( - "repeated_int32: 1\n" + - "repeated_int32: 2\n"); - assertParseSuccessWithOverwriteForbidden( - "RepeatedGroup { a: 1 }\n" + - "RepeatedGroup { a: 2 }\n"); - assertParseSuccessWithOverwriteForbidden( - "repeated_nested_message { bb: 1 }\n" + - "repeated_nested_message { bb: 2 }\n"); + "repeated_nested_message { bb: 1 }\nrepeated_nested_message { bb: 2 }\n"); assertParseErrorWithOverwriteForbidden( - "3:17: Non-repeated field " + - "\"protobuf_unittest.TestAllTypes.optional_int32\" " + - "cannot be overwritten.", - "optional_int32: 1\n" + - "optional_bool: true\n" + - "optional_int32: 1\n"); + "3:17: Non-repeated field " + + "\"protobuf_unittest.TestAllTypes.optional_int32\" " + + "cannot be overwritten.", + "optional_int32: 1\noptional_bool: true\noptional_int32: 1\n"); assertParseErrorWithOverwriteForbidden( - "2:17: Non-repeated field " + - "\"protobuf_unittest.TestAllTypes.optionalgroup\" " + - "cannot be overwritten.", - "OptionalGroup { a: 1 }\n" + - "OptionalGroup { }\n"); + "2:17: Non-repeated field " + + "\"protobuf_unittest.TestAllTypes.optionalgroup\" " + + "cannot be overwritten.", + "OptionalGroup { a: 1 }\nOptionalGroup { }\n"); assertParseErrorWithOverwriteForbidden( - "2:33: Non-repeated field " + - "\"protobuf_unittest.TestAllTypes.optional_nested_message\" " + - "cannot be overwritten.", - "optional_nested_message { }\n" + - "optional_nested_message { bb: 3 }\n"); + "2:33: Non-repeated field " + + "\"protobuf_unittest.TestAllTypes.optional_nested_message\" " + + "cannot be overwritten.", + "optional_nested_message { }\noptional_nested_message { bb: 3 }\n"); assertParseErrorWithOverwriteForbidden( - "2:16: Non-repeated field " + - "\"protobuf_unittest.TestAllTypes.default_int32\" " + - "cannot be overwritten.", - "default_int32: 41\n" + // the default value - "default_int32: 41\n"); + "2:16: Non-repeated field " + + "\"protobuf_unittest.TestAllTypes.default_int32\" " + + "cannot be overwritten.", + "default_int32: 41\n" + + // the default value + "default_int32: 41\n"); assertParseErrorWithOverwriteForbidden( - "2:17: Non-repeated field " + - "\"protobuf_unittest.TestAllTypes.default_string\" " + - "cannot be overwritten.", - "default_string: \"zxcv\"\n" + - "default_string: \"asdf\"\n"); + "2:17: Non-repeated field " + + "\"protobuf_unittest.TestAllTypes.default_string\" " + + "cannot be overwritten.", + "default_string: \"zxcv\"\ndefault_string: \"asdf\"\n"); } public void testParseShortRepeatedFormOfRepeatedFields() throws Exception { @@ -1073,27 +1008,20 @@ public class TextFormatTest extends TestCase { public void testParseShortRepeatedFormWithTrailingComma() throws Exception { assertParseErrorWithOverwriteForbidden( - "1:38: Expected identifier. Found \']\'", - "repeated_foreign_enum: [FOREIGN_FOO, ]\n"); + "1:38: Expected identifier. Found \']\'", "repeated_foreign_enum: [FOREIGN_FOO, ]\n"); assertParseErrorWithOverwriteForbidden( - "1:22: Couldn't parse integer: For input string: \"]\"", - "repeated_int32: [ 1, ]\n"); + "1:22: Couldn't parse integer: For input string: \"]\"", "repeated_int32: [ 1, ]\n"); + assertParseErrorWithOverwriteForbidden("1:25: Expected \"{\".", "RepeatedGroup [{ a: 1 },]\n"); assertParseErrorWithOverwriteForbidden( - "1:25: Expected \"{\".", - "RepeatedGroup [{ a: 1 },]\n"); - assertParseErrorWithOverwriteForbidden( - "1:37: Expected \"{\".", - "repeated_nested_message [{ bb: 1 }, ]\n"); + "1:37: Expected \"{\".", "repeated_nested_message [{ bb: 1 }, ]\n"); // See also testMapShortFormTrailingComma. } public void testParseShortRepeatedFormOfNonRepeatedFields() throws Exception { assertParseErrorWithOverwriteForbidden( - "1:17: Couldn't parse integer: For input string: \"[\"", - "optional_int32: [1]\n"); + "1:17: Couldn't parse integer: For input string: \"[\"", "optional_int32: [1]\n"); assertParseErrorWithOverwriteForbidden( - "1:17: Couldn't parse integer: For input string: \"[\"", - "optional_int32: []\n"); + "1:17: Couldn't parse integer: For input string: \"[\"", "optional_int32: []\n"); } // ======================================================================= @@ -1115,9 +1043,11 @@ public class TextFormatTest extends TestCase { parserWithOverwriteForbidden.merge(input, TestUtil.getFullExtensionRegistry(), builder); fail("Expected parse exception."); } catch (TextFormat.ParseException e) { - assertEquals("1:36: Field \"protobuf_unittest.TestOneof2.foo_int\"" - + " is specified along with field \"protobuf_unittest.TestOneof2.foo_string\"," - + " another member of oneof \"foo\".", e.getMessage()); + assertEquals( + "1:36: Field \"protobuf_unittest.TestOneof2.foo_int\"" + + " is specified along with field \"protobuf_unittest.TestOneof2.foo_string\"," + + " another member of oneof \"foo\".", + e.getMessage()); } } @@ -1157,8 +1087,8 @@ public class TextFormatTest extends TestCase { public void testMapShortForm() throws Exception { String text = "string_to_int32_field [{ key: 'x' value: 10 }, { key: 'y' value: 20 }]\n" - + "int32_to_message_field " - + "[{ key: 1 value { value: 100 } }, { key: 2 value: { value: 200 } }]\n"; + + "int32_to_message_field " + + "[{ key: 1 value { value: 100 } }, { key: 2 value: { value: 200 } }]\n"; TestMap.Builder dest = TestMap.newBuilder(); parserWithOverwriteForbidden.merge(text, dest); TestMap message = dest.build(); @@ -1169,8 +1099,7 @@ public class TextFormatTest extends TestCase { } public void testMapShortFormEmpty() throws Exception { - String text = "string_to_int32_field []\n" - + "int32_to_message_field: []\n"; + String text = "string_to_int32_field []\nint32_to_message_field: []\n"; TestMap.Builder dest = TestMap.newBuilder(); parserWithOverwriteForbidden.merge(text, dest); TestMap message = dest.build(); @@ -1231,19 +1160,19 @@ public class TextFormatTest extends TestCase { final String stringData = "optional_int32: 1\n" - + "optional_int64: 2\n" - + " optional_double: 2.4\n" - + "repeated_int32: 5\n" - + "repeated_int32: 10\n" - + "optional_nested_message <\n" - + " bb: 78\n" - + ">\n" - + "repeated_nested_message <\n" - + " bb: 79\n" - + ">\n" - + "repeated_nested_message <\n" - + " bb: 80\n" - + ">"; + + "optional_int64: 2\n" + + " optional_double: 2.4\n" + + "repeated_int32: 5\n" + + "repeated_int32: 10\n" + + "optional_nested_message <\n" + + " bb: 78\n" + + ">\n" + + "repeated_nested_message <\n" + + " bb: 79\n" + + ">\n" + + "repeated_nested_message <\n" + + " bb: 80\n" + + ">"; parser.merge(stringData, builder); TextFormatParseInfoTree tree = treeBuilder.build(); @@ -1303,9 +1232,7 @@ public class TextFormatTest extends TestCase { fail( String.format( "Tree/descriptor/fieldname did not contain index %d, line %d column %d expected", - index, - line, - column)); + index, line, column)); } } } diff --git a/java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java b/java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java index 88cbbf862c..cc18547bb3 100644 --- a/java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java +++ b/java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java @@ -39,8 +39,7 @@ import com.google.protobuf.TextFormat.ParseException; import junit.framework.TestCase; /** - * Unit tests for protos that keep unknown enum values rather than discard - * them as unknown fields. + * Unit tests for protos that keep unknown enum values rather than discard them as unknown fields. */ public class UnknownEnumValueTest extends TestCase { public void testUnknownEnumValues() throws Exception { @@ -58,7 +57,7 @@ public class UnknownEnumValueTest extends TestCase { assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, message.getRepeatedNestedEnum(0)); assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, message.getRepeatedNestedEnumList().get(0)); assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, message.getPackedNestedEnum(0)); - + // Test serialization and parsing. ByteString data = message.toByteString(); message = TestAllTypes.parseFrom(data); @@ -71,19 +70,19 @@ public class UnknownEnumValueTest extends TestCase { assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, message.getRepeatedNestedEnum(0)); assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, message.getRepeatedNestedEnumList().get(0)); assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, message.getPackedNestedEnum(0)); - + // Test toBuilder(). builder = message.toBuilder(); assertEquals(4321, builder.getOptionalNestedEnumValue()); assertEquals(5432, builder.getRepeatedNestedEnumValue(0)); assertEquals(5432, builder.getRepeatedNestedEnumValueList().get(0).intValue()); - assertEquals(6543, builder.getPackedNestedEnumValue(0)); + assertEquals(6543, builder.getPackedNestedEnumValue(0)); // Returns UNRECOGNIZED if an enum type is requested. assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getOptionalNestedEnum()); assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getRepeatedNestedEnum(0)); assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getRepeatedNestedEnumList().get(0)); assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getPackedNestedEnum(0)); - + // Test mergeFrom(). builder = TestAllTypes.newBuilder().mergeFrom(message); assertEquals(4321, builder.getOptionalNestedEnumValue()); @@ -95,7 +94,7 @@ public class UnknownEnumValueTest extends TestCase { assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getRepeatedNestedEnum(0)); assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getRepeatedNestedEnumList().get(0)); assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getPackedNestedEnum(0)); - + // Test equals() and hashCode() TestAllTypes sameMessage = builder.build(); assertEquals(message, sameMessage); @@ -123,7 +122,7 @@ public class UnknownEnumValueTest extends TestCase { // Expected. } } - + public void testUnknownEnumValueInReflectionApi() throws Exception { Descriptor descriptor = TestAllTypes.getDescriptor(); FieldDescriptor optionalNestedEnumField = descriptor.findFieldByName("optional_nested_enum"); @@ -132,14 +131,13 @@ public class UnknownEnumValueTest extends TestCase { EnumDescriptor enumType = TestAllTypes.NestedEnum.getDescriptor(); TestAllTypes.Builder builder = TestAllTypes.newBuilder(); - builder.setField(optionalNestedEnumField, - enumType.findValueByNumberCreatingIfUnknown(4321)); - builder.addRepeatedField(repeatedNestedEnumField, - enumType.findValueByNumberCreatingIfUnknown(5432)); - builder.addRepeatedField(packedNestedEnumField, - enumType.findValueByNumberCreatingIfUnknown(6543)); + builder.setField(optionalNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(4321)); + builder.addRepeatedField( + repeatedNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(5432)); + builder.addRepeatedField( + packedNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(6543)); TestAllTypes message = builder.build(); - + // Getters will return unknown enum values as EnumValueDescriptor. EnumValueDescriptor unknown4321 = (EnumValueDescriptor) message.getField(optionalNestedEnumField); @@ -166,79 +164,78 @@ public class UnknownEnumValueTest extends TestCase { message = builder.build(); // Like other descriptors, unknown EnumValueDescriptor can be compared by // object identity. - assertTrue(unknown6543 == message.getField(optionalNestedEnumField)); - assertTrue(unknown4321 == message.getRepeatedField(repeatedNestedEnumField, 0)); - assertTrue(unknown5432 == message.getRepeatedField(packedNestedEnumField, 0)); + assertSame(message.getField(optionalNestedEnumField), unknown6543); + assertSame(message.getRepeatedField(repeatedNestedEnumField, 0), unknown4321); + assertSame(message.getRepeatedField(packedNestedEnumField, 0), unknown5432); } - + public void testUnknownEnumValueWithDynamicMessage() throws Exception { Descriptor descriptor = TestAllTypes.getDescriptor(); FieldDescriptor optionalNestedEnumField = descriptor.findFieldByName("optional_nested_enum"); FieldDescriptor repeatedNestedEnumField = descriptor.findFieldByName("repeated_nested_enum"); FieldDescriptor packedNestedEnumField = descriptor.findFieldByName("packed_nested_enum"); EnumDescriptor enumType = TestAllTypes.NestedEnum.getDescriptor(); - + Message dynamicMessageDefaultInstance = DynamicMessage.getDefaultInstance(descriptor); Message.Builder builder = dynamicMessageDefaultInstance.newBuilderForType(); - builder.setField(optionalNestedEnumField, - enumType.findValueByNumberCreatingIfUnknown(4321)); - builder.addRepeatedField(repeatedNestedEnumField, - enumType.findValueByNumberCreatingIfUnknown(5432)); - builder.addRepeatedField(packedNestedEnumField, - enumType.findValueByNumberCreatingIfUnknown(6543)); + builder.setField(optionalNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(4321)); + builder.addRepeatedField( + repeatedNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(5432)); + builder.addRepeatedField( + packedNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(6543)); Message message = builder.build(); - assertEquals(4321, - ((EnumValueDescriptor) message.getField(optionalNestedEnumField)).getNumber()); - assertEquals(5432, + assertEquals( + 4321, ((EnumValueDescriptor) message.getField(optionalNestedEnumField)).getNumber()); + assertEquals( + 5432, ((EnumValueDescriptor) message.getRepeatedField(repeatedNestedEnumField, 0)).getNumber()); - assertEquals(6543, + assertEquals( + 6543, ((EnumValueDescriptor) message.getRepeatedField(packedNestedEnumField, 0)).getNumber()); - + // Test reflection based serialization/parsing implementation. ByteString data = message.toByteString(); - message = dynamicMessageDefaultInstance - .newBuilderForType() - .mergeFrom(data) - .build(); - assertEquals(4321, - ((EnumValueDescriptor) message.getField(optionalNestedEnumField)).getNumber()); - assertEquals(5432, + message = dynamicMessageDefaultInstance.newBuilderForType().mergeFrom(data).build(); + assertEquals( + 4321, ((EnumValueDescriptor) message.getField(optionalNestedEnumField)).getNumber()); + assertEquals( + 5432, ((EnumValueDescriptor) message.getRepeatedField(repeatedNestedEnumField, 0)).getNumber()); - assertEquals(6543, + assertEquals( + 6543, ((EnumValueDescriptor) message.getRepeatedField(packedNestedEnumField, 0)).getNumber()); - + // Test reflection based equals()/hashCode(). builder = dynamicMessageDefaultInstance.newBuilderForType(); - builder.setField(optionalNestedEnumField, - enumType.findValueByNumberCreatingIfUnknown(4321)); - builder.addRepeatedField(repeatedNestedEnumField, - enumType.findValueByNumberCreatingIfUnknown(5432)); - builder.addRepeatedField(packedNestedEnumField, - enumType.findValueByNumberCreatingIfUnknown(6543)); + builder.setField(optionalNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(4321)); + builder.addRepeatedField( + repeatedNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(5432)); + builder.addRepeatedField( + packedNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(6543)); Message sameMessage = builder.build(); assertEquals(message, sameMessage); assertEquals(message.hashCode(), sameMessage.hashCode()); - builder.setField(optionalNestedEnumField, - enumType.findValueByNumberCreatingIfUnknown(0)); + builder.setField(optionalNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(0)); Message differentMessage = builder.build(); assertFalse(message.equals(differentMessage)); } - + public void testUnknownEnumValuesInTextFormat() { TestAllTypes.Builder builder = TestAllTypes.newBuilder(); builder.setOptionalNestedEnumValue(4321); builder.addRepeatedNestedEnumValue(5432); builder.addPackedNestedEnumValue(6543); TestAllTypes message = builder.build(); - + // We can print a message with unknown enum values. String textData = TextFormat.printToString(message); assertEquals( "optional_nested_enum: UNKNOWN_ENUM_VALUE_NestedEnum_4321\n" - + "repeated_nested_enum: UNKNOWN_ENUM_VALUE_NestedEnum_5432\n" - + "packed_nested_enum: UNKNOWN_ENUM_VALUE_NestedEnum_6543\n", textData); - + + "repeated_nested_enum: UNKNOWN_ENUM_VALUE_NestedEnum_5432\n" + + "packed_nested_enum: UNKNOWN_ENUM_VALUE_NestedEnum_6543\n", + textData); + // Parsing unknown enum values will fail just like parsing other kinds of // unknown fields. try { diff --git a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java index 8ce0ca7362..a947d271b0 100644 --- a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java +++ b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java @@ -110,9 +110,7 @@ public class UnknownFieldSetLiteTest extends TestCase { } public void testMergeFieldFrom() throws IOException { - Foo foo = Foo.newBuilder() - .setValue(2) - .build(); + Foo foo = Foo.newBuilder().setValue(2).build(); CodedInputStream input = CodedInputStream.newInstance(foo.toByteArray()); @@ -123,9 +121,7 @@ public class UnknownFieldSetLiteTest extends TestCase { } public void testSerializedSize() throws IOException { - Foo foo = Foo.newBuilder() - .setValue(2) - .build(); + Foo foo = Foo.newBuilder().setValue(2).build(); CodedInputStream input = CodedInputStream.newInstance(foo.toByteArray()); @@ -136,9 +132,7 @@ public class UnknownFieldSetLiteTest extends TestCase { } public void testHashCodeAfterDeserialization() throws IOException { - Foo foo = Foo.newBuilder() - .setValue(2) - .build(); + Foo foo = Foo.newBuilder().setValue(2).build(); Foo fooDeserialized = Foo.parseFrom(foo.toByteArray()); @@ -172,8 +166,7 @@ public class UnknownFieldSetLiteTest extends TestCase { UnknownFieldSetLite builder = UnknownFieldSetLite.newInstance(); builder.mergeVarintField(10, -6); - CodedInputStream input = - CodedInputStream.newInstance(toByteString(builder).toByteArray()); + CodedInputStream input = CodedInputStream.newInstance(toByteString(builder).toByteArray()); int tag = input.readTag(); assertEquals(10, WireFormat.getTagFieldNumber(tag)); @@ -217,8 +210,9 @@ public class UnknownFieldSetLiteTest extends TestCase { } public void testMutableCopyOf_empty() { - UnknownFieldSetLite unknownFields = UnknownFieldSetLite.mutableCopyOf( - UnknownFieldSetLite.getDefaultInstance(), UnknownFieldSetLite.getDefaultInstance()); + UnknownFieldSetLite unknownFields = + UnknownFieldSetLite.mutableCopyOf( + UnknownFieldSetLite.getDefaultInstance(), UnknownFieldSetLite.getDefaultInstance()); unknownFields.checkMutable(); assertEquals(0, unknownFields.getSerializedSize()); @@ -226,18 +220,17 @@ public class UnknownFieldSetLiteTest extends TestCase { } public void testRoundTrips() throws InvalidProtocolBufferException { - Foo foo = Foo.newBuilder() - .setValue(1) - .setExtension(Bar.fooExt, Bar.newBuilder() - .setName("name") - .build()) - .setExtension(LiteEqualsAndHash.varint, 22) - .setExtension(LiteEqualsAndHash.fixed32, 44) - .setExtension(LiteEqualsAndHash.fixed64, 66L) - .setExtension(LiteEqualsAndHash.myGroup, LiteEqualsAndHash.MyGroup.newBuilder() - .setGroupValue("value") - .build()) - .build(); + Foo foo = + Foo.newBuilder() + .setValue(1) + .setExtension(Bar.fooExt, Bar.newBuilder().setName("name").build()) + .setExtension(LiteEqualsAndHash.varint, 22) + .setExtension(LiteEqualsAndHash.fixed32, 44) + .setExtension(LiteEqualsAndHash.fixed64, 66L) + .setExtension( + LiteEqualsAndHash.myGroup, + LiteEqualsAndHash.MyGroup.newBuilder().setGroupValue("value").build()) + .build(); Foo copy = Foo.parseFrom(foo.toByteArray()); @@ -310,16 +303,15 @@ public class UnknownFieldSetLiteTest extends TestCase { } public void testTruncatedInput() { - Foo foo = Foo.newBuilder() - .setValue(1) - .setExtension(Bar.fooExt, Bar.newBuilder() - .setName("name") - .build()) - .setExtension(LiteEqualsAndHash.varint, 22) - .setExtension(LiteEqualsAndHash.myGroup, LiteEqualsAndHash.MyGroup.newBuilder() - .setGroupValue("value") - .build()) - .build(); + Foo foo = + Foo.newBuilder() + .setValue(1) + .setExtension(Bar.fooExt, Bar.newBuilder().setName("name").build()) + .setExtension(LiteEqualsAndHash.varint, 22) + .setExtension( + LiteEqualsAndHash.myGroup, + LiteEqualsAndHash.MyGroup.newBuilder().setGroupValue("value").build()) + .build(); try { Foo.parseFrom(foo.toByteString().substring(0, foo.toByteString().size() - 10)); @@ -328,63 +320,72 @@ public class UnknownFieldSetLiteTest extends TestCase { // Expected. } } - + public void testMakeImmutable() throws Exception { UnknownFieldSetLite unknownFields = UnknownFieldSetLite.newInstance(); unknownFields.makeImmutable(); - + try { unknownFields.mergeVarintField(1, 1); fail(); - } catch (UnsupportedOperationException expected) {} - + } catch (UnsupportedOperationException expected) { + } + try { unknownFields.mergeLengthDelimitedField(2, ByteString.copyFromUtf8("hello")); fail(); - } catch (UnsupportedOperationException expected) {} - + } catch (UnsupportedOperationException expected) { + } + try { unknownFields.mergeFieldFrom(1, CodedInputStream.newInstance(new byte[0])); fail(); - } catch (UnsupportedOperationException expected) {} + } catch (UnsupportedOperationException expected) { + } } - + public void testEndToEnd() throws Exception { TestAllTypesLite testAllTypes = TestAllTypesLite.getDefaultInstance(); try { testAllTypes.unknownFields.checkMutable(); fail(); - } catch (UnsupportedOperationException expected) {} - + } catch (UnsupportedOperationException expected) { + } + testAllTypes = TestAllTypesLite.parseFrom(new byte[0]); try { testAllTypes.unknownFields.checkMutable(); fail(); - } catch (UnsupportedOperationException expected) {} - + } catch (UnsupportedOperationException expected) { + } + testAllTypes = TestAllTypesLite.newBuilder().build(); try { testAllTypes.unknownFields.checkMutable(); fail(); - } catch (UnsupportedOperationException expected) {} - - testAllTypes = TestAllTypesLite.newBuilder() - .setDefaultBool(true) - .build(); + } catch (UnsupportedOperationException expected) { + } + + testAllTypes = TestAllTypesLite.newBuilder().setDefaultBool(true).build(); try { testAllTypes.unknownFields.checkMutable(); fail(); - } catch (UnsupportedOperationException expected) {} - - TestAllExtensionsLite testAllExtensions = TestAllExtensionsLite.newBuilder() - .mergeFrom(TestAllExtensionsLite.newBuilder() - .setExtension(UnittestLite.optionalInt32ExtensionLite, 2) - .build().toByteArray()) - .build(); + } catch (UnsupportedOperationException expected) { + } + + TestAllExtensionsLite testAllExtensions = + TestAllExtensionsLite.newBuilder() + .mergeFrom( + TestAllExtensionsLite.newBuilder() + .setExtension(UnittestLite.optionalInt32ExtensionLite, 2) + .build() + .toByteArray()) + .build(); try { testAllExtensions.unknownFields.checkMutable(); fail(); - } catch (UnsupportedOperationException expected) {} + } catch (UnsupportedOperationException expected) { + } } private ByteString toByteString(UnknownFieldSetLite unknownFields) { diff --git a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java index 1a84806a46..86630f6504 100644 --- a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java +++ b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java @@ -69,13 +69,10 @@ public class UnknownFieldSetTest extends TestCase { ByteString getBizarroData() throws Exception { UnknownFieldSet.Builder bizarroFields = UnknownFieldSet.newBuilder(); - UnknownFieldSet.Field varintField = - UnknownFieldSet.Field.newBuilder().addVarint(1).build(); - UnknownFieldSet.Field fixed32Field = - UnknownFieldSet.Field.newBuilder().addFixed32(1).build(); + UnknownFieldSet.Field varintField = UnknownFieldSet.Field.newBuilder().addVarint(1).build(); + UnknownFieldSet.Field fixed32Field = UnknownFieldSet.Field.newBuilder().addFixed32(1).build(); - for (Map.Entry entry : - unknownFields.asMap().entrySet()) { + for (Map.Entry entry : unknownFields.asMap().entrySet()) { if (entry.getValue().getVarintList().isEmpty()) { // Original field is not a varint, so use a varint. bizarroFields.addField(entry.getKey(), varintField); @@ -102,34 +99,30 @@ public class UnknownFieldSetTest extends TestCase { public void testVarint() throws Exception { UnknownFieldSet.Field field = getField("optional_int32"); assertEquals(1, field.getVarintList().size()); - assertEquals(allFields.getOptionalInt32(), - (long) field.getVarintList().get(0)); + assertEquals(allFields.getOptionalInt32(), (long) field.getVarintList().get(0)); } public void testFixed32() throws Exception { UnknownFieldSet.Field field = getField("optional_fixed32"); assertEquals(1, field.getFixed32List().size()); - assertEquals(allFields.getOptionalFixed32(), - (int) field.getFixed32List().get(0)); + assertEquals(allFields.getOptionalFixed32(), (int) field.getFixed32List().get(0)); } public void testFixed64() throws Exception { UnknownFieldSet.Field field = getField("optional_fixed64"); assertEquals(1, field.getFixed64List().size()); - assertEquals(allFields.getOptionalFixed64(), - (long) field.getFixed64List().get(0)); + assertEquals(allFields.getOptionalFixed64(), (long) field.getFixed64List().get(0)); } public void testLengthDelimited() throws Exception { UnknownFieldSet.Field field = getField("optional_bytes"); assertEquals(1, field.getLengthDelimitedList().size()); - assertEquals(allFields.getOptionalBytes(), - field.getLengthDelimitedList().get(0)); + assertEquals(allFields.getOptionalBytes(), field.getLengthDelimitedList().get(0)); } public void testGroup() throws Exception { Descriptors.FieldDescriptor nestedFieldDescriptor = - TestAllTypes.OptionalGroup.getDescriptor().findFieldByName("a"); + TestAllTypes.OptionalGroup.getDescriptor().findFieldByName("a"); assertNotNull(nestedFieldDescriptor); UnknownFieldSet.Field field = getField("optionalgroup"); @@ -139,11 +132,9 @@ public class UnknownFieldSetTest extends TestCase { assertEquals(1, group.asMap().size()); assertTrue(group.hasField(nestedFieldDescriptor.getNumber())); - UnknownFieldSet.Field nestedField = - group.getField(nestedFieldDescriptor.getNumber()); + UnknownFieldSet.Field nestedField = group.getField(nestedFieldDescriptor.getNumber()); assertEquals(1, nestedField.getVarintList().size()); - assertEquals(allFields.getOptionalGroup().getA(), - (long) nestedField.getVarintList().get(0)); + assertEquals(allFields.getOptionalGroup().getA(), (long) nestedField.getVarintList().get(0)); } public void testSerialize() throws Exception { @@ -154,59 +145,44 @@ public class UnknownFieldSetTest extends TestCase { } public void testCopyFrom() throws Exception { - TestEmptyMessage message = - TestEmptyMessage.newBuilder().mergeFrom(emptyMessage).build(); + TestEmptyMessage message = TestEmptyMessage.newBuilder().mergeFrom(emptyMessage).build(); assertEquals(emptyMessage.toString(), message.toString()); } public void testMergeFrom() throws Exception { TestEmptyMessage source = - TestEmptyMessage.newBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField(2, - UnknownFieldSet.Field.newBuilder() - .addVarint(2).build()) - .addField(3, - UnknownFieldSet.Field.newBuilder() - .addVarint(4).build()) - .build()) - .build(); + TestEmptyMessage.newBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(2, UnknownFieldSet.Field.newBuilder().addVarint(2).build()) + .addField(3, UnknownFieldSet.Field.newBuilder().addVarint(4).build()) + .build()) + .build(); TestEmptyMessage destination = - TestEmptyMessage.newBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField(1, - UnknownFieldSet.Field.newBuilder() - .addVarint(1).build()) - .addField(3, - UnknownFieldSet.Field.newBuilder() - .addVarint(3).build()) - .build()) - .mergeFrom(source) - .build(); - - assertEquals( - "1: 1\n" + - "2: 2\n" + - "3: 3\n" + - "3: 4\n", - destination.toString()); + TestEmptyMessage.newBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(1, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .addField(3, UnknownFieldSet.Field.newBuilder().addVarint(3).build()) + .build()) + .mergeFrom(source) + .build(); + + assertEquals("1: 1\n2: 2\n3: 3\n3: 4\n", destination.toString()); } public void testClear() throws Exception { - UnknownFieldSet fields = - UnknownFieldSet.newBuilder().mergeFrom(unknownFields).clear().build(); + UnknownFieldSet fields = UnknownFieldSet.newBuilder().mergeFrom(unknownFields).clear().build(); assertTrue(fields.asMap().isEmpty()); } public void testClearMessage() throws Exception { TestEmptyMessage message = - TestEmptyMessage.newBuilder().mergeFrom(emptyMessage).clear().build(); + TestEmptyMessage.newBuilder().mergeFrom(emptyMessage).clear().build(); assertEquals(0, message.getSerializedSize()); } - + public void testClearField() throws Exception { int fieldNumber = unknownFields.asMap().keySet().iterator().next(); UnknownFieldSet fields = @@ -218,10 +194,9 @@ public class UnknownFieldSetTest extends TestCase { // Test mixing known and unknown fields when parsing. UnknownFieldSet fields = - UnknownFieldSet.newBuilder(unknownFields) - .addField(123456, - UnknownFieldSet.Field.newBuilder().addVarint(654321).build()) - .build(); + UnknownFieldSet.newBuilder(unknownFields) + .addField(123456, UnknownFieldSet.Field.newBuilder().addVarint(654321).build()) + .build(); ByteString data = fields.toByteString(); TestAllTypes destination = TestAllTypes.parseFrom(data); @@ -229,8 +204,7 @@ public class UnknownFieldSetTest extends TestCase { TestUtil.assertAllFieldsSet(destination); assertEquals(1, destination.getUnknownFields().asMap().size()); - UnknownFieldSet.Field field = - destination.getUnknownFields().getField(123456); + UnknownFieldSet.Field field = destination.getUnknownFields().getField(123456); assertEquals(1, field.getVarintList().size()); assertEquals(654321, (long) field.getVarintList().get(0)); } @@ -253,10 +227,9 @@ public class UnknownFieldSetTest extends TestCase { // they are declared as extension numbers. TestEmptyMessageWithExtensions message = - TestEmptyMessageWithExtensions.parseFrom(allFieldsData); + TestEmptyMessageWithExtensions.parseFrom(allFieldsData); - assertEquals(unknownFields.asMap().size(), - message.getUnknownFields().asMap().size()); + assertEquals(unknownFields.asMap().size(), message.getUnknownFields().asMap().size()); assertEquals(allFieldsData, message.toByteString()); } @@ -265,134 +238,99 @@ public class UnknownFieldSetTest extends TestCase { // when parsing extensions. ByteString bizarroData = getBizarroData(); - TestAllExtensions allExtensionsMessage = - TestAllExtensions.parseFrom(bizarroData); + TestAllExtensions allExtensionsMessage = TestAllExtensions.parseFrom(bizarroData); TestEmptyMessage emptyMessage = TestEmptyMessage.parseFrom(bizarroData); // All fields should have been interpreted as unknown, so the debug strings // should be the same. - assertEquals(emptyMessage.toString(), - allExtensionsMessage.toString()); + assertEquals(emptyMessage.toString(), allExtensionsMessage.toString()); } public void testParseUnknownEnumValue() throws Exception { Descriptors.FieldDescriptor singularField = - TestAllTypes.getDescriptor().findFieldByName("optional_nested_enum"); + TestAllTypes.getDescriptor().findFieldByName("optional_nested_enum"); Descriptors.FieldDescriptor repeatedField = - TestAllTypes.getDescriptor().findFieldByName("repeated_nested_enum"); + TestAllTypes.getDescriptor().findFieldByName("repeated_nested_enum"); assertNotNull(singularField); assertNotNull(repeatedField); ByteString data = - UnknownFieldSet.newBuilder() - .addField(singularField.getNumber(), - UnknownFieldSet.Field.newBuilder() - .addVarint(TestAllTypes.NestedEnum.BAR.getNumber()) - .addVarint(5) // not valid - .build()) - .addField(repeatedField.getNumber(), - UnknownFieldSet.Field.newBuilder() - .addVarint(TestAllTypes.NestedEnum.FOO.getNumber()) - .addVarint(4) // not valid - .addVarint(TestAllTypes.NestedEnum.BAZ.getNumber()) - .addVarint(6) // not valid - .build()) - .build() - .toByteString(); + UnknownFieldSet.newBuilder() + .addField( + singularField.getNumber(), + UnknownFieldSet.Field.newBuilder() + .addVarint(TestAllTypes.NestedEnum.BAR.getNumber()) + .addVarint(5) // not valid + .build()) + .addField( + repeatedField.getNumber(), + UnknownFieldSet.Field.newBuilder() + .addVarint(TestAllTypes.NestedEnum.FOO.getNumber()) + .addVarint(4) // not valid + .addVarint(TestAllTypes.NestedEnum.BAZ.getNumber()) + .addVarint(6) // not valid + .build()) + .build() + .toByteString(); { TestAllTypes message = TestAllTypes.parseFrom(data); - assertEquals(TestAllTypes.NestedEnum.BAR, - message.getOptionalNestedEnum()); + assertEquals(TestAllTypes.NestedEnum.BAR, message.getOptionalNestedEnum()); assertEquals( - Arrays.asList(TestAllTypes.NestedEnum.FOO, TestAllTypes.NestedEnum.BAZ), - message.getRepeatedNestedEnumList()); - assertEquals(Arrays.asList(5L), - message.getUnknownFields() - .getField(singularField.getNumber()) - .getVarintList()); - assertEquals(Arrays.asList(4L, 6L), - message.getUnknownFields() - .getField(repeatedField.getNumber()) - .getVarintList()); + Arrays.asList(TestAllTypes.NestedEnum.FOO, TestAllTypes.NestedEnum.BAZ), + message.getRepeatedNestedEnumList()); + assertEquals( + Arrays.asList(5L), + message.getUnknownFields().getField(singularField.getNumber()).getVarintList()); + assertEquals( + Arrays.asList(4L, 6L), + message.getUnknownFields().getField(repeatedField.getNumber()).getVarintList()); } { TestAllExtensions message = - TestAllExtensions.parseFrom(data, TestUtil.getExtensionRegistry()); - assertEquals(TestAllTypes.NestedEnum.BAR, - message.getExtension(UnittestProto.optionalNestedEnumExtension)); + TestAllExtensions.parseFrom(data, TestUtil.getExtensionRegistry()); + assertEquals( + TestAllTypes.NestedEnum.BAR, + message.getExtension(UnittestProto.optionalNestedEnumExtension)); + assertEquals( + Arrays.asList(TestAllTypes.NestedEnum.FOO, TestAllTypes.NestedEnum.BAZ), + message.getExtension(UnittestProto.repeatedNestedEnumExtension)); assertEquals( - Arrays.asList(TestAllTypes.NestedEnum.FOO, TestAllTypes.NestedEnum.BAZ), - message.getExtension(UnittestProto.repeatedNestedEnumExtension)); - assertEquals(Arrays.asList(5L), - message.getUnknownFields() - .getField(singularField.getNumber()) - .getVarintList()); - assertEquals(Arrays.asList(4L, 6L), - message.getUnknownFields() - .getField(repeatedField.getNumber()) - .getVarintList()); + Arrays.asList(5L), + message.getUnknownFields().getField(singularField.getNumber()).getVarintList()); + assertEquals( + Arrays.asList(4L, 6L), + message.getUnknownFields().getField(repeatedField.getNumber()).getVarintList()); } } public void testLargeVarint() throws Exception { ByteString data = - UnknownFieldSet.newBuilder() - .addField(1, - UnknownFieldSet.Field.newBuilder() - .addVarint(0x7FFFFFFFFFFFFFFFL) - .build()) - .build() - .toByteString(); + UnknownFieldSet.newBuilder() + .addField(1, UnknownFieldSet.Field.newBuilder().addVarint(0x7FFFFFFFFFFFFFFFL).build()) + .build() + .toByteString(); UnknownFieldSet parsed = UnknownFieldSet.parseFrom(data); UnknownFieldSet.Field field = parsed.getField(1); assertEquals(1, field.getVarintList().size()); - assertEquals(0x7FFFFFFFFFFFFFFFL, (long)field.getVarintList().get(0)); + assertEquals(0x7FFFFFFFFFFFFFFFL, (long) field.getVarintList().get(0)); } public void testEqualsAndHashCode() { - UnknownFieldSet.Field fixed32Field = - UnknownFieldSet.Field.newBuilder() - .addFixed32(1) - .build(); - UnknownFieldSet.Field fixed64Field = - UnknownFieldSet.Field.newBuilder() - .addFixed64(1) - .build(); - UnknownFieldSet.Field varIntField = - UnknownFieldSet.Field.newBuilder() - .addVarint(1) - .build(); + UnknownFieldSet.Field fixed32Field = UnknownFieldSet.Field.newBuilder().addFixed32(1).build(); + UnknownFieldSet.Field fixed64Field = UnknownFieldSet.Field.newBuilder().addFixed64(1).build(); + UnknownFieldSet.Field varIntField = UnknownFieldSet.Field.newBuilder().addVarint(1).build(); UnknownFieldSet.Field lengthDelimitedField = - UnknownFieldSet.Field.newBuilder() - .addLengthDelimited(ByteString.EMPTY) - .build(); + UnknownFieldSet.Field.newBuilder().addLengthDelimited(ByteString.EMPTY).build(); UnknownFieldSet.Field groupField = - UnknownFieldSet.Field.newBuilder() - .addGroup(unknownFields) - .build(); + UnknownFieldSet.Field.newBuilder().addGroup(unknownFields).build(); - UnknownFieldSet a = - UnknownFieldSet.newBuilder() - .addField(1, fixed32Field) - .build(); - UnknownFieldSet b = - UnknownFieldSet.newBuilder() - .addField(1, fixed64Field) - .build(); - UnknownFieldSet c = - UnknownFieldSet.newBuilder() - .addField(1, varIntField) - .build(); - UnknownFieldSet d = - UnknownFieldSet.newBuilder() - .addField(1, lengthDelimitedField) - .build(); - UnknownFieldSet e = - UnknownFieldSet.newBuilder() - .addField(1, groupField) - .build(); + UnknownFieldSet a = UnknownFieldSet.newBuilder().addField(1, fixed32Field).build(); + UnknownFieldSet b = UnknownFieldSet.newBuilder().addField(1, fixed64Field).build(); + UnknownFieldSet c = UnknownFieldSet.newBuilder().addField(1, varIntField).build(); + UnknownFieldSet d = UnknownFieldSet.newBuilder().addField(1, lengthDelimitedField).build(); + UnknownFieldSet e = UnknownFieldSet.newBuilder().addField(1, groupField).build(); checkEqualsIsConsistent(a); checkEqualsIsConsistent(b); @@ -413,12 +351,10 @@ public class UnknownFieldSetTest extends TestCase { } /** - * Asserts that the given field sets are not equal and have different - * hash codes. + * Asserts that the given field sets are not equal and have different hash codes. * - * @warning It's valid for non-equal objects to have the same hash code, so - * this test is stricter than it needs to be. However, this should happen - * relatively rarely. + * @warning It's valid for non-equal objects to have the same hash code, so this test is stricter + * than it needs to be. However, this should happen relatively rarely. */ private void checkNotEqual(UnknownFieldSet s1, UnknownFieldSet s2) { String equalsError = String.format("%s should not be equal to %s", s1, s2); @@ -430,9 +366,7 @@ public class UnknownFieldSetTest extends TestCase { s1.hashCode() == s2.hashCode()); } - /** - * Asserts that the given field sets are equal and have identical hash codes. - */ + /** Asserts that the given field sets are equal and have identical hash codes. */ private void checkEqualsIsConsistent(UnknownFieldSet set) { // Object should be equal to itself. assertEquals(set, set); diff --git a/java/core/src/test/java/com/google/protobuf/WireFormatTest.java b/java/core/src/test/java/com/google/protobuf/WireFormatTest.java index 425b56da16..45a396acd8 100644 --- a/java/core/src/test/java/com/google/protobuf/WireFormatTest.java +++ b/java/core/src/test/java/com/google/protobuf/WireFormatTest.java @@ -54,6 +54,13 @@ import junit.framework.TestCase; * @author kenton@google.com (Kenton Varda) */ public class WireFormatTest extends TestCase { + + private static final int TYPE_ID_1 = + TestMessageSetExtension1.getDescriptor().getExtensions().get(0).getNumber(); + private static final int TYPE_ID_2 = + TestMessageSetExtension2.getDescriptor().getExtensions().get(0).getNumber(); + private static final int UNKNOWN_TYPE_ID = 1550055; + public void testSerialization() throws Exception { TestAllTypes message = TestUtil.getAllSet(); @@ -102,8 +109,7 @@ public class WireFormatTest extends TestCase { assertEquals(rawBytes, rawBytes2); } - public void testSerializationPackedWithoutGetSerializedSize() - throws Exception { + public void testSerializationPackedWithoutGetSerializedSize() throws Exception { // Write directly to an OutputStream, without invoking getSerializedSize() // This used to be a bug where the size of a packed field was incorrect, // since getSerializedSize() was never invoked. @@ -118,8 +124,7 @@ public class WireFormatTest extends TestCase { codedOutput.flush(); - TestPackedTypes message2 = TestPackedTypes.parseFrom( - outputStream.toByteArray()); + TestPackedTypes message2 = TestPackedTypes.parseFrom(outputStream.toByteArray()); TestUtil.assertPackedFieldsSet(message2); } @@ -134,8 +139,7 @@ public class WireFormatTest extends TestCase { ExtensionRegistryLite registry = TestUtil.getExtensionRegistry(); - TestAllExtensions message2 = - TestAllExtensions.parseFrom(rawBytes, registry); + TestAllExtensions message2 = TestAllExtensions.parseFrom(rawBytes, registry); TestUtil.assertAllExtensionsSet(message2); } @@ -147,8 +151,7 @@ public class WireFormatTest extends TestCase { ExtensionRegistryLite registry = TestUtil.getExtensionRegistry(); - TestPackedExtensions message2 = - TestPackedExtensions.parseFrom(rawBytes, registry); + TestPackedExtensions message2 = TestPackedExtensions.parseFrom(rawBytes, registry); TestUtil.assertPackedExtensionsSet(message2); } @@ -192,25 +195,27 @@ public class WireFormatTest extends TestCase { // Tests that fields are written in order even when extension ranges // are interleaved with field numbers. ByteString data = - TestFieldOrderings.newBuilder() - .setMyInt(1) - .setMyString("foo") - .setMyFloat(1.0F) - .setExtension(UnittestProto.myExtensionInt, 23) - .setExtension(UnittestProto.myExtensionString, "bar") - .build().toByteString(); + TestFieldOrderings.newBuilder() + .setMyInt(1) + .setMyString("foo") + .setMyFloat(1.0F) + .setExtension(UnittestProto.myExtensionInt, 23) + .setExtension(UnittestProto.myExtensionString, "bar") + .build() + .toByteString(); assertFieldsInOrder(data); Descriptors.Descriptor descriptor = TestFieldOrderings.getDescriptor(); - ByteString dynamic_data = - DynamicMessage.newBuilder(TestFieldOrderings.getDescriptor()) - .setField(descriptor.findFieldByName("my_int"), 1L) - .setField(descriptor.findFieldByName("my_string"), "foo") - .setField(descriptor.findFieldByName("my_float"), 1.0F) - .setField(UnittestProto.myExtensionInt.getDescriptor(), 23) - .setField(UnittestProto.myExtensionString.getDescriptor(), "bar") - .build().toByteString(); - assertFieldsInOrder(dynamic_data); + ByteString dynamicData = + DynamicMessage.newBuilder(TestFieldOrderings.getDescriptor()) + .setField(descriptor.findFieldByName("my_int"), 1L) + .setField(descriptor.findFieldByName("my_string"), "foo") + .setField(descriptor.findFieldByName("my_float"), 1.0F) + .setField(UnittestProto.myExtensionInt.getDescriptor(), 23) + .setField(UnittestProto.myExtensionString.getDescriptor(), "bar") + .build() + .toByteString(); + assertFieldsInOrder(dynamicData); } private ExtensionRegistry getTestFieldOrderingsRegistry() { @@ -224,36 +229,35 @@ public class WireFormatTest extends TestCase { // Make sure we can parse a message that contains multiple extensions // ranges. TestFieldOrderings source = - TestFieldOrderings.newBuilder() - .setMyInt(1) - .setMyString("foo") - .setMyFloat(1.0F) - .setExtension(UnittestProto.myExtensionInt, 23) - .setExtension(UnittestProto.myExtensionString, "bar") - .build(); + TestFieldOrderings.newBuilder() + .setMyInt(1) + .setMyString("foo") + .setMyFloat(1.0F) + .setExtension(UnittestProto.myExtensionInt, 23) + .setExtension(UnittestProto.myExtensionString, "bar") + .build(); TestFieldOrderings dest = - TestFieldOrderings.parseFrom(source.toByteString(), - getTestFieldOrderingsRegistry()); + TestFieldOrderings.parseFrom(source.toByteString(), getTestFieldOrderingsRegistry()); assertEquals(source, dest); } - + private static ExtensionRegistry getTestExtensionInsideTableRegistry() { ExtensionRegistry result = ExtensionRegistry.newInstance(); result.add(UnittestProto.testExtensionInsideTableExtension); return result; } - + public void testExtensionInsideTable() throws Exception { // Make sure the extension within the range of table is parsed correctly in experimental // runtime. TestExtensionInsideTable source = TestExtensionInsideTable.newBuilder() - .setField1(1) - .setExtension(UnittestProto.testExtensionInsideTableExtension, 23) - .build(); + .setField1(1) + .setExtension(UnittestProto.testExtensionInsideTableExtension, 23) + .build(); TestExtensionInsideTable dest = - TestExtensionInsideTable.parseFrom(source.toByteString(), - getTestExtensionInsideTableRegistry()); + TestExtensionInsideTable.parseFrom( + source.toByteString(), getTestExtensionInsideTableRegistry()); assertEquals(source, dest); } @@ -261,25 +265,19 @@ public class WireFormatTest extends TestCase { // Same as above except with DynamicMessage. Descriptors.Descriptor descriptor = TestFieldOrderings.getDescriptor(); DynamicMessage source = - DynamicMessage.newBuilder(TestFieldOrderings.getDescriptor()) - .setField(descriptor.findFieldByName("my_int"), 1L) - .setField(descriptor.findFieldByName("my_string"), "foo") - .setField(descriptor.findFieldByName("my_float"), 1.0F) - .setField(UnittestProto.myExtensionInt.getDescriptor(), 23) - .setField(UnittestProto.myExtensionString.getDescriptor(), "bar") - .build(); + DynamicMessage.newBuilder(TestFieldOrderings.getDescriptor()) + .setField(descriptor.findFieldByName("my_int"), 1L) + .setField(descriptor.findFieldByName("my_string"), "foo") + .setField(descriptor.findFieldByName("my_float"), 1.0F) + .setField(UnittestProto.myExtensionInt.getDescriptor(), 23) + .setField(UnittestProto.myExtensionString.getDescriptor(), "bar") + .build(); DynamicMessage dest = - DynamicMessage.parseFrom(descriptor, source.toByteString(), - getTestFieldOrderingsRegistry()); + DynamicMessage.parseFrom( + descriptor, source.toByteString(), getTestFieldOrderingsRegistry()); assertEquals(source, dest); } - private static final int UNKNOWN_TYPE_ID = 1550055; - private static final int TYPE_ID_1 = - TestMessageSetExtension1.getDescriptor().getExtensions().get(0).getNumber(); - private static final int TYPE_ID_2 = - TestMessageSetExtension2.getDescriptor().getExtensions().get(0).getNumber(); - public void testSerializeMessageSetEagerly() throws Exception { testSerializeMessageSetWithFlag(true); } @@ -288,26 +286,26 @@ public class WireFormatTest extends TestCase { testSerializeMessageSetWithFlag(false); } - private void testSerializeMessageSetWithFlag(boolean eagerParsing) - throws Exception { + private void testSerializeMessageSetWithFlag(boolean eagerParsing) throws Exception { ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing); // Set up a TestMessageSet with two known messages and an unknown one. TestMessageSet messageSet = - TestMessageSet.newBuilder() - .setExtension( - TestMessageSetExtension1.messageSetExtension, - TestMessageSetExtension1.newBuilder().setI(123).build()) - .setExtension( - TestMessageSetExtension2.messageSetExtension, - TestMessageSetExtension2.newBuilder().setStr("foo").build()) - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField(UNKNOWN_TYPE_ID, - UnknownFieldSet.Field.newBuilder() - .addLengthDelimited(ByteString.copyFromUtf8("bar")) - .build()) - .build()) - .build(); + TestMessageSet.newBuilder() + .setExtension( + TestMessageSetExtension1.messageSetExtension, + TestMessageSetExtension1.newBuilder().setI(123).build()) + .setExtension( + TestMessageSetExtension2.messageSetExtension, + TestMessageSetExtension2.newBuilder().setStr("foo").build()) + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + UNKNOWN_TYPE_ID, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited(ByteString.copyFromUtf8("bar")) + .build()) + .build()) + .build(); ByteString data = messageSet.toByteString(); @@ -322,13 +320,11 @@ public class WireFormatTest extends TestCase { assertEquals(UNKNOWN_TYPE_ID, raw.getItem(2).getTypeId()); TestMessageSetExtension1 message1 = - TestMessageSetExtension1.parseFrom( - raw.getItem(0).getMessage().toByteArray()); + TestMessageSetExtension1.parseFrom(raw.getItem(0).getMessage()); assertEquals(123, message1.getI()); TestMessageSetExtension2 message2 = - TestMessageSetExtension2.parseFrom( - raw.getItem(1).getMessage().toByteArray()); + TestMessageSetExtension2.parseFrom(raw.getItem(1).getMessage()); assertEquals("foo", message2.getStr()); assertEquals("bar", raw.getItem(2).getMessage().toStringUtf8()); @@ -338,12 +334,11 @@ public class WireFormatTest extends TestCase { testParseMessageSetWithFlag(true); } - public void testParseMessageSetNotEagerly()throws Exception { + public void testParseMessageSetNotEagerly() throws Exception { testParseMessageSetWithFlag(false); } - private void testParseMessageSetWithFlag(boolean eagerParsing) - throws Exception { + private void testParseMessageSetWithFlag(boolean eagerParsing) throws Exception { ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing); ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance(); extensionRegistry.add(TestMessageSetExtension1.messageSetExtension); @@ -351,40 +346,34 @@ public class WireFormatTest extends TestCase { // Set up a RawMessageSet with two known messages and an unknown one. RawMessageSet raw = - RawMessageSet.newBuilder() - .addItem( - RawMessageSet.Item.newBuilder() - .setTypeId(TYPE_ID_1) - .setMessage( - TestMessageSetExtension1.newBuilder() - .setI(123) - .build().toByteString()) - .build()) - .addItem( - RawMessageSet.Item.newBuilder() - .setTypeId(TYPE_ID_2) - .setMessage( - TestMessageSetExtension2.newBuilder() - .setStr("foo") - .build().toByteString()) - .build()) - .addItem( - RawMessageSet.Item.newBuilder() - .setTypeId(UNKNOWN_TYPE_ID) - .setMessage(ByteString.copyFromUtf8("bar")) - .build()) - .build(); + RawMessageSet.newBuilder() + .addItem( + RawMessageSet.Item.newBuilder() + .setTypeId(TYPE_ID_1) + .setMessage( + TestMessageSetExtension1.newBuilder().setI(123).build().toByteString()) + .build()) + .addItem( + RawMessageSet.Item.newBuilder() + .setTypeId(TYPE_ID_2) + .setMessage( + TestMessageSetExtension2.newBuilder().setStr("foo").build().toByteString()) + .build()) + .addItem( + RawMessageSet.Item.newBuilder() + .setTypeId(UNKNOWN_TYPE_ID) + .setMessage(ByteString.copyFromUtf8("bar")) + .build()) + .build(); ByteString data = raw.toByteString(); // Parse as a TestMessageSet and check the contents. - TestMessageSet messageSet = - TestMessageSet.parseFrom(data, extensionRegistry); + TestMessageSet messageSet = TestMessageSet.parseFrom(data, extensionRegistry); - assertEquals(123, messageSet.getExtension( - TestMessageSetExtension1.messageSetExtension).getI()); - assertEquals("foo", messageSet.getExtension( - TestMessageSetExtension2.messageSetExtension).getStr()); + assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI()); + assertEquals( + "foo", messageSet.getExtension(TestMessageSetExtension2.messageSetExtension).getStr()); // Check for unknown field with type LENGTH_DELIMITED, // number UNKNOWN_TYPE_ID, and contents "bar". @@ -405,35 +394,27 @@ public class WireFormatTest extends TestCase { testParseMessageSetExtensionWithFlag(false); } - private void testParseMessageSetExtensionWithFlag(boolean eagerParsing) - throws Exception { + private void testParseMessageSetExtensionWithFlag(boolean eagerParsing) throws Exception { ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing); ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance(); extensionRegistry.add(TestMessageSetExtension1.messageSetExtension); // Set up a RawMessageSet with a known messages. - int TYPE_ID_1 = - TestMessageSetExtension1 - .getDescriptor().getExtensions().get(0).getNumber(); RawMessageSet raw = - RawMessageSet.newBuilder() - .addItem( - RawMessageSet.Item.newBuilder() - .setTypeId(TYPE_ID_1) - .setMessage( - TestMessageSetExtension1.newBuilder() - .setI(123) - .build().toByteString()) - .build()) - .build(); + RawMessageSet.newBuilder() + .addItem( + RawMessageSet.Item.newBuilder() + .setTypeId(TYPE_ID_1) + .setMessage( + TestMessageSetExtension1.newBuilder().setI(123).build().toByteString()) + .build()) + .build(); ByteString data = raw.toByteString(); // Parse as a TestMessageSet and check the contents. - TestMessageSet messageSet = - TestMessageSet.parseFrom(data, extensionRegistry); - assertEquals(123, messageSet.getExtension( - TestMessageSetExtension1.messageSetExtension).getI()); + TestMessageSet messageSet = TestMessageSet.parseFrom(data, extensionRegistry); + assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI()); } public void testMergeLazyMessageSetExtensionEagerly() throws Exception { @@ -444,38 +425,29 @@ public class WireFormatTest extends TestCase { testMergeLazyMessageSetExtensionWithFlag(false); } - private void testMergeLazyMessageSetExtensionWithFlag(boolean eagerParsing) - throws Exception { + private void testMergeLazyMessageSetExtensionWithFlag(boolean eagerParsing) throws Exception { ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing); ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance(); extensionRegistry.add(TestMessageSetExtension1.messageSetExtension); // Set up a RawMessageSet with a known messages. - int TYPE_ID_1 = - TestMessageSetExtension1 - .getDescriptor().getExtensions().get(0).getNumber(); RawMessageSet raw = - RawMessageSet.newBuilder() - .addItem( - RawMessageSet.Item.newBuilder() - .setTypeId(TYPE_ID_1) - .setMessage( - TestMessageSetExtension1.newBuilder() - .setI(123) - .build().toByteString()) - .build()) - .build(); + RawMessageSet.newBuilder() + .addItem( + RawMessageSet.Item.newBuilder() + .setTypeId(TYPE_ID_1) + .setMessage( + TestMessageSetExtension1.newBuilder().setI(123).build().toByteString()) + .build()) + .build(); ByteString data = raw.toByteString(); // Parse as a TestMessageSet and store value into lazy field - TestMessageSet messageSet = - TestMessageSet.parseFrom(data, extensionRegistry); + TestMessageSet messageSet = TestMessageSet.parseFrom(data, extensionRegistry); // Merge lazy field check the contents. - messageSet = - messageSet.toBuilder().mergeFrom(data, extensionRegistry).build(); - assertEquals(123, messageSet.getExtension( - TestMessageSetExtension1.messageSetExtension).getI()); + messageSet = messageSet.toBuilder().mergeFrom(data, extensionRegistry).build(); + assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI()); } public void testMergeMessageSetExtensionEagerly() throws Exception { @@ -486,31 +458,24 @@ public class WireFormatTest extends TestCase { testMergeMessageSetExtensionWithFlag(false); } - private void testMergeMessageSetExtensionWithFlag(boolean eagerParsing) - throws Exception { + private void testMergeMessageSetExtensionWithFlag(boolean eagerParsing) throws Exception { ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing); ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance(); extensionRegistry.add(TestMessageSetExtension1.messageSetExtension); // Set up a RawMessageSet with a known messages. - int TYPE_ID_1 = - TestMessageSetExtension1 - .getDescriptor().getExtensions().get(0).getNumber(); RawMessageSet raw = - RawMessageSet.newBuilder() - .addItem( - RawMessageSet.Item.newBuilder() - .setTypeId(TYPE_ID_1) - .setMessage( - TestMessageSetExtension1.newBuilder() - .setI(123) - .build().toByteString()) - .build()) - .build(); + RawMessageSet.newBuilder() + .addItem( + RawMessageSet.Item.newBuilder() + .setTypeId(TYPE_ID_1) + .setMessage( + TestMessageSetExtension1.newBuilder().setI(123).build().toByteString()) + .build()) + .build(); // Serialize RawMessageSet unnormally (message value before type id) - ByteString.CodedBuilder out = ByteString.newCodedBuilder( - raw.getSerializedSize()); + ByteString.CodedBuilder out = ByteString.newCodedBuilder(raw.getSerializedSize()); CodedOutputStream output = out.getCodedOutput(); List items = raw.getItemList(); for (int i = 0; i < items.size(); i++) { @@ -525,8 +490,7 @@ public class WireFormatTest extends TestCase { // Merge bytes into TestMessageSet and check the contents. TestMessageSet messageSet = TestMessageSet.newBuilder().mergeFrom(data, extensionRegistry).build(); - assertEquals(123, messageSet.getExtension( - TestMessageSetExtension1.messageSetExtension).getI()); + assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI()); } // ================================================================ @@ -544,8 +508,8 @@ public class WireFormatTest extends TestCase { } public void testOneofOnlyLastSet() throws Exception { - TestOneofBackwardsCompatible source = TestOneofBackwardsCompatible - .newBuilder().setFooInt(100).setFooString("101").build(); + TestOneofBackwardsCompatible source = + TestOneofBackwardsCompatible.newBuilder().setFooInt(100).setFooString("101").build(); ByteString rawBytes = source.toByteString(); TestOneof2 message = TestOneof2.parseFrom(rawBytes); diff --git a/java/util/src/main/java/com/google/protobuf/util/JsonFormat.java b/java/util/src/main/java/com/google/protobuf/util/JsonFormat.java index 955dfd8677..46deb5d164 100644 --- a/java/util/src/main/java/com/google/protobuf/util/JsonFormat.java +++ b/java/util/src/main/java/com/google/protobuf/util/JsonFormat.java @@ -1540,7 +1540,7 @@ public class JsonFormat { Object key = parseFieldValue(keyField, new JsonPrimitive(entry.getKey()), entryBuilder); Object value = parseFieldValue(valueField, entry.getValue(), entryBuilder); if (value == null) { - if(ignoringUnknownFields && valueField.getType() == Type.ENUM) { + if (ignoringUnknownFields && valueField.getType() == Type.ENUM) { continue; } else { throw new InvalidProtocolBufferException("Map value cannot be null."); @@ -1562,11 +1562,11 @@ public class JsonFormat { for (int i = 0; i < array.size(); ++i) { Object value = parseFieldValue(field, array.get(i), builder); if (value == null) { - if(ignoringUnknownFields && field.getType() == Type.ENUM) { + if (ignoringUnknownFields && field.getType() == Type.ENUM) { continue; } else { throw new InvalidProtocolBufferException( - "Repeated field elements cannot be null in field: " + field.getFullName()); + "Repeated field elements cannot be null in field: " + field.getFullName()); } } builder.addRepeatedField(field, value); diff --git a/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java b/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java index 7637c267f4..64413bc14e 100644 --- a/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java +++ b/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java @@ -161,7 +161,8 @@ public class JsonFormatTest extends TestCase { JsonFormat.parser().merge(json, builder); } - private void mergeFromJsonIgnoringUnknownFields(String json, Message.Builder builder) throws IOException { + private void mergeFromJsonIgnoringUnknownFields(String json, Message.Builder builder) + throws IOException { JsonFormat.parser().ignoringUnknownFields().merge(json, builder); } @@ -677,17 +678,14 @@ public class JsonFormatTest extends TestCase { // Exception expected. } } - + public void testMapEnumNullValueIsIgnored() throws Exception { TestMap.Builder builder = TestMap.newBuilder(); mergeFromJsonIgnoringUnknownFields( - "{\n" - + " \"int32ToEnumMap\": {\"1\": null}\n" - + "}", - builder); - TestMap map = builder.build(); - assertEquals(0, map.getInt32ToEnumMapMap().entrySet().size()); - } + "{\n" + " \"int32ToEnumMap\": {\"1\": null}\n" + "}", builder); + TestMap map = builder.build(); + assertEquals(0, map.getInt32ToEnumMapMap().size()); + } public void testParserAcceptNonQuotedObjectKey() throws Exception { TestMap.Builder builder = TestMap.newBuilder(); @@ -1188,40 +1186,36 @@ public class JsonFormatTest extends TestCase { String json = "{\n" + " \"unknownField\": \"XXX\"\n" + "}"; JsonFormat.parser().ignoringUnknownFields().merge(json, builder); } - + public void testParserIgnoringUnknownEnums() throws Exception { TestAllTypes.Builder builder = TestAllTypes.newBuilder(); String json = "{\n" + " \"optionalNestedEnum\": \"XXX\"\n" + "}"; JsonFormat.parser().ignoringUnknownFields().merge(json, builder); assertEquals(0, builder.getOptionalNestedEnumValue()); } - + public void testUnknownEnumMap() throws Exception { TestMap.Builder builder = TestMap.newBuilder(); - JsonFormat.parser().ignoringUnknownFields().merge( - "{\n" - + " \"int32ToEnumMap\": {1: XXX, 2: FOO}" - + "}", - builder); - - assertEquals(NestedEnum.FOO, builder.getInt32ToEnumMapMap().get(2)); - assertEquals(1, builder.getInt32ToEnumMapMap().size()); + JsonFormat.parser() + .ignoringUnknownFields() + .merge("{\n" + " \"int32ToEnumMap\": {1: XXX, 2: FOO}" + "}", builder); + + assertEquals(NestedEnum.FOO, builder.getInt32ToEnumMapMap().get(2)); + assertEquals(1, builder.getInt32ToEnumMapMap().size()); } - + public void testRepeatedUnknownEnum() throws Exception { TestAllTypes.Builder builder = TestAllTypes.newBuilder(); - JsonFormat.parser().ignoringUnknownFields().merge( - "{\n" - + " \"repeatedNestedEnum\": [XXX, FOO, BAR, BAZ]" - + "}", - builder); - + JsonFormat.parser() + .ignoringUnknownFields() + .merge("{\n" + " \"repeatedNestedEnum\": [XXX, FOO, BAR, BAZ]" + "}", builder); + assertEquals(NestedEnum.FOO, builder.getRepeatedNestedEnum(0)); assertEquals(NestedEnum.BAR, builder.getRepeatedNestedEnum(1)); assertEquals(NestedEnum.BAZ, builder.getRepeatedNestedEnum(2)); assertEquals(3, builder.getRepeatedNestedEnumList().size()); } - + public void testParserIntegerEnumValue() throws Exception { TestAllTypes.Builder actualBuilder = TestAllTypes.newBuilder(); mergeFromJson("{\n" + " \"optionalNestedEnum\": 2\n" + "}", actualBuilder); diff --git a/objectivec/google/protobuf/Any.pbobjc.h b/objectivec/google/protobuf/Any.pbobjc.h index ad261898e4..2091d72df4 100644 --- a/objectivec/google/protobuf/Any.pbobjc.h +++ b/objectivec/google/protobuf/Any.pbobjc.h @@ -140,7 +140,8 @@ typedef GPB_ENUM(GPBAny_FieldNumber) { /** * A URL/resource name that uniquely identifies the type of the serialized - * protocol buffer message. The last segment of the URL's path must represent + * protocol buffer message. This string must contain at least + * one "/" character. The last segment of the URL's path must represent * the fully qualified name of the type (as in * `path/google.protobuf.Duration`). The name should be in a canonical form * (e.g., leading "." is not accepted). diff --git a/objectivec/google/protobuf/Timestamp.pbobjc.h b/objectivec/google/protobuf/Timestamp.pbobjc.h index 2c4b8b2050..dc4cef7593 100644 --- a/objectivec/google/protobuf/Timestamp.pbobjc.h +++ b/objectivec/google/protobuf/Timestamp.pbobjc.h @@ -132,7 +132,7 @@ typedef GPB_ENUM(GPBTimestamp_FieldNumber) { * to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) * with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one * can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( - * http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime-- + * http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D * ) to obtain a formatter capable of generating timestamps in this format. **/ @interface GPBTimestamp : GPBMessage diff --git a/python/google/protobuf/descriptor_database.py b/python/google/protobuf/descriptor_database.py index a7616cbc88..5453f50c80 100644 --- a/python/google/protobuf/descriptor_database.py +++ b/python/google/protobuf/descriptor_database.py @@ -134,7 +134,11 @@ class DescriptorDatabase(object): # descriptor can also be found. The behavior is the same with # protobuf C++. top_level, _, _ = symbol.rpartition('.') - return self._file_desc_protos_by_symbol[top_level] + try: + return self._file_desc_protos_by_symbol[top_level] + except KeyError: + # Raise the original symbol as a KeyError for better diagnostics. + raise KeyError(symbol) def FindFileContainingExtension(self, extendee_name, extension_number): # TODO(jieluo): implement this API. diff --git a/python/google/protobuf/internal/decoder.py b/python/google/protobuf/internal/decoder.py index d2ec4f7b71..5a5401841e 100755 --- a/python/google/protobuf/internal/decoder.py +++ b/python/google/protobuf/internal/decoder.py @@ -81,9 +81,8 @@ we repeatedly read a tag, look up the corresponding decoder, and invoke it. __author__ = 'kenton@google.com (Kenton Varda)' import struct - -import six import sys +import six _UCS2_MAXUNICODE = 65535 if six.PY3: diff --git a/python/google/protobuf/internal/descriptor_database_test.py b/python/google/protobuf/internal/descriptor_database_test.py index 97e5315a42..da5dbd9252 100644 --- a/python/google/protobuf/internal/descriptor_database_test.py +++ b/python/google/protobuf/internal/descriptor_database_test.py @@ -103,9 +103,8 @@ class DescriptorDatabaseTest(unittest.TestCase): self.assertEqual(file_desc_proto2, db.FindFileContainingSymbol( 'protobuf_unittest.TestAllTypes.none_field')) - self.assertRaises(KeyError, - db.FindFileContainingSymbol, - 'protobuf_unittest.NoneMessage') + with self.assertRaisesRegexp(KeyError, r'\'protobuf_unittest\.NoneMessage\''): + db.FindFileContainingSymbol('protobuf_unittest.NoneMessage') def testConflictRegister(self): db = descriptor_database.DescriptorDatabase() diff --git a/python/google/protobuf/internal/message_test.py b/python/google/protobuf/internal/message_test.py index ccb9221c91..4dd1104a2f 100755 --- a/python/google/protobuf/internal/message_test.py +++ b/python/google/protobuf/internal/message_test.py @@ -1217,13 +1217,13 @@ class Proto2Test(BaseTestCase): message.optional_bool = True message.optional_nested_message.bb = 15 - self.assertTrue(message.HasField("optional_int32")) + self.assertTrue(message.HasField(u"optional_int32")) self.assertTrue(message.HasField("optional_bool")) self.assertTrue(message.HasField("optional_nested_message")) # Clearing the fields unsets them and resets their value to default. message.ClearField("optional_int32") - message.ClearField("optional_bool") + message.ClearField(u"optional_bool") message.ClearField("optional_nested_message") self.assertFalse(message.HasField("optional_int32")) @@ -1435,6 +1435,16 @@ class Proto2Test(BaseTestCase): with self.assertRaises(ValueError): unittest_pb2.TestAllTypes(repeated_nested_enum='FOO') + def testPythonicInitWithDict(self): + # Both string/unicode field name keys should work. + kwargs = { + 'optional_int32': 100, + u'optional_fixed32': 200, + } + msg = unittest_pb2.TestAllTypes(**kwargs) + self.assertEqual(100, msg.optional_int32) + self.assertEqual(200, msg.optional_fixed32) + def test_documentation(self): # Also used by the interactive help() function. @@ -2210,9 +2220,8 @@ class Proto3Test(BaseTestCase): msg.map_int32_int32[35] = 64 msg.map_string_foreign_message['foo'].c = 5 self.assertEqual(0, len(msg.FindInitializationErrors())) - - @unittest.skipIf(sys.maxunicode == UCS2_MAXUNICODE, - 'Skip for ucs2') + + @unittest.skipIf(sys.maxunicode == UCS2_MAXUNICODE, 'Skip for ucs2') def testStrictUtf8Check(self): # Test u'\ud801' is rejected at parser in both python2 and python3. serialized = (b'r\x03\xed\xa0\x81') diff --git a/python/google/protobuf/internal/python_message.py b/python/google/protobuf/internal/python_message.py index ab5d160f48..4e0f545c71 100755 --- a/python/google/protobuf/internal/python_message.py +++ b/python/google/protobuf/internal/python_message.py @@ -1003,8 +1003,13 @@ def _AddEqualsMethod(message_descriptor, cls): if not self.ListFields() == other.ListFields(): return False - # pylint: disable=protected-access - return self._unknown_field_set == other._unknown_field_set + # TODO(jieluo): Fix UnknownFieldSet to consider MessageSet extensions, + # then use it for the comparison. + unknown_fields = list(self._unknown_fields) + unknown_fields.sort() + other_unknown_fields = list(other._unknown_fields) + other_unknown_fields.sort() + return unknown_fields == other_unknown_fields cls.__eq__ = __eq__ diff --git a/python/google/protobuf/internal/reflection_test.py b/python/google/protobuf/internal/reflection_test.py index 31ceda2462..90d2fe3cc6 100755 --- a/python/google/protobuf/internal/reflection_test.py +++ b/python/google/protobuf/internal/reflection_test.py @@ -1579,6 +1579,8 @@ class ReflectionTest(BaseTestCase): proto1.repeated_int32.append(3) container = copy.deepcopy(proto1.repeated_int32) self.assertEqual([2, 3], container) + container.remove(container[0]) + self.assertEqual([3], container) message1 = proto1.repeated_nested_message.add() message1.bb = 1 @@ -1586,6 +1588,8 @@ class ReflectionTest(BaseTestCase): self.assertEqual(proto1.repeated_nested_message, messages) message1.bb = 2 self.assertNotEqual(proto1.repeated_nested_message, messages) + messages.remove(messages[0]) + self.assertEqual(len(messages), 0) # TODO(anuraag): Implement deepcopy for extension dict diff --git a/python/google/protobuf/internal/text_format_test.py b/python/google/protobuf/internal/text_format_test.py index c68f42d296..ccf8ac161d 100755 --- a/python/google/protobuf/internal/text_format_test.py +++ b/python/google/protobuf/internal/text_format_test.py @@ -835,6 +835,29 @@ class OnlyWorksWithProto2RightNowTests(TextFormatBase): ' }\n' '}\n') + # In cpp implementation, __str__ calls the cpp implementation of text format. + def testPrintMapUsingCppImplementation(self): + message = map_unittest_pb2.TestMap() + inner_msg = message.map_int32_foreign_message[111] + inner_msg.c = 1 + self.assertEqual( + str(message), + 'map_int32_foreign_message {\n' + ' key: 111\n' + ' value {\n' + ' c: 1\n' + ' }\n' + '}\n') + inner_msg.c = 2 + self.assertEqual( + str(message), + 'map_int32_foreign_message {\n' + ' key: 111\n' + ' value {\n' + ' c: 2\n' + ' }\n' + '}\n') + def testMapOrderEnforcement(self): message = map_unittest_pb2.TestMap() for letter in string.ascii_uppercase[13:26]: @@ -1397,6 +1420,24 @@ class Proto3Tests(unittest.TestCase): ' < data: "string" > ' '>') + def testPrintAndParseMessageInvalidAny(self): + packed_message = unittest_pb2.OneString() + packed_message.data = 'string' + message = any_test_pb2.TestAny() + message.any_value.Pack(packed_message) + # Only include string after last '/' in type_url. + message.any_value.type_url = message.any_value.TypeName() + text = text_format.MessageToString(message) + self.assertEqual( + text, 'any_value {\n' + ' type_url: "protobuf_unittest.OneString"\n' + ' value: "\\n\\006string"\n' + '}\n') + + parsed_message = any_test_pb2.TestAny() + text_format.Parse(text, parsed_message) + self.assertEqual(message, parsed_message) + def testUnknownEnums(self): message = unittest_proto3_arena_pb2.TestAllTypes() message2 = unittest_proto3_arena_pb2.TestAllTypes() @@ -1866,5 +1907,64 @@ class PrettyPrinterTest(TextFormatBase): 'repeated_nested_message { My lucky number is 42 } ' 'repeated_nested_message { My lucky number is 99 }')) + +class WhitespaceTest(TextFormatBase): + + def setUp(self): + self.out = text_format.TextWriter(False) + self.addCleanup(self.out.close) + self.message = unittest_pb2.NestedTestAllTypes() + self.message.child.payload.optional_string = 'value' + self.field = self.message.DESCRIPTOR.fields_by_name['child'] + self.value = self.message.child + + def testMessageToString(self): + self.CompareToGoldenText( + text_format.MessageToString(self.message), + textwrap.dedent("""\ + child { + payload { + optional_string: "value" + } + } + """)) + + def testPrintMessage(self): + text_format.PrintMessage(self.message, self.out) + self.CompareToGoldenText( + self.out.getvalue(), + textwrap.dedent("""\ + child { + payload { + optional_string: "value" + } + } + """)) + + def testPrintField(self): + text_format.PrintField(self.field, self.value, self.out) + self.CompareToGoldenText( + self.out.getvalue(), + textwrap.dedent("""\ + child { + payload { + optional_string: "value" + } + } + """)) + + def testPrintFieldValue(self): + text_format.PrintFieldValue( + self.field, self.value, self.out) + self.CompareToGoldenText( + self.out.getvalue(), + textwrap.dedent("""\ + { + payload { + optional_string: "value" + } + }""")) + + if __name__ == '__main__': unittest.main() diff --git a/python/google/protobuf/internal/well_known_types.py b/python/google/protobuf/internal/well_known_types.py index 37a65cfab1..95c5615f88 100644 --- a/python/google/protobuf/internal/well_known_types.py +++ b/python/google/protobuf/internal/well_known_types.py @@ -40,6 +40,7 @@ This files defines well known classes which need extra maintenance including: __author__ = 'jieluo@google.com (Jie Luo)' +import calendar import collections from datetime import datetime from datetime import timedelta @@ -92,7 +93,7 @@ class Any(object): def Is(self, descriptor): """Checks if this Any represents the given protobuf type.""" - return self.TypeName() == descriptor.full_name + return '/' in self.type_url and self.TypeName() == descriptor.full_name class Timestamp(object): @@ -233,9 +234,15 @@ class Timestamp(object): def FromDatetime(self, dt): """Converts datetime to Timestamp.""" - td = dt - datetime(1970, 1, 1) - self.seconds = td.seconds + td.days * _SECONDS_PER_DAY - self.nanos = td.microseconds * _NANOS_PER_MICROSECOND + # Using this guide: http://wiki.python.org/moin/WorkingWithTime + # And this conversion guide: http://docs.python.org/library/time.html + + # Turn the date parameter into a tuple (struct_time) that can then be + # manipulated into a long value of seconds. During the conversion from + # struct_time to long, the source date in UTC, and so it follows that the + # correct transformation is calendar.timegm() + self.seconds = calendar.timegm(dt.utctimetuple()) + self.nanos = dt.microsecond * _NANOS_PER_MICROSECOND class Duration(object): diff --git a/python/google/protobuf/internal/well_known_types_test.py b/python/google/protobuf/internal/well_known_types_test.py index 965940b261..4dc2ae4f83 100644 --- a/python/google/protobuf/internal/well_known_types_test.py +++ b/python/google/protobuf/internal/well_known_types_test.py @@ -35,7 +35,7 @@ __author__ = 'jieluo@google.com (Jie Luo)' import collections -from datetime import datetime +import datetime try: import unittest2 as unittest #PY26 @@ -240,14 +240,34 @@ class TimeUtilTest(TimeUtilTestBase): def testDatetimeConverison(self): message = timestamp_pb2.Timestamp() - dt = datetime(1970, 1, 1) + dt = datetime.datetime(1970, 1, 1) message.FromDatetime(dt) self.assertEqual(dt, message.ToDatetime()) message.FromMilliseconds(1999) - self.assertEqual(datetime(1970, 1, 1, 0, 0, 1, 999000), + self.assertEqual(datetime.datetime(1970, 1, 1, 0, 0, 1, 999000), message.ToDatetime()) + def testDatetimeConversionWithTimezone(self): + class TZ(datetime.tzinfo): + + def utcoffset(self, _): + return datetime.timedelta(hours=1) + + def dst(self, _): + return datetime.timedelta(0) + + def tzname(self, _): + return 'UTC+1' + + message1 = timestamp_pb2.Timestamp() + dt = datetime.datetime(1970, 1, 1, 1, tzinfo=TZ()) + message1.FromDatetime(dt) + message2 = timestamp_pb2.Timestamp() + dt = datetime.datetime(1970, 1, 1, 0) + message2.FromDatetime(dt) + self.assertEqual(message1, message2) + def testTimedeltaConversion(self): message = duration_pb2.Duration() message.FromNanoseconds(1999999999) @@ -879,6 +899,17 @@ class AnyTest(unittest.TestCase): raise AttributeError('%s should not have Pack method.' % msg_descriptor.full_name) + def testUnpackWithNoSlashInTypeUrl(self): + msg = any_test_pb2.TestAny() + all_types = unittest_pb2.TestAllTypes() + all_descriptor = all_types.DESCRIPTOR + msg.value.Pack(all_types) + # Reset type_url to part of type_url after '/' + msg.value.type_url = msg.value.TypeName() + self.assertFalse(msg.value.Is(all_descriptor)) + unpacked_message = unittest_pb2.TestAllTypes() + self.assertFalse(msg.value.Unpack(unpacked_message)) + def testMessageName(self): # Creates and sets message. submessage = any_test_pb2.TestAny() diff --git a/python/google/protobuf/pyext/descriptor_database.h b/python/google/protobuf/pyext/descriptor_database.h index daf25e0ba6..30aa1b73ed 100644 --- a/python/google/protobuf/pyext/descriptor_database.h +++ b/python/google/protobuf/pyext/descriptor_database.h @@ -48,18 +48,18 @@ class PyDescriptorDatabase : public DescriptorDatabase { // with a copy of FileDescriptorProto. // Find a file by file name. - bool FindFileByName(const string& filename, + bool FindFileByName(const std::string& filename, FileDescriptorProto* output); // Find the file that declares the given fully-qualified symbol name. - bool FindFileContainingSymbol(const string& symbol_name, + bool FindFileContainingSymbol(const std::string& symbol_name, FileDescriptorProto* output); // Find the file which defines an extension extending the given message type // with the given field number. // Containing_type must be a fully-qualified type name. // Python objects are not required to implement this method. - bool FindFileContainingExtension(const string& containing_type, + bool FindFileContainingExtension(const std::string& containing_type, int field_number, FileDescriptorProto* output); @@ -67,7 +67,7 @@ class PyDescriptorDatabase : public DescriptorDatabase { // containing_type, and appends them to output in an undefined // order. // Python objects are not required to implement this method. - bool FindAllExtensionNumbers(const string& containing_type, + bool FindAllExtensionNumbers(const std::string& containing_type, std::vector* output); private: diff --git a/python/google/protobuf/pyext/descriptor_pool.h b/python/google/protobuf/pyext/descriptor_pool.h index 8289daeaa7..8e7b4d6b98 100644 --- a/python/google/protobuf/pyext/descriptor_pool.h +++ b/python/google/protobuf/pyext/descriptor_pool.h @@ -89,7 +89,7 @@ namespace cdescriptor_pool { // Looks up a message by name. // Returns a message Descriptor, or NULL if not found. const Descriptor* FindMessageTypeByName(PyDescriptorPool* self, - const string& name); + const std::string& name); // The functions below are also exposed as methods of the DescriptorPool type. diff --git a/python/google/protobuf/pyext/message.cc b/python/google/protobuf/pyext/message.cc index 2205f12fdc..fecb9364ed 100644 --- a/python/google/protobuf/pyext/message.cc +++ b/python/google/protobuf/pyext/message.cc @@ -68,6 +68,8 @@ #include #include +#include + #if PY_MAJOR_VERSION >= 3 #define PyInt_AsLong PyLong_AsLong #define PyInt_FromLong PyLong_FromLong @@ -642,7 +644,7 @@ void OutOfRangeError(PyObject* arg) { template bool VerifyIntegerCastAndRange(PyObject* arg, ValueType value) { - if (GOOGLE_PREDICT_FALSE(value == -1 && PyErr_Occurred())) { + if (PROTOBUF_PREDICT_FALSE(value == -1 && PyErr_Occurred())) { if (PyErr_ExceptionMatches(PyExc_OverflowError)) { // Replace it with the same ValueError as pure python protos instead of // the default one. @@ -651,7 +653,7 @@ bool VerifyIntegerCastAndRange(PyObject* arg, ValueType value) { } // Otherwise propagate existing error. return false; } - if (GOOGLE_PREDICT_FALSE(!IsValidNumericCast(value))) { + if (PROTOBUF_PREDICT_FALSE(!IsValidNumericCast(value))) { OutOfRangeError(arg); return false; } @@ -663,22 +665,22 @@ bool CheckAndGetInteger(PyObject* arg, T* value) { // The fast path. #if PY_MAJOR_VERSION < 3 // For the typical case, offer a fast path. - if (GOOGLE_PREDICT_TRUE(PyInt_Check(arg))) { + if (PROTOBUF_PREDICT_TRUE(PyInt_Check(arg))) { long int_result = PyInt_AsLong(arg); - if (GOOGLE_PREDICT_TRUE(IsValidNumericCast(int_result))) { + if (PROTOBUF_PREDICT_TRUE(IsValidNumericCast(int_result))) { *value = static_cast(int_result); return true; } else { OutOfRangeError(arg); return false; } - } + } #endif // This effectively defines an integer as "an object that can be cast as // an integer and can be used as an ordinal number". // This definition includes everything that implements numbers.Integral // and shouldn't cast the net too wide. - if (GOOGLE_PREDICT_FALSE(!PyIndex_Check(arg))) { + if (PROTOBUF_PREDICT_FALSE(!PyIndex_Check(arg))) { FormatTypeError(arg, "int, long"); return false; } @@ -695,7 +697,7 @@ bool CheckAndGetInteger(PyObject* arg, T* value) { // Unlike PyLong_AsLongLong, PyLong_AsUnsignedLongLong is very // picky about the exact type. PyObject* casted = PyNumber_Long(arg); - if (GOOGLE_PREDICT_FALSE(casted == nullptr)) { + if (PROTOBUF_PREDICT_FALSE(casted == nullptr)) { // Propagate existing error. return false; } @@ -720,7 +722,7 @@ bool CheckAndGetInteger(PyObject* arg, T* value) { // Valid subclasses of numbers.Integral should have a __long__() method // so fall back to that. PyObject* casted = PyNumber_Long(arg); - if (GOOGLE_PREDICT_FALSE(casted == nullptr)) { + if (PROTOBUF_PREDICT_FALSE(casted == nullptr)) { // Propagate existing error. return false; } @@ -746,7 +748,7 @@ template bool CheckAndGetInteger(PyObject*, uint64*); bool CheckAndGetDouble(PyObject* arg, double* value) { *value = PyFloat_AsDouble(arg); - if (GOOGLE_PREDICT_FALSE(*value == -1 && PyErr_Occurred())) { + if (PROTOBUF_PREDICT_FALSE(*value == -1 && PyErr_Occurred())) { FormatTypeError(arg, "int, long, float"); return false; } @@ -1106,11 +1108,10 @@ static PyObject* GetIntegerEnumValue(const FieldDescriptor& descriptor, // needs to do this to make sure CMessages stay alive if they're still // referenced after deletion. Repeated scalar container doesn't need to worry. int InternalDeleteRepeatedField( - CMessage* self, + Message* message, const FieldDescriptor* field_descriptor, PyObject* slice, PyObject* cmessage_list) { - Message* message = self->message; Py_ssize_t length, from, to, step, slice_length; const Reflection* reflection = message->GetReflection(); int min, max; @@ -1188,7 +1189,7 @@ int InternalDeleteRepeatedField( CMessage* last_cmessage = reinterpret_cast( PyList_GET_ITEM(cmessage_list, PyList_GET_SIZE(cmessage_list) - 1)); repeated_composite_container::ReleaseLastTo( - self, field_descriptor, last_cmessage); + message, field_descriptor, last_cmessage); if (PySequence_DelItem(cmessage_list, -1) < 0) { return -1; } @@ -1214,7 +1215,7 @@ int InitAttributes(CMessage* self, PyObject* args, PyObject* kwargs) { PyObject* name; PyObject* value; while (PyDict_Next(kwargs, &pos, &name, &value)) { - if (!PyString_Check(name)) { + if (!(PyString_Check(name) || PyUnicode_Check(name))) { PyErr_SetString(PyExc_ValueError, "Field name must be a string"); return -1; } @@ -1808,13 +1809,16 @@ PyObject* ClearFieldByDescriptor( } PyObject* ClearField(CMessage* self, PyObject* arg) { - if (!PyString_Check(arg)) { + if (!(PyString_Check(arg) || PyUnicode_Check(arg))) { PyErr_SetString(PyExc_TypeError, "field name must be a string"); return NULL; } #if PY_MAJOR_VERSION < 3 - const char* field_name = PyString_AS_STRING(arg); - Py_ssize_t size = PyString_GET_SIZE(arg); + char* field_name; + Py_ssize_t size; + if (PyString_AsStringAndSize(arg, &field_name, &size) < 0) { + return NULL; + } #else Py_ssize_t size; const char* field_name = PyUnicode_AsUTF8AndSize(arg, &size); diff --git a/python/google/protobuf/pyext/message.h b/python/google/protobuf/pyext/message.h index cbd422be02..c112a88fea 100644 --- a/python/google/protobuf/pyext/message.h +++ b/python/google/protobuf/pyext/message.h @@ -166,13 +166,13 @@ PyObject* InternalGetSubMessage( // Deletes a range of C++ submessages in a repeated field (following a // removal in a RepeatedCompositeContainer). // -// Releases messages to the provided cmessage_list if it is not NULL rather +// Releases submessages to the provided cmessage_list if it is not NULL rather // than just removing them from the underlying proto. This cmessage_list must // have a CMessage for each underlying submessage. The CMessages referred to // by slice will be removed from cmessage_list by this function. // // Corresponds to reflection api method RemoveLast. -int InternalDeleteRepeatedField(CMessage* self, +int InternalDeleteRepeatedField(Message* message, const FieldDescriptor* field_descriptor, PyObject* slice, PyObject* cmessage_list); @@ -332,7 +332,7 @@ bool CheckAndSetString( bool append, int index); PyObject* ToStringObject(const FieldDescriptor* descriptor, - const string& value); + const std::string& value); // Check if the passed field descriptor belongs to the given message. // If not, return false and set a Python exception (a KeyError) diff --git a/python/google/protobuf/pyext/repeated_composite_container.cc b/python/google/protobuf/pyext/repeated_composite_container.cc index d6bc3d7b26..ca70058039 100644 --- a/python/google/protobuf/pyext/repeated_composite_container.cc +++ b/python/google/protobuf/pyext/repeated_composite_container.cc @@ -272,8 +272,8 @@ int AssignSubscript(RepeatedCompositeContainer* self, } // Delete from the underlying Message, if any. - if (self->parent != NULL) { - if (cmessage::InternalDeleteRepeatedField(self->parent, + if (self->message != nullptr) { + if (cmessage::InternalDeleteRepeatedField(self->message, self->parent_field_descriptor, slice, self->child_messages) < 0) { @@ -486,15 +486,15 @@ static PyObject* Pop(PyObject* pself, PyObject* args) { } // Release field of parent message and transfer the ownership to target. -void ReleaseLastTo(CMessage* parent, +void ReleaseLastTo(Message* message, const FieldDescriptor* field, CMessage* target) { - GOOGLE_CHECK(parent != nullptr); + GOOGLE_CHECK(message != nullptr); GOOGLE_CHECK(field != nullptr); GOOGLE_CHECK(target != nullptr); CMessage::OwnerRef released_message( - parent->message->GetReflection()->ReleaseLast(parent->message, field)); + message->GetReflection()->ReleaseLast(message, field)); // TODO(tibell): Deal with proto1. target->parent = NULL; @@ -524,7 +524,7 @@ int Release(RepeatedCompositeContainer* self) { for (Py_ssize_t i = size - 1; i >= 0; --i) { CMessage* child_cmessage = reinterpret_cast( PyList_GET_ITEM(self->child_messages, i)); - ReleaseLastTo(self->parent, field, child_cmessage); + ReleaseLastTo(message, field, child_cmessage); } // Detach from containing message. diff --git a/python/google/protobuf/pyext/repeated_composite_container.h b/python/google/protobuf/pyext/repeated_composite_container.h index 464699aa83..d075577145 100644 --- a/python/google/protobuf/pyext/repeated_composite_container.h +++ b/python/google/protobuf/pyext/repeated_composite_container.h @@ -154,7 +154,7 @@ int SetOwner(RepeatedCompositeContainer* self, // Message to 'target'. // // Corresponds to reflection api method ReleaseMessage. -void ReleaseLastTo(CMessage* parent, +void ReleaseLastTo(Message* message, const FieldDescriptor* field, CMessage* target); diff --git a/python/google/protobuf/pyext/repeated_scalar_container.cc b/python/google/protobuf/pyext/repeated_scalar_container.cc index cdb6426932..ac06cff3aa 100644 --- a/python/google/protobuf/pyext/repeated_scalar_container.cc +++ b/python/google/protobuf/pyext/repeated_scalar_container.cc @@ -104,7 +104,8 @@ static int AssignItem(PyObject* pself, Py_ssize_t index, PyObject* arg) { if (arg == NULL) { ScopedPyObjectPtr py_index(PyLong_FromLong(index)); - return cmessage::InternalDeleteRepeatedField(self->parent, field_descriptor, + return cmessage::InternalDeleteRepeatedField(self->message, + field_descriptor, py_index.get(), NULL); } @@ -467,7 +468,7 @@ static int AssSubscript(PyObject* pself, PyObject* slice, PyObject* value) { if (value == NULL) { return cmessage::InternalDeleteRepeatedField( - self->parent, field_descriptor, slice, NULL); + self->message, field_descriptor, slice, nullptr); } if (!create_list) { diff --git a/python/google/protobuf/pyext/safe_numerics.h b/python/google/protobuf/pyext/safe_numerics.h index 60112cfa4e..93ae640e8b 100644 --- a/python/google/protobuf/pyext/safe_numerics.h +++ b/python/google/protobuf/pyext/safe_numerics.h @@ -132,10 +132,10 @@ template inline bool IsValidNumericCast(Source source) { typedef std::numeric_limits SourceLimits; typedef std::numeric_limits DestLimits; - GOOGLE_COMPILE_ASSERT(SourceLimits::is_specialized, argument_must_be_numeric); - GOOGLE_COMPILE_ASSERT(SourceLimits::is_integer, argument_must_be_integral); - GOOGLE_COMPILE_ASSERT(DestLimits::is_specialized, result_must_be_numeric); - GOOGLE_COMPILE_ASSERT(DestLimits::is_integer, result_must_be_integral); + static_assert(SourceLimits::is_specialized, "argument must be numeric"); + static_assert(SourceLimits::is_integer, "argument must be integral"); + static_assert(DestLimits::is_specialized, "result must be numeric"); + static_assert(DestLimits::is_integer, "result must be integral"); return IsValidNumericCastImpl< sizeof(Dest) == sizeof(Source), @@ -150,7 +150,7 @@ inline bool IsValidNumericCast(Source source) { // checked_numeric_cast<> is analogous to static_cast<> for numeric types, // except that it CHECKs that the specified numeric conversion will not // overflow or underflow. Floating point arguments are not currently allowed -// (this is COMPILE_ASSERTd), though this could be supported if necessary. +// (this is static_asserted), though this could be supported if necessary. template inline Dest checked_numeric_cast(Source source) { GOOGLE_CHECK(IsValidNumericCast(source)); diff --git a/python/google/protobuf/text_format.py b/python/google/protobuf/text_format.py index 5dd41830c2..998cd681c3 100755 --- a/python/google/protobuf/text_format.py +++ b/python/google/protobuf/text_format.py @@ -155,7 +155,7 @@ def MessageToString(message, (per the "Format Specification Mini-Language"); otherwise, str() is used. use_field_number: If True, print field numbers instead of names. descriptor_pool: A DescriptorPool used to resolve Any types. - indent: The indent level, in terms of spaces, for pretty print. + indent: The initial indent level, in terms of spaces, for pretty print. message_formatter: A function(message, indent, as_one_line): unicode|None to custom format selected sub-messages (usually based on message type). Use to pretty print parts of the protobuf for easier diffing. @@ -296,7 +296,7 @@ class _Printer(object): Args: out: To record the text format result. - indent: The indent level for pretty print. + indent: The initial indent level for pretty print. as_utf8: Return unescaped Unicode for non-ASCII characters. In Python 3 actual Unicode characters may appear as is in strings. In Python 2 the return value will be valid UTF-8 rather than ASCII. @@ -330,11 +330,13 @@ class _Printer(object): def _TryPrintAsAnyMessage(self, message): """Serializes if message is a google.protobuf.Any field.""" + if '/' not in message.type_url: + return False packed_message = _BuildMessageFromTypeName(message.TypeName(), self.descriptor_pool) if packed_message: packed_message.MergeFromString(message.value) - self.out.write('%s[%s]' % (self.indent * ' ', message.type_url)) + self.out.write('%s[%s] ' % (self.indent * ' ', message.type_url)) self._PrintMessageFieldValue(packed_message) self.out.write(' ' if self.as_one_line else '\n') return True @@ -413,11 +415,12 @@ class _Printer(object): if field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE: # The colon is optional in this case, but our cross-language golden files # don't include it. - out.write(': ') + out.write(':') def PrintField(self, field, value): """Print a single field name/value pair.""" self._PrintFieldName(field) + self.out.write(' ') self.PrintFieldValue(field, value) self.out.write(' ' if self.as_one_line else '\n') @@ -441,11 +444,11 @@ class _Printer(object): closeb = '}' if self.as_one_line: - self.out.write(' %s ' % openb) + self.out.write('%s ' % openb) self.PrintMessage(value) self.out.write(closeb) else: - self.out.write(' %s\n' % openb) + self.out.write('%s\n' % openb) self.indent += 2 self.PrintMessage(value) self.indent -= 2 diff --git a/src/google/protobuf/any.h b/src/google/protobuf/any.h index 61dc7176a4..db7d76a891 100644 --- a/src/google/protobuf/any.h +++ b/src/google/protobuf/any.h @@ -38,12 +38,14 @@ #include #include +#include + namespace google { namespace protobuf { namespace internal { // Helper class used to implement google::protobuf::Any. -class LIBPROTOBUF_EXPORT AnyMetadata { +class PROTOBUF_EXPORT AnyMetadata { typedef ArenaStringPtr UrlType; typedef ArenaStringPtr ValueType; public: @@ -59,7 +61,7 @@ class LIBPROTOBUF_EXPORT AnyMetadata { // For example, both PackFrom(message, "type.googleapis.com") and // PackFrom(message, "type.googleapis.com/") yield the same result type // URL: "type.googleapis.com/". - void PackFrom(const Message& message, const string& type_url_prefix); + void PackFrom(const Message& message, const std::string& type_url_prefix); // Unpacks the payload into the given message. Returns false if the message's // type doesn't match the type specified in the type URL (i.e., the full @@ -95,15 +97,15 @@ extern const char kTypeGoogleProdComPrefix[]; // "type.googleprod.com/". // // NOTE: this function is available publicly as: // google::protobuf::Any() // static method on the generated message type. -bool ParseAnyTypeUrl(const string& type_url, string* full_type_name); +bool ParseAnyTypeUrl(const std::string& type_url, std::string* full_type_name); // Get the proto type name and prefix from Any::type_url value. For example, // passing "type.googleapis.com/rpc.QueryOrigin" will return // "type.googleapis.com/" in *url_prefix and "rpc.QueryOrigin" in // *full_type_name. Returns false if the type_url does not have a "/" in the // type url separating the full type name. -bool ParseAnyTypeUrl(const string& type_url, string* url_prefix, - string* full_type_name); +bool ParseAnyTypeUrl(const std::string& type_url, std::string* url_prefix, + std::string* full_type_name); // See if message is of type google.protobuf.Any, if so, return the descriptors // for "type_url" and "value" fields. @@ -115,4 +117,6 @@ bool GetAnyFieldDescriptors(const Message& message, } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_ANY_H__ diff --git a/src/google/protobuf/any.pb.cc b/src/google/protobuf/any.pb.cc index 7b10893ca1..a45f6580c2 100644 --- a/src/google/protobuf/any.pb.cc +++ b/src/google/protobuf/any.pb.cc @@ -13,10 +13,6 @@ #include #include #include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif // @@protoc_insertion_point(includes) #include @@ -39,7 +35,7 @@ static void InitDefaultsAny_google_2fprotobuf_2fany_2eproto() { ::google::protobuf::Any::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Any_google_2fprotobuf_2fany_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Any_google_2fprotobuf_2fany_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsAny_google_2fprotobuf_2fany_2eproto}, {}}; void InitDefaults_google_2fprotobuf_2fany_2eproto() { @@ -50,16 +46,16 @@ void InitDefaults_google_2fprotobuf_2fany_2eproto() { constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fany_2eproto = nullptr; constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fany_2eproto = nullptr; -const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fany_2eproto::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fany_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Any, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Any, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Any, type_url_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Any, value_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Any, type_url_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Any, value_), }; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::google::protobuf::Any)}, }; @@ -204,14 +200,13 @@ const char* Any::_InternalParse(const char* begin, const char* end, void* object while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // string type_url = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.Any.type_url"); parser_till_end = ::google::protobuf::internal::StringParserUTF8; ::std::string* str = msg->mutable_type_url(); @@ -219,29 +214,29 @@ const char* Any::_InternalParse(const char* begin, const char* end, void* object object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // bytes value = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::internal::StringParser; ::std::string* str = msg->mutable_value(); str->clear(); object = str; if (size > end - ptr) goto len_delim_till_end; - auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + str->append(ptr, size); + ptr += size; break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -252,8 +247,6 @@ const char* Any::_InternalParse(const char* begin, const char* end, void* object } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -265,7 +258,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Any::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Any) for (;;) { @@ -488,10 +481,11 @@ void Any::InternalSwap(Any* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Any* Arena::CreateMaybeMessage< ::google::protobuf::Any >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::Any* Arena::CreateMaybeMessage< ::google::protobuf::Any >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::Any >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope) +#include diff --git a/src/google/protobuf/any.pb.h b/src/google/protobuf/any.pb.h index a5ad5827f2..c931d500a6 100644 --- a/src/google/protobuf/any.pb.h +++ b/src/google/protobuf/any.pb.h @@ -7,18 +7,19 @@ #include #include -#include -#if GOOGLE_PROTOBUF_VERSION < 3006000 +#include +#if PROTOBUF_VERSION < 3006001 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3006001 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include @@ -33,27 +34,27 @@ #include // @@protoc_insertion_point(includes) #include -#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fany_2eproto LIBPROTOBUF_EXPORT +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fany_2eproto PROTOBUF_EXPORT // Internal implementation detail -- do not use these members. -struct LIBPROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fany_2eproto { +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fany_2eproto { static const ::google::protobuf::internal::ParseTableField entries[] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::AuxillaryParseTableField aux[] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::ParseTable schema[1] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::FieldMetadata field_metadata[]; static const ::google::protobuf::internal::SerializationTable serialization_table[]; static const ::google::protobuf::uint32 offsets[]; }; -void LIBPROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fany_2eproto(); +void PROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fany_2eproto(); namespace google { namespace protobuf { class Any; class AnyDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern AnyDefaultTypeInternal _Any_default_instance_; -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Any* Arena::CreateMaybeMessage<::google::protobuf::Any>(Arena*); +PROTOBUF_EXPORT extern AnyDefaultTypeInternal _Any_default_instance_; +template<> PROTOBUF_EXPORT ::google::protobuf::Any* Arena::CreateMaybeMessage<::google::protobuf::Any>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -61,7 +62,7 @@ namespace protobuf { // =================================================================== -class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Any) */ { +class PROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Any) */ { public: Any(); virtual ~Any(); diff --git a/src/google/protobuf/any.proto b/src/google/protobuf/any.proto index 4932942558..c9be854167 100644 --- a/src/google/protobuf/any.proto +++ b/src/google/protobuf/any.proto @@ -121,7 +121,8 @@ option objc_class_prefix = "GPB"; // message Any { // A URL/resource name that uniquely identifies the type of the serialized - // protocol buffer message. The last segment of the URL's path must represent + // protocol buffer message. This string must contain at least + // one "/" character. The last segment of the URL's path must represent // the fully qualified name of the type (as in // `path/google.protobuf.Duration`). The name should be in a canonical form // (e.g., leading "." is not accepted). diff --git a/src/google/protobuf/api.pb.cc b/src/google/protobuf/api.pb.cc index ac2a0e898e..1734dfdfe5 100644 --- a/src/google/protobuf/api.pb.cc +++ b/src/google/protobuf/api.pb.cc @@ -13,10 +13,6 @@ #include #include #include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif // @@protoc_insertion_point(includes) #include @@ -51,7 +47,7 @@ static void InitDefaultsApi_google_2fprotobuf_2fapi_2eproto() { ::google::protobuf::Api::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<4> scc_info_Api_google_2fprotobuf_2fapi_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<4> scc_info_Api_google_2fprotobuf_2fapi_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 4, InitDefaultsApi_google_2fprotobuf_2fapi_2eproto}, { &scc_info_Method_google_2fprotobuf_2fapi_2eproto.base, &scc_info_Option_google_2fprotobuf_2ftype_2eproto.base, @@ -69,7 +65,7 @@ static void InitDefaultsMethod_google_2fprotobuf_2fapi_2eproto() { ::google::protobuf::Method::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_Method_google_2fprotobuf_2fapi_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_Method_google_2fprotobuf_2fapi_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethod_google_2fprotobuf_2fapi_2eproto}, { &scc_info_Option_google_2fprotobuf_2ftype_2eproto.base,}}; @@ -84,7 +80,7 @@ static void InitDefaultsMixin_google_2fprotobuf_2fapi_2eproto() { ::google::protobuf::Mixin::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Mixin_google_2fprotobuf_2fapi_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Mixin_google_2fprotobuf_2fapi_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsMixin_google_2fprotobuf_2fapi_2eproto}, {}}; void InitDefaults_google_2fprotobuf_2fapi_2eproto() { @@ -97,40 +93,40 @@ void InitDefaults_google_2fprotobuf_2fapi_2eproto() { constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fapi_2eproto = nullptr; constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fapi_2eproto = nullptr; -const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fapi_2eproto::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fapi_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, methods_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, options_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, version_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, source_context_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, mixins_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, syntax_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, name_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, methods_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, options_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, version_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, source_context_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, mixins_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, syntax_), ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, request_type_url_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, request_streaming_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, response_type_url_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, response_streaming_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, options_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, syntax_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, name_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, request_type_url_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, request_streaming_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, response_type_url_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, response_streaming_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, options_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, syntax_), ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Mixin, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Mixin, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Mixin, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Mixin, root_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Mixin, name_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Mixin, root_), }; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::google::protobuf::Api)}, { 12, -1, sizeof(::google::protobuf::Method)}, { 24, -1, sizeof(::google::protobuf::Mixin)}, @@ -310,14 +306,13 @@ const char* Api::_InternalParse(const char* begin, const char* end, void* object while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // string name = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.Api.name"); parser_till_end = ::google::protobuf::internal::StringParserUTF8; ::std::string* str = msg->mutable_name(); @@ -325,8 +320,8 @@ const char* Api::_InternalParse(const char* begin, const char* end, void* object object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // repeated .google.protobuf.Method methods = 2; @@ -334,15 +329,17 @@ const char* Api::_InternalParse(const char* begin, const char* end, void* object if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::Method::_InternalParse; object = msg->add_methods(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 18 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1)); break; } // repeated .google.protobuf.Option options = 3; @@ -350,22 +347,24 @@ const char* Api::_InternalParse(const char* begin, const char* end, void* object if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::Option::_InternalParse; object = msg->add_options(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 26 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 26 && (ptr += 1)); break; } // string version = 4; case 4: { if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.Api.version"); parser_till_end = ::google::protobuf::internal::StringParserUTF8; ::std::string* str = msg->mutable_version(); @@ -373,20 +372,22 @@ const char* Api::_InternalParse(const char* begin, const char* end, void* object object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // .google.protobuf.SourceContext source_context = 5; case 5: { if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::SourceContext::_InternalParse; object = msg->mutable_source_context(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; break; } @@ -395,15 +396,17 @@ const char* Api::_InternalParse(const char* begin, const char* end, void* object if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::Mixin::_InternalParse; object = msg->add_mixins(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 50 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 50 && (ptr += 1)); break; } // .google.protobuf.Syntax syntax = 7; @@ -411,15 +414,16 @@ const char* Api::_InternalParse(const char* begin, const char* end, void* object if (static_cast<::google::protobuf::uint8>(tag) != 56) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::Syntax value = static_cast<::google::protobuf::Syntax>(val); msg->set_syntax(value); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -430,8 +434,6 @@ const char* Api::_InternalParse(const char* begin, const char* end, void* object } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -443,7 +445,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Api::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Api) for (;;) { @@ -974,14 +976,13 @@ const char* Method::_InternalParse(const char* begin, const char* end, void* obj while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // string name = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.Method.name"); parser_till_end = ::google::protobuf::internal::StringParserUTF8; ::std::string* str = msg->mutable_name(); @@ -989,15 +990,15 @@ const char* Method::_InternalParse(const char* begin, const char* end, void* obj object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // string request_type_url = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.Method.request_type_url"); parser_till_end = ::google::protobuf::internal::StringParserUTF8; ::std::string* str = msg->mutable_request_type_url(); @@ -1005,8 +1006,8 @@ const char* Method::_InternalParse(const char* begin, const char* end, void* obj object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // bool request_streaming = 3; @@ -1014,7 +1015,7 @@ const char* Method::_InternalParse(const char* begin, const char* end, void* obj if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_request_streaming(value); break; @@ -1023,7 +1024,7 @@ const char* Method::_InternalParse(const char* begin, const char* end, void* obj case 4: { if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.Method.response_type_url"); parser_till_end = ::google::protobuf::internal::StringParserUTF8; ::std::string* str = msg->mutable_response_type_url(); @@ -1031,8 +1032,8 @@ const char* Method::_InternalParse(const char* begin, const char* end, void* obj object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // bool response_streaming = 5; @@ -1040,7 +1041,7 @@ const char* Method::_InternalParse(const char* begin, const char* end, void* obj if (static_cast<::google::protobuf::uint8>(tag) != 40) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_response_streaming(value); break; @@ -1050,15 +1051,17 @@ const char* Method::_InternalParse(const char* begin, const char* end, void* obj if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::Option::_InternalParse; object = msg->add_options(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 50 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 50 && (ptr += 1)); break; } // .google.protobuf.Syntax syntax = 7; @@ -1066,15 +1069,16 @@ const char* Method::_InternalParse(const char* begin, const char* end, void* obj if (static_cast<::google::protobuf::uint8>(tag) != 56) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::Syntax value = static_cast<::google::protobuf::Syntax>(val); msg->set_syntax(value); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -1085,8 +1089,6 @@ const char* Method::_InternalParse(const char* begin, const char* end, void* obj } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -1098,7 +1100,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Method::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Method) for (;;) { @@ -1599,14 +1601,13 @@ const char* Mixin::_InternalParse(const char* begin, const char* end, void* obje while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // string name = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.Mixin.name"); parser_till_end = ::google::protobuf::internal::StringParserUTF8; ::std::string* str = msg->mutable_name(); @@ -1614,15 +1615,15 @@ const char* Mixin::_InternalParse(const char* begin, const char* end, void* obje object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // string root = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.Mixin.root"); parser_till_end = ::google::protobuf::internal::StringParserUTF8; ::std::string* str = msg->mutable_root(); @@ -1630,14 +1631,15 @@ const char* Mixin::_InternalParse(const char* begin, const char* end, void* obje object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -1648,8 +1650,6 @@ const char* Mixin::_InternalParse(const char* begin, const char* end, void* obje } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -1661,7 +1661,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Mixin::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Mixin) for (;;) { @@ -1896,16 +1896,17 @@ void Mixin::InternalSwap(Mixin* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Api* Arena::CreateMaybeMessage< ::google::protobuf::Api >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::Api* Arena::CreateMaybeMessage< ::google::protobuf::Api >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::Api >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Method* Arena::CreateMaybeMessage< ::google::protobuf::Method >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::Method* Arena::CreateMaybeMessage< ::google::protobuf::Method >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::Method >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Mixin* Arena::CreateMaybeMessage< ::google::protobuf::Mixin >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::Mixin* Arena::CreateMaybeMessage< ::google::protobuf::Mixin >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::Mixin >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope) +#include diff --git a/src/google/protobuf/api.pb.h b/src/google/protobuf/api.pb.h index 5af8aaf237..40a609b7db 100644 --- a/src/google/protobuf/api.pb.h +++ b/src/google/protobuf/api.pb.h @@ -7,18 +7,19 @@ #include #include -#include -#if GOOGLE_PROTOBUF_VERSION < 3006000 +#include +#if PROTOBUF_VERSION < 3006001 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3006001 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include @@ -34,35 +35,35 @@ #include // @@protoc_insertion_point(includes) #include -#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fapi_2eproto LIBPROTOBUF_EXPORT +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fapi_2eproto PROTOBUF_EXPORT // Internal implementation detail -- do not use these members. -struct LIBPROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fapi_2eproto { +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fapi_2eproto { static const ::google::protobuf::internal::ParseTableField entries[] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::AuxillaryParseTableField aux[] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::ParseTable schema[3] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::FieldMetadata field_metadata[]; static const ::google::protobuf::internal::SerializationTable serialization_table[]; static const ::google::protobuf::uint32 offsets[]; }; -void LIBPROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fapi_2eproto(); +void PROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fapi_2eproto(); namespace google { namespace protobuf { class Api; class ApiDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern ApiDefaultTypeInternal _Api_default_instance_; +PROTOBUF_EXPORT extern ApiDefaultTypeInternal _Api_default_instance_; class Method; class MethodDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern MethodDefaultTypeInternal _Method_default_instance_; +PROTOBUF_EXPORT extern MethodDefaultTypeInternal _Method_default_instance_; class Mixin; class MixinDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern MixinDefaultTypeInternal _Mixin_default_instance_; -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Api* Arena::CreateMaybeMessage<::google::protobuf::Api>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Method* Arena::CreateMaybeMessage<::google::protobuf::Method>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Mixin* Arena::CreateMaybeMessage<::google::protobuf::Mixin>(Arena*); +PROTOBUF_EXPORT extern MixinDefaultTypeInternal _Mixin_default_instance_; +template<> PROTOBUF_EXPORT ::google::protobuf::Api* Arena::CreateMaybeMessage<::google::protobuf::Api>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::Method* Arena::CreateMaybeMessage<::google::protobuf::Method>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::Mixin* Arena::CreateMaybeMessage<::google::protobuf::Mixin>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -70,7 +71,7 @@ namespace protobuf { // =================================================================== -class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Api) */ { +class PROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Api) */ { public: Api(); virtual ~Api(); @@ -260,7 +261,7 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Method) */ { +class PROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Method) */ { public: Method(); virtual ~Method(); @@ -443,7 +444,7 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Mixin) */ { +class PROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Mixin) */ { public: Mixin(); virtual ~Mixin(); diff --git a/src/google/protobuf/arena.cc b/src/google/protobuf/arena.cc index 1d81c322d5..26c291cf05 100644 --- a/src/google/protobuf/arena.cc +++ b/src/google/protobuf/arena.cc @@ -125,7 +125,7 @@ ArenaImpl::Block* ArenaImpl::NewBlock(Block* last_block, size_t min_bytes) { ArenaImpl::Block::Block(size_t size, Block* next) : next_(next), pos_(kBlockHeaderSize), size_(size) {} -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE +PROTOBUF_NOINLINE void ArenaImpl::SerialArena::AddCleanupFallback(void* elem, void (*cleanup)(void*)) { size_t size = cleanup_ ? cleanup_->size * 2 : kMinCleanupListElements; @@ -142,10 +142,10 @@ void ArenaImpl::SerialArena::AddCleanupFallback(void* elem, AddCleanup(elem, cleanup); } -GOOGLE_PROTOBUF_ATTRIBUTE_FUNC_ALIGN(32) +PROTOBUF_FUNC_ALIGN(32) void* ArenaImpl::AllocateAligned(size_t n) { SerialArena* arena; - if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) { + if (PROTOBUF_PREDICT_TRUE(GetSerialArenaFast(&arena))) { return arena->AllocateAligned(n); } else { return AllocateAlignedFallback(n); @@ -155,7 +155,7 @@ void* ArenaImpl::AllocateAligned(size_t n) { void* ArenaImpl::AllocateAlignedAndAddCleanup(size_t n, void (*cleanup)(void*)) { SerialArena* arena; - if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) { + if (PROTOBUF_PREDICT_TRUE(GetSerialArenaFast(&arena))) { return arena->AllocateAlignedAndAddCleanup(n, cleanup); } else { return AllocateAlignedAndAddCleanupFallback(n, cleanup); @@ -164,36 +164,36 @@ void* ArenaImpl::AllocateAlignedAndAddCleanup(size_t n, void ArenaImpl::AddCleanup(void* elem, void (*cleanup)(void*)) { SerialArena* arena; - if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) { + if (PROTOBUF_PREDICT_TRUE(GetSerialArenaFast(&arena))) { arena->AddCleanup(elem, cleanup); } else { return AddCleanupFallback(elem, cleanup); } } -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE +PROTOBUF_NOINLINE void* ArenaImpl::AllocateAlignedFallback(size_t n) { return GetSerialArena()->AllocateAligned(n); } -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE +PROTOBUF_NOINLINE void* ArenaImpl::AllocateAlignedAndAddCleanupFallback(size_t n, void (*cleanup)(void*)) { return GetSerialArena()->AllocateAlignedAndAddCleanup(n, cleanup); } -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE +PROTOBUF_NOINLINE void ArenaImpl::AddCleanupFallback(void* elem, void (*cleanup)(void*)) { GetSerialArena()->AddCleanup(elem, cleanup); } -inline GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool -ArenaImpl::GetSerialArenaFast(ArenaImpl::SerialArena** arena) { +inline PROTOBUF_ALWAYS_INLINE bool ArenaImpl::GetSerialArenaFast( + ArenaImpl::SerialArena** arena) { // If this thread already owns a block in this arena then try to use that. // This fast path optimizes the case where multiple threads allocate from the // same arena. ThreadCache* tc = &thread_cache(); - if (GOOGLE_PREDICT_TRUE(tc->last_lifecycle_id_seen == lifecycle_id_)) { + if (PROTOBUF_PREDICT_TRUE(tc->last_lifecycle_id_seen == lifecycle_id_)) { *arena = tc->last_serial_arena; return true; } @@ -201,7 +201,7 @@ ArenaImpl::GetSerialArenaFast(ArenaImpl::SerialArena** arena) { // Check whether we own the last accessed SerialArena on this arena. This // fast path optimizes the case where a single thread uses multiple arenas. SerialArena* serial = hint_.load(std::memory_order_acquire); - if (GOOGLE_PREDICT_TRUE(serial != NULL && serial->owner() == tc)) { + if (PROTOBUF_PREDICT_TRUE(serial != NULL && serial->owner() == tc)) { *arena = serial; return true; } @@ -211,14 +211,14 @@ ArenaImpl::GetSerialArenaFast(ArenaImpl::SerialArena** arena) { ArenaImpl::SerialArena* ArenaImpl::GetSerialArena() { SerialArena* arena; - if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) { + if (PROTOBUF_PREDICT_TRUE(GetSerialArenaFast(&arena))) { return arena; } else { return GetSerialArenaFallback(&thread_cache()); } } -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE +PROTOBUF_NOINLINE void* ArenaImpl::SerialArena::AllocateAlignedFallback(size_t n) { // Sync back to current's pos. head_->set_pos(head_->size() - (limit_ - ptr_)); @@ -362,7 +362,7 @@ ArenaImpl::SerialArena* ArenaImpl::SerialArena::New(Block* b, void* owner, return serial; } -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE +PROTOBUF_NOINLINE ArenaImpl::SerialArena* ArenaImpl::GetSerialArenaFallback(void* me) { // Look for this SerialArena in our linked list. SerialArena* serial = threads_.load(std::memory_order_acquire); diff --git a/src/google/protobuf/arena.h b/src/google/protobuf/arena.h index 53099ff616..a38a802103 100644 --- a/src/google/protobuf/arena.h +++ b/src/google/protobuf/arena.h @@ -187,7 +187,7 @@ struct ArenaOptions { // Support for non-RTTI environments. (The metrics hooks API uses type // information.) -#if GOOGLE_PROTOBUF_RTTI +#if PROTOBUF_RTTI #define RTTI_TYPE_ID(type) (&typeid(type)) #else #define RTTI_TYPE_ID(type) (NULL) @@ -245,7 +245,7 @@ struct ArenaOptions { // // Do NOT subclass Arena. This class will be marked as final when C++11 is // enabled. -class LIBPROTOBUF_EXPORT Arena { +class PROTOBUF_EXPORT Arena { public: // Arena constructor taking custom options. See ArenaOptions below for // descriptions of the options available. @@ -295,8 +295,7 @@ class LIBPROTOBUF_EXPORT Arena { // This function also accepts any type T that satisfies the arena message // allocation protocol, documented above. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessage( - Arena* arena, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static T* CreateMessage(Arena* arena, Args&&... args) { static_assert( InternalHelper::is_arena_constructable::value, "CreateMessage can only construct types that are ArenaConstructable"); @@ -322,8 +321,7 @@ class LIBPROTOBUF_EXPORT Arena { // if the object were allocated on the heap (except that the underlying memory // is obtained from the arena). template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* Create(Arena* arena, - Args&&... args) { + PROTOBUF_ALWAYS_INLINE static T* Create(Arena* arena, Args&&... args) { return CreateNoMessage(arena, is_arena_constructable(), std::forward(args)...); } @@ -335,8 +333,8 @@ class LIBPROTOBUF_EXPORT Arena { // (when compiled as C++11) that T is trivially default-constructible and // trivially destructible. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateArray( - Arena* arena, size_t num_elements) { + PROTOBUF_ALWAYS_INLINE static T* CreateArray(Arena* arena, + size_t num_elements) { static_assert(std::is_pod::value, "CreateArray requires a trivially constructible type"); static_assert(std::is_trivially_destructible::value, @@ -363,8 +361,7 @@ class LIBPROTOBUF_EXPORT Arena { // // Combines SpaceAllocated and SpaceUsed. Returns a pair of // . - GOOGLE_PROTOBUF_DEPRECATED_MSG( - "Please use SpaceAllocated() and SpaceUsed()") + PROTOBUF_DEPRECATED_MSG("Please use SpaceAllocated() and SpaceUsed()") std::pair SpaceAllocatedAndUsed() const { return std::make_pair(SpaceAllocated(), SpaceUsed()); } @@ -374,7 +371,7 @@ class LIBPROTOBUF_EXPORT Arena { // Any objects allocated on this arena are unusable after this call. It also // returns the total space used by the arena which is the sums of the sizes // of the allocated blocks. This method is not thread-safe. - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE uint64 Reset() { + PROTOBUF_NOINLINE uint64 Reset() { // Call the reset hook if (on_arena_reset_ != NULL) { on_arena_reset_(this, hooks_cookie_, impl_.SpaceAllocated()); @@ -385,7 +382,7 @@ class LIBPROTOBUF_EXPORT Arena { // Adds |object| to a list of heap-allocated objects to be freed with |delete| // when the arena is destroyed or reset. template - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void Own(T* object) { + PROTOBUF_NOINLINE void Own(T* object) { OwnInternal(object, std::is_convertible()); } @@ -395,7 +392,7 @@ class LIBPROTOBUF_EXPORT Arena { // normally only used for objects that are placement-newed into // arena-allocated memory. template - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void OwnDestructor(T* object) { + PROTOBUF_NOINLINE void OwnDestructor(T* object) { if (object != NULL) { impl_.AddCleanup(object, &internal::arena_destruct_object); } @@ -405,7 +402,7 @@ class LIBPROTOBUF_EXPORT Arena { // will be manually called when the arena is destroyed or reset. This differs // from OwnDestructor() in that any member function may be specified, not only // the class destructor. - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void OwnCustomDestructor( + PROTOBUF_NOINLINE void OwnCustomDestructor( void* object, void (*destruct)(void*)) { impl_.AddCleanup(object, destruct); } @@ -415,8 +412,7 @@ class LIBPROTOBUF_EXPORT Arena { // latter is a virtual call, while this method is a templated call that // resolves at compile-time. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArena( - const T* value) { + PROTOBUF_ALWAYS_INLINE static Arena* GetArena(const T* value) { return GetArenaInternal(value, is_arena_constructable()); } @@ -474,8 +470,8 @@ class LIBPROTOBUF_EXPORT Arena { private: template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessageInternal( - Arena* arena, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static T* CreateMessageInternal(Arena* arena, + Args&&... args) { static_assert( InternalHelper::is_arena_constructable::value, "CreateMessage can only construct types that are ArenaConstructable"); @@ -490,8 +486,7 @@ class LIBPROTOBUF_EXPORT Arena { // slightly different. When the arena pointer is nullptr, it calls T() // instead of T(nullptr). template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessageInternal( - Arena* arena) { + PROTOBUF_ALWAYS_INLINE static T* CreateMessageInternal(Arena* arena) { static_assert( InternalHelper::is_arena_constructable::value, "CreateMessage can only construct types that are ArenaConstructable"); @@ -503,8 +498,8 @@ class LIBPROTOBUF_EXPORT Arena { } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateInternal( - Arena* arena, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static T* CreateInternal(Arena* arena, + Args&&... args) { if (arena == NULL) { return new T(std::forward(args)...); } else { @@ -516,7 +511,7 @@ class LIBPROTOBUF_EXPORT Arena { void CallDestructorHooks(); void OnArenaAllocation(const std::type_info* allocated_type, size_t n) const; inline void AllocHook(const std::type_info* allocated_type, size_t n) const { - if (GOOGLE_PREDICT_FALSE(hooks_cookie_ != NULL)) { + if (PROTOBUF_PREDICT_FALSE(hooks_cookie_ != NULL)) { OnArenaAllocation(allocated_type, n); } } @@ -525,8 +520,7 @@ class LIBPROTOBUF_EXPORT Arena { // allocated type info when the hooks are in place in ArenaOptions and // the cookie is not null. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void* AllocateInternal( - bool skip_explicit_ownership) { + PROTOBUF_ALWAYS_INLINE void* AllocateInternal(bool skip_explicit_ownership) { const size_t n = internal::AlignUpTo8(sizeof(T)); AllocHook(RTTI_TYPE_ID(T), n); // Monitor allocation if needed. @@ -544,27 +538,29 @@ class LIBPROTOBUF_EXPORT Arena { // user code. These are used only internally from LazyField and Repeated // fields, since they are designed to work in all mode combinations. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Msg* DoCreateMaybeMessage( - Arena* arena, std::true_type, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static Msg* DoCreateMaybeMessage(Arena* arena, + std::true_type, + Args&&... args) { return CreateMessageInternal(arena, std::forward(args)...); } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* DoCreateMaybeMessage( - Arena* arena, std::false_type, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static T* DoCreateMaybeMessage(Arena* arena, + std::false_type, + Args&&... args) { return CreateInternal(arena, std::forward(args)...); } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMaybeMessage( - Arena* arena, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static T* CreateMaybeMessage(Arena* arena, + Args&&... args) { return DoCreateMaybeMessage(arena, is_arena_constructable(), std::forward(args)...); } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateNoMessage( - Arena* arena, std::true_type, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static T* CreateNoMessage(Arena* arena, std::true_type, + Args&&... args) { // User is constructing with Create() despite the fact that T supports arena // construction. In this case we have to delegate to CreateInternal(), and // we can't use any CreateMaybeMessage() specialization that may be defined. @@ -572,8 +568,9 @@ class LIBPROTOBUF_EXPORT Arena { } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateNoMessage( - Arena* arena, std::false_type, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static T* CreateNoMessage(Arena* arena, + std::false_type, + Args&&... args) { // User is constructing with Create() and the type does not support arena // construction. In this case we can delegate to CreateMaybeMessage() and // use any specialization that may be available for that. @@ -583,8 +580,7 @@ class LIBPROTOBUF_EXPORT Arena { // Just allocate the required size for the given type assuming the // type has a trivial constructor. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateInternalRawArray( - size_t num_elements) { + PROTOBUF_ALWAYS_INLINE T* CreateInternalRawArray(size_t num_elements) { GOOGLE_CHECK_LE(num_elements, std::numeric_limits::max() / sizeof(T)) << "Requested size is too large to fit into size_t."; const size_t n = internal::AlignUpTo8(sizeof(T) * num_elements); @@ -594,13 +590,13 @@ class LIBPROTOBUF_EXPORT Arena { } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* DoCreate( - bool skip_explicit_ownership, Args&&... args) { + PROTOBUF_ALWAYS_INLINE T* DoCreate(bool skip_explicit_ownership, + Args&&... args) { return new (AllocateInternal(skip_explicit_ownership)) T(std::forward(args)...); } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* DoCreateMessage(Args&&... args) { + PROTOBUF_ALWAYS_INLINE T* DoCreateMessage(Args&&... args) { return InternalHelper::Construct( AllocateInternal(InternalHelper::is_destructor_skippable::value), this, std::forward(args)...); @@ -644,15 +640,13 @@ class LIBPROTOBUF_EXPORT Arena { // all template instantiations to one for generic Message reduces code size, // using the virtual destructor instead. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void OwnInternal(T* object, - std::true_type) { + PROTOBUF_ALWAYS_INLINE void OwnInternal(T* object, std::true_type) { if (object != NULL) { impl_.AddCleanup(object, &internal::arena_delete_object); } } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void OwnInternal(T* object, - std::false_type) { + PROTOBUF_ALWAYS_INLINE void OwnInternal(T* object, std::false_type) { if (object != NULL) { impl_.AddCleanup(object, &internal::arena_delete_object); } @@ -662,14 +656,14 @@ class LIBPROTOBUF_EXPORT Arena { // InternalArenaConstructable_ tags can be associated with an arena, and such // objects must implement a GetArenaNoVirtual() method. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArenaInternal( - const T* value, std::true_type) { + PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value, + std::true_type) { return InternalHelper::GetArena(value); } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArenaInternal( - const T* /* value */, std::false_type) { + PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* /* value */, + std::false_type) { return NULL; } diff --git a/src/google/protobuf/arena_impl.h b/src/google/protobuf/arena_impl.h index 0b71819d29..a0fb1069c8 100644 --- a/src/google/protobuf/arena_impl.h +++ b/src/google/protobuf/arena_impl.h @@ -61,7 +61,7 @@ inline size_t AlignUpTo8(size_t n) { // in turn would be templates, which will/cannot happen. However separating // the memory allocation part from the cruft of the API users expect we can // use #ifdef the select the best implementation based on hardware / OS. -class LIBPROTOBUF_EXPORT ArenaImpl { +class PROTOBUF_EXPORT ArenaImpl { public: struct Options { size_t start_block_size; @@ -137,7 +137,7 @@ class LIBPROTOBUF_EXPORT ArenaImpl { class Block; // A thread-unsafe Arena that can only be used within its owning thread. - class LIBPROTOBUF_EXPORT SerialArena { + class PROTOBUF_EXPORT SerialArena { public: // The allocate/free methods here are a little strange, since SerialArena is // allocated inside a Block which it also manages. This is to avoid doing @@ -157,7 +157,7 @@ class LIBPROTOBUF_EXPORT ArenaImpl { void* AllocateAligned(size_t n) { GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned. GOOGLE_DCHECK_GE(limit_, ptr_); - if (GOOGLE_PREDICT_FALSE(static_cast(limit_ - ptr_) < n)) { + if (PROTOBUF_PREDICT_FALSE(static_cast(limit_ - ptr_) < n)) { return AllocateAlignedFallback(n); } void* ret = ptr_; @@ -169,7 +169,7 @@ class LIBPROTOBUF_EXPORT ArenaImpl { } void AddCleanup(void* elem, void (*cleanup)(void*)) { - if (GOOGLE_PREDICT_FALSE(cleanup_ptr_ == cleanup_limit_)) { + if (PROTOBUF_PREDICT_FALSE(cleanup_ptr_ == cleanup_limit_)) { AddCleanupFallback(elem, cleanup); return; } @@ -212,7 +212,7 @@ class LIBPROTOBUF_EXPORT ArenaImpl { // Blocks are variable length malloc-ed objects. The following structure // describes the common header for all blocks. - class LIBPROTOBUF_EXPORT Block { + class PROTOBUF_EXPORT Block { public: Block(size_t size, Block* next); diff --git a/src/google/protobuf/arena_test_util.h b/src/google/protobuf/arena_test_util.h index 9c821b90d7..fdbaca068a 100644 --- a/src/google/protobuf/arena_test_util.h +++ b/src/google/protobuf/arena_test_util.h @@ -33,6 +33,8 @@ #include #include +#include +#include #include namespace google { @@ -41,7 +43,15 @@ namespace protobuf { template void TestParseCorruptedString(const T& message) { int success_count = 0; - string s = message.SerializeAsString(); + std::string s; + { + // Map order is not deterministic. To make the test deterministic we want + // to serialize the proto deterministically. + io::StringOutputStream output(&s); + io::CodedOutputStream out(&output); + out.SetSerializationDeterministic(true); + message.SerializePartialToCodedStream(&out); + } const int kMaxIters = 900; const int stride = s.size() <= kMaxIters ? 1 : s.size() / kMaxIters; const int start = stride == 1 || use_arena ? 0 : (stride + 1) / 2; diff --git a/src/google/protobuf/arena_unittest.cc b/src/google/protobuf/arena_unittest.cc index 92e5c84d2c..361b83efdd 100644 --- a/src/google/protobuf/arena_unittest.cc +++ b/src/google/protobuf/arena_unittest.cc @@ -586,7 +586,7 @@ TEST(ArenaTest, ReleaseFromArenaMessageMakesCopy) { delete nested_string; } -#if GOOGLE_PROTOBUF_RTTI +#if PROTOBUF_RTTI TEST(ArenaTest, ReleaseFromArenaMessageUsingReflectionMakesCopy) { TestAllTypes::NestedMessage* nested_msg = NULL; // Note: no string: reflection API only supports releasing submessages. @@ -603,7 +603,7 @@ TEST(ArenaTest, ReleaseFromArenaMessageUsingReflectionMakesCopy) { EXPECT_EQ(42, nested_msg->bb()); delete nested_msg; } -#endif // GOOGLE_PROTOBUF_RTTI +#endif // PROTOBUF_RTTI TEST(ArenaTest, SetAllocatedAcrossArenas) { Arena arena1; @@ -1129,7 +1129,7 @@ TEST(ArenaTest, RepeatedFieldOnArena) { } -#if GOOGLE_PROTOBUF_RTTI +#if PROTOBUF_RTTI TEST(ArenaTest, MutableMessageReflection) { Arena arena; TestAllTypes* message = Arena::CreateMessage(&arena); @@ -1153,7 +1153,7 @@ TEST(ArenaTest, MutableMessageReflection) { EXPECT_EQ(submessage_expected, submessage); EXPECT_EQ(&arena, submessage->GetArena()); } -#endif // GOOGLE_PROTOBUF_RTTI +#endif // PROTOBUF_RTTI void FillArenaAwareFields(TestAllTypes* message) { @@ -1199,7 +1199,7 @@ TEST(ArenaTest, ParseCorruptedString) { TestParseCorruptedString(message); } -#if GOOGLE_PROTOBUF_RTTI +#if PROTOBUF_RTTI // Test construction on an arena via generic MessageLite interface. We should be // able to successfully deserialize on the arena without incurring heap // allocations, i.e., everything should still be arena-allocation-aware. @@ -1228,7 +1228,7 @@ TEST(ArenaTest, MessageLiteOnArena) { arena.Reset(); } -#endif // GOOGLE_PROTOBUF_RTTI +#endif // PROTOBUF_RTTI // RepeatedField should support non-POD types, and invoke constructors and diff --git a/src/google/protobuf/arenastring.h b/src/google/protobuf/arenastring.h index 168fc972b8..cb4dc8b3ad 100644 --- a/src/google/protobuf/arenastring.h +++ b/src/google/protobuf/arenastring.h @@ -39,6 +39,8 @@ #include #include +#include + // This is the implementation of arena string fields written for the open-source // release. The ArenaStringPtr struct below is an internal implementation class // and *should not be used* by user code. It is used to collect string @@ -63,7 +65,7 @@ class TaggedPtr { uintptr_t ptr_; }; -struct LIBPROTOBUF_EXPORT ArenaStringPtr { +struct PROTOBUF_EXPORT ArenaStringPtr { inline void Set(const ::std::string* default_value, const ::std::string& value, ::google::protobuf::Arena* arena) { if (ptr_ == default_value) { @@ -168,11 +170,12 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { // Swaps internal pointers. Arena-safety semantics: this is guarded by the // logic in Swap()/UnsafeArenaSwap() at the message level, so this method is // 'unsafe' if called directly. - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Swap(ArenaStringPtr* other) { + PROTOBUF_ALWAYS_INLINE void Swap(ArenaStringPtr* other) { std::swap(ptr_, other->ptr_); } - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Swap( - ArenaStringPtr* other, const ::std::string* default_value, Arena* arena) { + PROTOBUF_ALWAYS_INLINE void Swap(ArenaStringPtr* other, + const ::std::string* default_value, + Arena* arena) { #ifndef NDEBUG // For debug builds, we swap the contents of the string, rather than the // string instances themselves. This invalidates previously taken const @@ -364,14 +367,14 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { private: ::std::string* ptr_; - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE + PROTOBUF_NOINLINE void CreateInstance(::google::protobuf::Arena* arena, const ::std::string* initial_value) { GOOGLE_DCHECK(initial_value != NULL); // uses "new ::std::string" when arena is nullptr ptr_ = Arena::Create< ::std::string >(arena, *initial_value); } - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE + PROTOBUF_NOINLINE void CreateInstanceNoArena(const ::std::string* initial_value) { GOOGLE_DCHECK(initial_value != NULL); ptr_ = new ::std::string(*initial_value); @@ -398,6 +401,8 @@ inline void ArenaStringPtr::AssignWithDefault(const ::std::string* default_value } // namespace internal } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_ARENASTRING_H__ diff --git a/src/google/protobuf/compiler/annotation_test_util.h b/src/google/protobuf/compiler/annotation_test_util.h index 34c3f6a979..fbd3dec5f3 100644 --- a/src/google/protobuf/compiler/annotation_test_util.h +++ b/src/google/protobuf/compiler/annotation_test_util.h @@ -49,15 +49,15 @@ namespace annotation_test_util { // file_content = content of Foo.java // file_info = parsed content of Foo.java.pb.meta struct ExpectedOutput { - string file_path; - string file_content; + std::string file_path; + std::string file_content; GeneratedCodeInfo file_info; - explicit ExpectedOutput(const string& file_path) : file_path(file_path) {} + explicit ExpectedOutput(const std::string& file_path) : file_path(file_path) {} }; // Creates a file with name `filename` and content `data` in temp test // directory. -void AddFile(const string& filename, const string& data); +void AddFile(const std::string& filename, const std::string& data); // Runs proto compiler. Captures proto file structrue in FileDescriptorProto. // Files will be generated in TestTempDir() folder. Callers of this @@ -70,17 +70,17 @@ void AddFile(const string& filename, const string& data); // annotation_unittest.cc for an example of how to initialize it. // file: output parameter, will be set to the descriptor of the proto file // specified in filename. -bool RunProtoCompiler(const string& filename, - const string& plugin_specific_args, +bool RunProtoCompiler(const std::string& filename, + const std::string& plugin_specific_args, CommandLineInterface* cli, FileDescriptorProto* file); -bool DecodeMetadata(const string& path, GeneratedCodeInfo* info); +bool DecodeMetadata(const std::string& path, GeneratedCodeInfo* info); // Finds all of the Annotations for a given source file and path. // See Location.path in http://google3/net/proto2/proto/descriptor.proto for // explanation of what path vector is. void FindAnnotationsOnPath( - const GeneratedCodeInfo& info, const string& source_file, + const GeneratedCodeInfo& info, const std::string& source_file, const std::vector& path, std::vector* annotations); @@ -90,21 +90,21 @@ void FindAnnotationsOnPath( // http://google3/net/proto2/proto/descriptor.proto for explanation of what path // vector is. const GeneratedCodeInfo::Annotation* FindAnnotationOnPath( - const GeneratedCodeInfo& info, const string& source_file, + const GeneratedCodeInfo& info, const std::string& source_file, const std::vector& path); // Returns true if at least one of the provided annotations covers a given // substring in file_content. bool AtLeastOneAnnotationMatchesSubstring( - const string& file_content, + const std::string& file_content, const std::vector& annotations, - const string& expected_text); + const std::string& expected_text); // Returns true if the provided annotation covers a given substring in // file_content. -bool AnnotationMatchesSubstring(const string& file_content, +bool AnnotationMatchesSubstring(const std::string& file_content, const GeneratedCodeInfo::Annotation* annotation, - const string& expected_text); + const std::string& expected_text); } // namespace annotation_test_util } // namespace compiler diff --git a/src/google/protobuf/compiler/code_generator.h b/src/google/protobuf/compiler/code_generator.h index a1cd6113e6..b1eb61accb 100644 --- a/src/google/protobuf/compiler/code_generator.h +++ b/src/google/protobuf/compiler/code_generator.h @@ -43,6 +43,8 @@ #include #include +#include + namespace google { namespace protobuf { @@ -61,7 +63,7 @@ class GeneratorContext; // The abstract interface to a class which generates code implementing a // particular proto file in a particular language. A number of these may // be registered with CommandLineInterface to support various languages. -class LIBPROTOC_EXPORT CodeGenerator { +class PROTOC_EXPORT CodeGenerator { public: inline CodeGenerator() {} virtual ~CodeGenerator(); @@ -78,9 +80,9 @@ class LIBPROTOC_EXPORT CodeGenerator { // Returns true if successful. Otherwise, sets *error to a description of // the problem (e.g. "invalid parameter") and returns false. virtual bool Generate(const FileDescriptor* file, - const string& parameter, + const std::string& parameter, GeneratorContext* generator_context, - string* error) const = 0; + std::string* error) const = 0; // Generates code for all given proto files. // @@ -94,9 +96,9 @@ class LIBPROTOC_EXPORT CodeGenerator { // Returns true if successful. Otherwise, sets *error to a description of // the problem (e.g. "invalid parameter") and returns false. virtual bool GenerateAll(const std::vector& files, - const string& parameter, + const std::string& parameter, GeneratorContext* generator_context, - string* error) const; + std::string* error) const; // This is no longer used, but this class is part of the opensource protobuf // library, so it has to remain to keep vtables the same for the current @@ -112,7 +114,7 @@ class LIBPROTOC_EXPORT CodeGenerator { // abstract interface represents the directory to which the CodeGenerator is // to write and other information about the context in which the Generator // runs. -class LIBPROTOC_EXPORT GeneratorContext { +class PROTOC_EXPORT GeneratorContext { public: inline GeneratorContext() { } @@ -128,10 +130,10 @@ class LIBPROTOC_EXPORT GeneratorContext { // generate the files "foo/bar.pb.h" and "foo/bar.pb.cc"; note that // "foo/" is included in these filenames. The filename is not allowed to // contain "." or ".." components. - virtual io::ZeroCopyOutputStream* Open(const string& filename) = 0; + virtual io::ZeroCopyOutputStream* Open(const std::string& filename) = 0; // Similar to Open() but the output will be appended to the file if exists - virtual io::ZeroCopyOutputStream* OpenForAppend(const string& filename); + virtual io::ZeroCopyOutputStream* OpenForAppend(const std::string& filename); // Creates a ZeroCopyOutputStream which will insert code into the given file // at the given insertion point. See plugin.proto (plugin.pb.h) for more @@ -140,7 +142,7 @@ class LIBPROTOC_EXPORT GeneratorContext { // // WARNING: This feature is currently EXPERIMENTAL and is subject to change. virtual io::ZeroCopyOutputStream* OpenForInsert( - const string& filename, const string& insertion_point); + const std::string& filename, const std::string& insertion_point); // Returns a vector of FileDescriptors for all the files being compiled // in this run. Useful for languages, such as Go, that treat files @@ -166,11 +168,13 @@ typedef GeneratorContext OutputDirectory; // "foo=bar,baz,qux=corge" // parses to the pairs: // ("foo", "bar"), ("baz", ""), ("qux", "corge") -LIBPROTOC_EXPORT void ParseGeneratorParameter( - const string&, std::vector >*); +PROTOC_EXPORT void ParseGeneratorParameter( + const std::string&, std::vector >*); } // namespace compiler } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_CODE_GENERATOR_H__ diff --git a/src/google/protobuf/compiler/command_line_interface.cc b/src/google/protobuf/compiler/command_line_interface.cc index 8005677456..4d1ef09b66 100644 --- a/src/google/protobuf/compiler/command_line_interface.cc +++ b/src/google/protobuf/compiler/command_line_interface.cc @@ -84,6 +84,8 @@ #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -169,7 +171,8 @@ bool VerifyDirectoryExists(const string& path) { bool TryCreateParentDirectory(const string& prefix, const string& filename) { // Recursively create parent directories to the output file. // On Windows, both '/' and '\' are valid path separators. - std::vector parts = Split(filename, "/\\", true); + std::vector parts = + Split(filename, "/\\", true); string path_so_far = prefix; for (int i = 0; i < parts.size() - 1; i++) { path_so_far += parts[i]; @@ -1546,7 +1549,7 @@ CommandLineInterface::InterpretArgument(const string& name, std::cout << version_info_ << std::endl; } std::cout << "libprotoc " - << protobuf::internal::VersionString(GOOGLE_PROTOBUF_VERSION) + << protobuf::internal::VersionString(PROTOBUF_VERSION) << std::endl; return PARSE_ARGUMENT_DONE_AND_EXIT; // Exit without running compiler. @@ -1932,10 +1935,10 @@ bool CommandLineInterface::GeneratePluginOutput( google::protobuf::compiler::Version* version = request.mutable_compiler_version(); - version->set_major(GOOGLE_PROTOBUF_VERSION / 1000000); - version->set_minor(GOOGLE_PROTOBUF_VERSION / 1000 % 1000); - version->set_patch(GOOGLE_PROTOBUF_VERSION % 1000); - version->set_suffix(GOOGLE_PROTOBUF_VERSION_SUFFIX); + version->set_major(PROTOBUF_VERSION / 1000000); + version->set_minor(PROTOBUF_VERSION / 1000 % 1000); + version->set_patch(PROTOBUF_VERSION % 1000); + version->set_suffix(PROTOBUF_VERSION_SUFFIX); // Invoke the plugin. Subprocess subprocess; diff --git a/src/google/protobuf/compiler/command_line_interface.h b/src/google/protobuf/compiler/command_line_interface.h index 8dba994961..cef29ffe2d 100644 --- a/src/google/protobuf/compiler/command_line_interface.h +++ b/src/google/protobuf/compiler/command_line_interface.h @@ -47,6 +47,8 @@ #include +#include + namespace google { namespace protobuf { @@ -102,7 +104,7 @@ class DiskSourceTree; // importer.h // relative virtual path, the physical file path takes precendence. // // For a full description of the command-line syntax, invoke it with --help. -class LIBPROTOC_EXPORT CommandLineInterface { +class PROTOC_EXPORT CommandLineInterface { public: static const char* const kPathSeparator; @@ -125,9 +127,9 @@ class LIBPROTOC_EXPORT CommandLineInterface { // protoc --foo_out=enable_bar:outdir // The text before the colon is passed to CodeGenerator::Generate() as the // "parameter". - void RegisterGenerator(const string& flag_name, + void RegisterGenerator(const std::string& flag_name, CodeGenerator* generator, - const string& help_text); + const std::string& help_text); // Register a code generator for a language. // Besides flag_name you can specify another option_flag_name that could be @@ -137,10 +139,10 @@ class LIBPROTOC_EXPORT CommandLineInterface { // Then you could invoke the compiler with a command like: // protoc --foo_out=enable_bar:outdir --foo_opt=enable_baz // This will pass "enable_bar,enable_baz" as the parameter to the generator. - void RegisterGenerator(const string& flag_name, - const string& option_flag_name, + void RegisterGenerator(const std::string& flag_name, + const std::string& option_flag_name, CodeGenerator* generator, - const string& help_text); + const std::string& help_text); // Enables "plugins". In this mode, if a command-line flag ends with "_out" // but does not match any registered generator, the compiler will attempt to @@ -178,7 +180,7 @@ class LIBPROTOC_EXPORT CommandLineInterface { // protoc --plug_out=enable_bar:outdir --plug_opt=enable_baz // This will pass "enable_bar,enable_baz" as the parameter to the plugin. // - void AllowPlugins(const string& exe_name_prefix); + void AllowPlugins(const std::string& exe_name_prefix); // Run the Protocol Compiler with the given command-line parameters. // Returns the error code which should be returned by main(). @@ -196,7 +198,7 @@ class LIBPROTOC_EXPORT CommandLineInterface { // Provides some text which will be printed when the --version flag is // used. The version of libprotoc will also be printed on the next line // after this text. - void SetVersionInfo(const string& text) { + void SetVersionInfo(const std::string& text) { version_info_ = text; } @@ -207,14 +209,14 @@ class LIBPROTOC_EXPORT CommandLineInterface { class ErrorPrinter; class GeneratorContextImpl; class MemoryOutputStream; - typedef std::unordered_map GeneratorContextMap; + typedef std::unordered_map GeneratorContextMap; // Clear state from previous Run(). void Clear(); // Remaps the proto file so that it is relative to one of the ddirectories // in proto_path_. Returns false if an error occurred. - bool MakeProtoProtoPathRelative(DiskSourceTree* source_tree, string* proto); + bool MakeProtoProtoPathRelative(DiskSourceTree* source_tree, std::string* proto); // Remaps each file in input_files_ so that it is relative to one of the // directories in proto_path_. Returns false if an error occurred. @@ -234,7 +236,7 @@ class LIBPROTOC_EXPORT CommandLineInterface { // Read an argument file and append the file's content to the list of // arguments. Return false if the file cannot be read. - bool ExpandArgumentFile(const string& file, std::vector* arguments); + bool ExpandArgumentFile(const std::string& file, std::vector* arguments); // Parses a command-line argument into a name/value pair. Returns // true if the next argument in the argv should be used as the value, @@ -247,11 +249,11 @@ class LIBPROTOC_EXPORT CommandLineInterface { // name = "--cpp_out", value = "src/foo.pb2.cc" // "foo.proto" -> // name = "", value = "foo.proto" - bool ParseArgument(const char* arg, string* name, string* value); + bool ParseArgument(const char* arg, std::string* name, std::string* value); // Interprets arguments parsed with ParseArgument. - ParseArgumentStatus InterpretArgument(const string& name, - const string& value); + ParseArgumentStatus InterpretArgument(const std::string& name, + const std::string& value); // Print the --help text to stderr. void PrintHelpText(); @@ -273,8 +275,8 @@ class LIBPROTOC_EXPORT CommandLineInterface { GeneratorContext* generator_context); bool GeneratePluginOutput( const std::vector& parsed_files, - const string& plugin_name, const string& parameter, - GeneratorContext* generator_context, string* error); + const std::string& plugin_name, const std::string& parameter, + GeneratorContext* generator_context, std::string* error); // Implements --encode and --decode. bool EncodeOrDecode(const DescriptorPool* pool); @@ -324,36 +326,36 @@ class LIBPROTOC_EXPORT CommandLineInterface { // ----------------------------------------------------------------- // The name of the executable as invoked (i.e. argv[0]). - string executable_name_; + std::string executable_name_; // Version info set with SetVersionInfo(). - string version_info_; + std::string version_info_; // Registered generators. struct GeneratorInfo { - string flag_name; - string option_flag_name; + std::string flag_name; + std::string option_flag_name; CodeGenerator* generator; - string help_text; + std::string help_text; }; - typedef std::map GeneratorMap; + typedef std::map GeneratorMap; GeneratorMap generators_by_flag_name_; GeneratorMap generators_by_option_name_; // A map from generator names to the parameters specified using the option // flag. For example, if the user invokes the compiler with: // protoc --foo_out=outputdir --foo_opt=enable_bar ... // Then there will be an entry ("--foo_out", "enable_bar") in this map. - std::map generator_parameters_; + std::map generator_parameters_; // Similar to generator_parameters_, but stores the parameters for plugins. - std::map plugin_parameters_; + std::map plugin_parameters_; // See AllowPlugins(). If this is empty, plugins aren't allowed. - string plugin_prefix_; + std::string plugin_prefix_; // Maps specific plugin names to files. When executing a plugin, this map // is searched first to find the plugin executable. If not found here, the // PATH (or other OS-specific search strategy) is searched. - std::map plugins_; + std::map plugins_; // Stuff parsed from command line. enum Mode { @@ -379,44 +381,44 @@ class LIBPROTOC_EXPORT CommandLineInterface { ErrorFormat error_format_; - std::vector > + std::vector > proto_path_; // Search path for proto files. - std::vector input_files_; // Names of the input proto files. + std::vector input_files_; // Names of the input proto files. // Names of proto files which are allowed to be imported. Used by build // systems to enforce depend-on-what-you-import. - std::set direct_dependencies_; + std::set direct_dependencies_; bool direct_dependencies_explicitly_set_; // If there's a violation of depend-on-what-you-import, this string will be // presented to the user. "%s" will be replaced with the violating import. - string direct_dependencies_violation_msg_; + std::string direct_dependencies_violation_msg_; // output_directives_ lists all the files we are supposed to output and what // generator to use for each. struct OutputDirective { - string name; // E.g. "--foo_out" + std::string name; // E.g. "--foo_out" CodeGenerator* generator; // NULL for plugins - string parameter; - string output_location; + std::string parameter; + std::string output_location; }; std::vector output_directives_; // When using --encode or --decode, this names the type we are encoding or // decoding. (Empty string indicates --decode_raw.) - string codec_type_; + std::string codec_type_; // If --descriptor_set_in was given, these are filenames containing // parsed FileDescriptorSets to be used for loading protos. Otherwise, empty. - std::vector descriptor_set_in_names_; + std::vector descriptor_set_in_names_; // If --descriptor_set_out was given, this is the filename to which the // FileDescriptorSet should be written. Otherwise, empty. - string descriptor_set_out_name_; + std::string descriptor_set_out_name_; // If --dependency_out was given, this is the path to the file where the // dependency file will be written. Otherwise, empty. - string dependency_out_name_; + std::string dependency_out_name_; // True if --include_imports was given, meaning that we should // write all transitive dependencies to the DescriptorSet. Otherwise, only @@ -437,4 +439,6 @@ class LIBPROTOC_EXPORT CommandLineInterface { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_COMMAND_LINE_INTERFACE_H__ diff --git a/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc index 4c135649f9..a19ad595ff 100644 --- a/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc +++ b/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc @@ -50,6 +50,7 @@ #include #include #include +#include #include #include #include @@ -98,6 +99,13 @@ class MockGeneratorContext : public GeneratorContext { &actual_contents, true)) << physical_filename; CleanStringLineEndings(&actual_contents, false); + +#ifdef WRITE_FILES // Define to debug mismatched files. + GOOGLE_CHECK_OK( + File::SetContents("/tmp/1.cc", *expected_contents, true)); + GOOGLE_CHECK_OK(File::SetContents("/tmp/2.cc", actual_contents, true)); +#endif + EXPECT_EQ(*expected_contents, actual_contents) << physical_filename << " needs to be regenerated. Please run " @@ -119,8 +127,8 @@ class MockGeneratorContext : public GeneratorContext { std::map files_; }; -const char kDescriptorParameter[] = "dllexport_decl=LIBPROTOBUF_EXPORT"; -const char kPluginParameter[] = "dllexport_decl=LIBPROTOC_EXPORT"; +const char kDescriptorParameter[] = "dllexport_decl=PROTOBUF_EXPORT"; +const char kPluginParameter[] = "dllexport_decl=PROTOC_EXPORT"; const char kNormalParameter[] = ""; const char* test_protos[][2] = { diff --git a/src/google/protobuf/compiler/cpp/cpp_enum.h b/src/google/protobuf/compiler/cpp/cpp_enum.h index 55e6b83548..6b9700ae5d 100644 --- a/src/google/protobuf/compiler/cpp/cpp_enum.h +++ b/src/google/protobuf/compiler/cpp/cpp_enum.h @@ -58,7 +58,7 @@ class EnumGenerator { public: // See generator.cc for the meaning of dllexport_decl. EnumGenerator(const EnumDescriptor* descriptor, - const std::map& vars, const Options& options); + const std::map& vars, const Options& options); ~EnumGenerator(); // Generate header code defining the enum. This code should be placed @@ -85,12 +85,12 @@ class EnumGenerator { private: const EnumDescriptor* descriptor_; - const string classname_; + const std::string classname_; const Options& options_; // whether to generate the *_ARRAYSIZE constant. const bool generate_array_size_; - std::map variables_; + std::map variables_; friend class FileGenerator; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator); diff --git a/src/google/protobuf/compiler/cpp/cpp_extension.cc b/src/google/protobuf/compiler/cpp/cpp_extension.cc index 25bcc333dd..f866eb6e0b 100644 --- a/src/google/protobuf/compiler/cpp/cpp_extension.cc +++ b/src/google/protobuf/compiler/cpp/cpp_extension.cc @@ -137,6 +137,16 @@ void ExtensionGenerator::GenerateDeclaration(io::Printer* printer) const { } void ExtensionGenerator::GenerateDefinition(io::Printer* printer) { + // If we are building for lite with implicit weak fields, we want to skip over + // any custom options (i.e. extensions of messages from descriptor.proto). + // This prevents the creation of any unnecessary linker references to the + // descriptor messages. + if (options_.lite_implicit_weak_fields && + descriptor_->containing_type()->file()->name() == + "net/proto2/proto/descriptor.proto") { + return; + } + Formatter format(printer, variables_); string default_str; // If this is a class member, it needs to be declared in its class scope. diff --git a/src/google/protobuf/compiler/cpp/cpp_extension.h b/src/google/protobuf/compiler/cpp/cpp_extension.h index c316f5dabc..72413f6b28 100644 --- a/src/google/protobuf/compiler/cpp/cpp_extension.h +++ b/src/google/protobuf/compiler/cpp/cpp_extension.h @@ -75,10 +75,10 @@ class ExtensionGenerator { private: const FieldDescriptor* descriptor_; - string type_traits_; + std::string type_traits_; Options options_; - std::map variables_; + std::map variables_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator); }; diff --git a/src/google/protobuf/compiler/cpp/cpp_field.h b/src/google/protobuf/compiler/cpp/cpp_field.h index 4561b33e85..43a3e3674d 100644 --- a/src/google/protobuf/compiler/cpp/cpp_field.h +++ b/src/google/protobuf/compiler/cpp/cpp_field.h @@ -61,11 +61,11 @@ namespace cpp { // ['name', 'index', 'number', 'classname', 'declared_type', 'tag_size', // 'deprecation']. void SetCommonFieldVariables(const FieldDescriptor* descriptor, - std::map* variables, + std::map* variables, const Options& options); void SetCommonOneofFieldVariables(const FieldDescriptor* descriptor, - std::map* variables); + std::map* variables); class FieldGenerator { public: @@ -203,7 +203,7 @@ class FieldGenerator { protected: const FieldDescriptor* descriptor_; const Options& options_; - std::map variables_; + std::map variables_; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator); diff --git a/src/google/protobuf/compiler/cpp/cpp_file.cc b/src/google/protobuf/compiler/cpp/cpp_file.cc index 414da2f8ad..1e80715dbc 100644 --- a/src/google/protobuf/compiler/cpp/cpp_file.cc +++ b/src/google/protobuf/compiler/cpp/cpp_file.cc @@ -256,6 +256,8 @@ void FileGenerator::GenerateProtoHeader(io::Printer* printer, GenerateHeader(printer); + IncludeFile("net/proto2/public/port_undef.inc", printer); + GenerateBottomHeaderGuard(printer, filename_identifier); } @@ -425,20 +427,6 @@ void FileGenerator::GenerateSourceIncludes(io::Printer* printer) { } } - // TODO(gerbens) Remove this when all code in google is using the same - // proto library. This is a temporary hack to force build errors if - // the proto library is compiled with GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - // and is also linking internal proto2. This is to prevent regressions while - // we work cleaning up the code base. After this is completed and we have - // one proto lib all code uses this should be removed. - if (options_.opensource_runtime) { - format( - "// This is a temporary google only hack\n" - "#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS\n" - "#include \"third_party/protobuf/version.h\"\n" - "#endif\n"); - } - format("// @@protoc_insertion_point(includes)\n"); IncludeFile("net/proto2/public/port_def.inc", printer); } @@ -702,6 +690,8 @@ void FileGenerator::GenerateSource(io::Printer* printer) { format( "\n" "// @@protoc_insertion_point(global_scope)\n"); + + IncludeFile("net/proto2/public/port_undef.inc", printer); } void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) { @@ -751,7 +741,7 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) { format( "\n" "const $uint32$ $tablename$::offsets[] " - "$GOOGLE_PROTOBUF$_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n"); + "PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {\n"); format.Indent(); std::vector > pairs; pairs.reserve(message_generators_.size()); @@ -762,7 +752,7 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) { format( "};\n" "static const ::$proto_ns$::internal::MigrationSchema schemas[] " - "$GOOGLE_PROTOBUF$_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n"); + "PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {\n"); format.Indent(); { int offset = 0; @@ -958,7 +948,7 @@ void FileGenerator::GenerateTables(io::Printer* printer) { format( "PROTOBUF_CONSTEXPR_VAR ::$proto_ns$::internal::ParseTableField\n" " const $tablename$::entries[] " - "$GOOGLE_PROTOBUF$_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n"); + "PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {\n"); format.Indent(); std::vector entries; @@ -981,7 +971,7 @@ void FileGenerator::GenerateTables(io::Printer* printer) { "PROTOBUF_CONSTEXPR_VAR " "::$proto_ns$::internal::AuxillaryParseTableField\n" " const $tablename$::aux[] " - "$GOOGLE_PROTOBUF$_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n"); + "PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {\n"); format.Indent(); std::vector aux_entries; @@ -1001,7 +991,7 @@ void FileGenerator::GenerateTables(io::Printer* printer) { "};\n" "PROTOBUF_CONSTEXPR_VAR ::$proto_ns$::internal::ParseTable const\n" " $tablename$::schema[] " - "$GOOGLE_PROTOBUF$_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n"); + "PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {\n"); format.Indent(); size_t offset = 0; @@ -1199,25 +1189,25 @@ void FileGenerator::GenerateLibraryIncludes(io::Printer* printer) { } if (options_.opensource_runtime) { - DoIncludeFile("net/proto2/public/stubs/common.h", false, printer); - // Verify the protobuf library header version is compatible with the protoc // version before going any further. + IncludeFile("net/proto2/public/port_def.inc", printer); format( - "#if GOOGLE_PROTOBUF_VERSION < $1$\n" + "#if PROTOBUF_VERSION < $1$\n" "#error This file was generated by a newer version of protoc which is\n" "#error incompatible with your Protocol Buffer headers. Please update\n" "#error your headers.\n" "#endif\n" - "#if $2$ < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION\n" + "#if $2$ < PROTOBUF_MIN_PROTOC_VERSION\n" "#error This file was generated by an older version of protoc which " "is\n" "#error incompatible with your Protocol Buffer headers. Please\n" "#error regenerate this file with a newer version of protoc.\n" "#endif\n" "\n", - GOOGLE_PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC, // 1 - GOOGLE_PROTOBUF_VERSION); // 2 + PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC, // 1 + PROTOBUF_VERSION); // 2 + IncludeFile("net/proto2/public/port_undef.inc", printer); } // OK, it's now safe to #include other files. @@ -1341,11 +1331,11 @@ void FileGenerator::GenerateGlobalStateFunctionDeclarations( // These tables describe how to serialize and parse messages. Used // for table driven code. " static const ::$proto_ns$::internal::ParseTableField entries[]\n" - " $GOOGLE_PROTOBUF$_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold);\n" + " PROTOBUF_SECTION_VARIABLE(protodesc_cold);\n" " static const ::$proto_ns$::internal::AuxillaryParseTableField aux[]\n" - " $GOOGLE_PROTOBUF$_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold);\n" + " PROTOBUF_SECTION_VARIABLE(protodesc_cold);\n" " static const ::$proto_ns$::internal::ParseTable schema[$1$]\n" - " $GOOGLE_PROTOBUF$_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold);\n" + " PROTOBUF_SECTION_VARIABLE(protodesc_cold);\n" " static const ::$proto_ns$::internal::FieldMetadata field_metadata[];\n" " static const ::$proto_ns$::internal::SerializationTable " "serialization_table[];\n" diff --git a/src/google/protobuf/compiler/cpp/cpp_file.h b/src/google/protobuf/compiler/cpp/cpp_file.h index 9dfdf50fd0..315cf139be 100644 --- a/src/google/protobuf/compiler/cpp/cpp_file.h +++ b/src/google/protobuf/compiler/cpp/cpp_file.h @@ -76,10 +76,10 @@ class FileGenerator { // info_path, if non-empty, should be the path (relative to printer's // output) to the metadata file describing this proto header. - void GenerateProtoHeader(io::Printer* printer, const string& info_path); + void GenerateProtoHeader(io::Printer* printer, const std::string& info_path); // info_path, if non-empty, should be the path (relative to printer's // output) to the metadata file describing this PB header. - void GeneratePBHeader(io::Printer* printer, const string& info_path); + void GeneratePBHeader(io::Printer* printer, const std::string& info_path); void GenerateSource(io::Printer* printer); int NumMessages() const { return message_generators_.size(); } @@ -91,16 +91,16 @@ class FileGenerator { // Internal type used by GenerateForwardDeclarations (defined in file.cc). class ForwardDeclarations; - void IncludeFile(const string& google3_name, io::Printer* printer) { + void IncludeFile(const std::string& google3_name, io::Printer* printer) { DoIncludeFile(google3_name, false, printer); } - void IncludeFileAndExport(const string& google3_name, io::Printer* printer) { + void IncludeFileAndExport(const std::string& google3_name, io::Printer* printer) { DoIncludeFile(google3_name, true, printer); } - void DoIncludeFile(const string& google3_name, bool do_export, + void DoIncludeFile(const std::string& google3_name, bool do_export, io::Printer* printer); - string CreateHeaderInclude(const string& basename, + std::string CreateHeaderInclude(const std::string& basename, const FileDescriptor* file); void GenerateInternalForwardDeclarations( const std::vector& fields, const Options& options, @@ -117,9 +117,9 @@ class FileGenerator { // Generates top or bottom of a header file. void GenerateTopHeaderGuard(io::Printer* printer, - const string& filename_identifier); + const std::string& filename_identifier); void GenerateBottomHeaderGuard(io::Printer* printer, - const string& filename_identifier); + const std::string& filename_identifier); // Generates #include directives. void GenerateLibraryIncludes(io::Printer* printer); @@ -127,7 +127,7 @@ class FileGenerator { // Generate a pragma to pull in metadata using the given info_path (if // non-empty). info_path should be relative to printer's output. - void GenerateMetadataPragma(io::Printer* printer, const string& info_path); + void GenerateMetadataPragma(io::Printer* printer, const std::string& info_path); // Generates a couple of different pieces before definitions: void GenerateGlobalStateFunctionDeclarations(io::Printer* printer); @@ -182,7 +182,7 @@ class FileGenerator { MessageSCCAnalyzer scc_analyzer_; - std::map variables_; + std::map variables_; // Contains the post-order walk of all the messages (and child messages) in // this file. If you need a pre-order walk just reverse iterate. diff --git a/src/google/protobuf/compiler/cpp/cpp_generator.cc b/src/google/protobuf/compiler/cpp/cpp_generator.cc index 79f773ee49..0e7e4dfde2 100644 --- a/src/google/protobuf/compiler/cpp/cpp_generator.cc +++ b/src/google/protobuf/compiler/cpp/cpp_generator.cc @@ -182,32 +182,41 @@ bool CppGenerator::Generate(const FileDescriptor* file, // Generate cc file(s). if (UsingImplicitWeakFields(file, file_options)) { - { - // This is the global .cc file, containing enum/services/tables/reflection + if (file->name() == "net/proto2/proto/descriptor.proto") { + // If we are building with implicit weak fields then we do not want to + // produce any symbols for descriptor.proto, so we just create an empty + // pb.cc file. std::unique_ptr output( generator_context->Open(basename + ".pb.cc")); - io::Printer printer(output.get(), '$'); - file_generator.GenerateGlobalSource(&printer); - } + } else { + { + // This is the global .cc file, containing + // enum/services/tables/reflection + std::unique_ptr output( + generator_context->Open(basename + ".pb.cc")); + io::Printer printer(output.get(), '$'); + file_generator.GenerateGlobalSource(&printer); + } - int num_cc_files = file_generator.NumMessages(); + int num_cc_files = file_generator.NumMessages(); - // If we're using implicit weak fields then we allow the user to optionally - // specify how many files to generate, not counting the global pb.cc file. - // If we have more files than messages, then some files will be generated as - // empty placeholders. - if (file_options.num_cc_files > 0) { - GOOGLE_CHECK_LE(file_generator.NumMessages(), file_options.num_cc_files) - << "There must be at least as many numbered .cc files as messages."; - num_cc_files = file_options.num_cc_files; - } - for (int i = 0; i < num_cc_files; i++) { - // TODO(gerbens) Agree on naming scheme. - std::unique_ptr output(generator_context->Open( - basename + ".out/" + SimpleItoa(i) + ".cc")); - io::Printer printer(output.get(), '$'); - if (i < file_generator.NumMessages()) { - file_generator.GenerateSourceForMessage(i, &printer); + // If we're using implicit weak fields then we allow the user to + // optionally specify how many files to generate, not counting the global + // pb.cc file. If we have more files than messages, then some files will + // be generated as empty placeholders. + if (file_options.num_cc_files > 0) { + GOOGLE_CHECK_LE(file_generator.NumMessages(), file_options.num_cc_files) + << "There must be at least as many numbered .cc files as messages."; + num_cc_files = file_options.num_cc_files; + } + for (int i = 0; i < num_cc_files; i++) { + std::unique_ptr output( + generator_context->Open(basename + ".out/" + + SimpleItoa(i) + ".cc")); + io::Printer printer(output.get(), '$'); + if (i < file_generator.NumMessages()) { + file_generator.GenerateSourceForMessage(i, &printer); + } } } } else { diff --git a/src/google/protobuf/compiler/cpp/cpp_generator.h b/src/google/protobuf/compiler/cpp/cpp_generator.h index 06d3c36f4f..30363e73a5 100644 --- a/src/google/protobuf/compiler/cpp/cpp_generator.h +++ b/src/google/protobuf/compiler/cpp/cpp_generator.h @@ -40,6 +40,8 @@ #include #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -49,12 +51,12 @@ namespace cpp { // header. If you create your own protocol compiler binary and you want // it to support C++ output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT CppGenerator : public CodeGenerator { +class PROTOC_EXPORT CppGenerator : public CodeGenerator { public: CppGenerator(); ~CppGenerator(); - enum class LIBPROTOC_EXPORT Runtime { + enum class Runtime { kGoogle3, // Use the internal google3 runtime. kOpensource, // Use the open-source runtime. @@ -70,9 +72,9 @@ class LIBPROTOC_EXPORT CppGenerator : public CodeGenerator { // implements CodeGenerator ---------------------------------------- bool Generate(const FileDescriptor* file, - const string& parameter, + const std::string& parameter, GeneratorContext* generator_context, - string* error) const; + std::string* error) const; private: Runtime runtime_ = Runtime::kOpensource; @@ -84,4 +86,6 @@ class LIBPROTOC_EXPORT CppGenerator : public CodeGenerator { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_GENERATOR_H__ diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.cc b/src/google/protobuf/compiler/cpp/cpp_helpers.cc index bc0a9264ad..472c55f452 100644 --- a/src/google/protobuf/compiler/cpp/cpp_helpers.cc +++ b/src/google/protobuf/compiler/cpp/cpp_helpers.cc @@ -53,6 +53,8 @@ #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -487,10 +489,9 @@ string DefaultValue(const Options& options, const FieldDescriptor* field) { case FieldDescriptor::CPPTYPE_UINT32: return SimpleItoa(field->default_value_uint32()) + "u"; case FieldDescriptor::CPPTYPE_INT64: - return Int64ToString(MacroPrefix(options), field->default_value_int64()); + return Int64ToString("PROTOBUF", field->default_value_int64()); case FieldDescriptor::CPPTYPE_UINT64: - return UInt64ToString(MacroPrefix(options), - field->default_value_uint64()); + return UInt64ToString("PROTOBUF", field->default_value_uint64()); case FieldDescriptor::CPPTYPE_DOUBLE: { double value = field->default_value_double(); if (value == std::numeric_limits::infinity()) { @@ -1058,7 +1059,7 @@ void ListAllTypesForServices(const FileDescriptor* fd, bool GetBootstrapBasename(const Options& options, const string& basename, string* bootstrap_basename) { - if (options.opensource_runtime) { + if (options.opensource_runtime || options.lite_implicit_weak_fields) { return false; } @@ -1169,6 +1170,193 @@ bool ShouldRepeat(const FieldDescriptor* descriptor, wiretype != internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED); } +void GenerateLengthDelim( + const FieldDescriptor* field, const Options& options, + MessageSCCAnalyzer* scc_analyzer, + const Formatter& format) { + format( + "ptr = Varint::Parse32Inline(ptr, &size);\n" + "$GOOGLE_PROTOBUF$_PARSER_ASSERT(ptr);\n"); + if (!IsProto1(field->file(), options) && field->is_packable()) { + if (!HasPreservingUnknownEnumSemantics(field->file()) && + field->type() == FieldDescriptor::TYPE_ENUM) { + format( + "ctx->extra_parse_data().SetEnumValidator($1$_IsValid, " + "msg->mutable_unknown_fields(), $2$);\n" + "parser_till_end = " + "::$proto_ns$::internal::PackedValidEnumParser$3$;\n" + "object = msg->mutable_$4$();\n", + QualifiedClassName(field->enum_type()), field->number(), + UseUnknownFieldSet(field->file(), options) ? "" : "Lite", + FieldName(field)); + } else { + format( + "parser_till_end = ::$proto_ns$::internal::Packed$1$Parser;\n" + "object = msg->mutable_$2$();\n", + DeclaredTypeMethodName(field->type()), FieldName(field)); + } + format( + "if (size > end - ptr) goto len_delim_till_end;\n" + "auto newend = ptr + size;\n" + "if (size) ptr = parser_till_end(ptr, newend, object, ctx);\n" + "$GOOGLE_PROTOBUF$_PARSER_ASSERT(ptr == newend);\n"); + } else { + auto field_type = field->type(); + if (IsProto1(field->file(), options)) { + if (field->is_packable()) { + // Sigh ... packed fields endup as a string in proto1 + field_type = FieldDescriptor::TYPE_BYTES; + } + if (field_type == FieldDescriptor::TYPE_STRING) { + // In proto1 strings are treated as bytes + field_type = FieldDescriptor::TYPE_BYTES; + } + } + string utf8 = ""; + switch (field_type) { + case FieldDescriptor::TYPE_STRING: + utf8 = GetUtf8Suffix(field, options); + if (!utf8.empty()) { + string name = "nullptr"; + if (HasDescriptorMethods(field->file(), options)) { + name = "\"" + field->full_name() + "\""; + } + format("ctx->extra_parse_data().SetFieldName($1$);\n", name); + } + PROTOBUF_FALLTHROUGH_INTENDED; + case FieldDescriptor::TYPE_BYTES: { + if (field->options().ctype() == FieldOptions::STRING || + (IsProto1(field->file(), options) && + field->options().ctype() == FieldOptions::STRING_PIECE)) { + format( + "parser_till_end = ::$proto_ns$::internal::StringParser$1$;\n" + "$string$* str = msg->$2$_$3$();\n" + "str->clear();\n", + utf8, + field->is_repeated() && !field->is_map() && + !field->is_packable() + ? "add" + : "mutable", + FieldName(field)); + if (utf8.empty()) { + // special case if there is no utf8 verification. + format( + "object = str;\n" + "if (size > end - ptr) goto len_delim_till_end;\n" + "str->append(ptr, size);\n" + "ptr += size;\n"); + return; + } + } else if (field->options().ctype() == FieldOptions::CORD) { + string cord_parser = "CordParser" + utf8; + format( + "parser_till_end = ::$proto_ns$::internal::$1$;\n" + "auto* str = msg->$2$_$3$();\n" + "str->Clear();\n", + cord_parser, + field->is_repeated() && !field->is_map() ? "add" : "mutable", + FieldName(field)); + } else if (field->options().ctype() == FieldOptions::STRING_PIECE) { + format( + "parser_till_end = " + "::$proto_ns$::internal::StringPieceParser$1$;\n" + "::$proto_ns$::internal::StringPieceField* str = " + "msg->$2$_$3$();\n" + "str->Clear();\n", + utf8, + field->is_repeated() && !field->is_map() ? "add" : "mutable", + FieldName(field)); + } + format( + "object = str;\n" + "if (size > end - ptr) goto len_delim_till_end;\n" + "auto newend = ptr + size;\n" + "if (size) ptr = parser_till_end(ptr, newend, object, ctx);\n"); + if (!utf8.empty()) { + // If utf8 verification is on this can fail. + format("$GOOGLE_PROTOBUF$_PARSER_ASSERT(ptr == newend);\n"); + } + break; + } + case FieldDescriptor::TYPE_MESSAGE: { + GOOGLE_CHECK(field->message_type()); + if (!IsProto1(field->file(), options) && field->is_map()) { + const FieldDescriptor* val = + field->message_type()->FindFieldByName("value"); + GOOGLE_CHECK(val); + if (HasFieldPresence(field->file()) && + val->type() == FieldDescriptor::TYPE_ENUM) { + format( + "ctx->extra_parse_data().field_number = $1$;\n" + "ctx->extra_parse_data().unknown_fields = " + "&msg->_internal_metadata_;\n", + field->number()); + } + format( + "parser_till_end = ::$proto_ns$::internal::SlowMapEntryParser;\n" + "auto parse_map = $1$::_ParseMap;\n" + "ctx->extra_parse_data().payload.clear();\n" + "ctx->extra_parse_data().parse_map = parse_map;\n" + "object = &msg->$2$_;\n" + "if (size > end - ptr) goto len_delim_till_end;\n" + "auto newend = ptr + size;\n" + "GOOGLE_PROTOBUF_PARSER_ASSERT(parse_map(ptr, newend, " + "object, ctx));\n" + "ptr = newend;\n", + QualifiedClassName(field->message_type()), FieldName(field)); + break; + } + if (IsImplicitWeakField(field, options, scc_analyzer)) { + if (!field->is_repeated()) { + format("object = HasBitSetters::mutable_$1$(msg);\n", + FieldName(field)); + } else { + format( + "object = " + "CastToBase(&msg->$1$_)->AddWeak(reinterpret_cast(&$2$::_$3$_default_instance_));\n", + FieldName(field), Namespace(field->message_type()), + ClassName(field->message_type())); + } + format( + "parser_till_end = static_cast<::$proto_ns$::MessageLite*>(" + "object)->_ParseFunc();\n"); + } else if (IsWeak(field, options)) { + if (IsProto1(field->file(), options)) { + format("object = msg->internal_mutable_$1$();\n", + FieldName(field)); + } else { + format( + "object = msg->_weak_field_map_.MutableMessage($1$, " + "_$classname$_default_instance_.$2$_);\n", + field->number(), FieldName(field)); + } + format( + "parser_till_end = static_cast<::$proto_ns$::MessageLite*>(" + "object)->_ParseFunc();\n"); + } else { + format( + "parser_till_end = $1$::_InternalParse;\n" + "object = msg->$2$_$3$();\n", + QualifiedClassName(field->message_type()), + field->is_repeated() ? "add" : "mutable", FieldName(field)); + } + format( + "if (size > end - ptr) goto len_delim_till_end;\n" + "auto newend = ptr + size;\n" + "bool ok = ctx->ParseExactRange({parser_till_end, object},\n" + " ptr, newend);\n" + "$GOOGLE_PROTOBUF$_PARSER_ASSERT(ok);\n" + "ptr = newend;\n"); + break; + } + default: + GOOGLE_LOG(FATAL) << "Illegal combination for length delimited wiretype " + << " filed type is " << field->type(); + } + } +} + void GenerateCaseBody(internal::WireFormatLite::WireType wiretype, const FieldDescriptor* field, const Options& options, MessageSCCAnalyzer* scc_analyzer, @@ -1185,10 +1373,11 @@ void GenerateCaseBody(internal::WireFormatLite::WireType wiretype, format( "$uint64$ val;\n" "ptr = Varint::Parse64(ptr, &val);\n" - "if (!ptr) goto error;\n"); + "$GOOGLE_PROTOBUF$_PARSER_ASSERT(ptr);\n"); string type = PrimitiveTypeName(options, field->cpp_type()); - if (field->type() == FieldDescriptor::TYPE_SINT32 || - field->type() == FieldDescriptor::TYPE_SINT64) { + if ((field->type() == FieldDescriptor::TYPE_SINT32 || + field->type() == FieldDescriptor::TYPE_SINT64) && + !IsProto1(field->file(), options)) { int size = EstimateAlignmentSize(field) * 8; format( "$1$ value = " @@ -1232,149 +1421,17 @@ void GenerateCaseBody(internal::WireFormatLite::WireType wiretype, break; } case WireFormatLite::WIRETYPE_LENGTH_DELIMITED: { - format( - "ptr = Varint::Parse32Inline(ptr, &size);\n" - "if (!ptr) goto error;\n"); - if (!IsProto1(field->file(), options) && field->is_packable()) { - if (!HasPreservingUnknownEnumSemantics(field->file()) && - field->type() == FieldDescriptor::TYPE_ENUM) { - format( - "ctx->extra_parse_data().SetEnumValidator($1$_IsValid, " - "msg->mutable_unknown_fields(), $2$);\n" - "parser_till_end = " - "::$proto_ns$::internal::PackedValidEnumParser$3$;\n" - "object = msg->mutable_$4$();\n", - QualifiedClassName(field->enum_type()), field->number(), - UseUnknownFieldSet(field->file(), options) ? "" : "Lite", - FieldName(field)); - } else { - format( - "parser_till_end = ::$proto_ns$::internal::Packed$1$Parser;\n" - "object = msg->mutable_$2$();\n", - DeclaredTypeMethodName(field->type()), FieldName(field)); - } - } else { - auto field_type = field->type(); - if (IsProto1(field->file(), options)) { - if (field->is_packable()) { - // Sigh ... packed fields endup as a string in proto1 - field_type = FieldDescriptor::TYPE_BYTES; - } - if (field_type == FieldDescriptor::TYPE_STRING) { - // In proto1 strings are treated as bytes - field_type = FieldDescriptor::TYPE_BYTES; - } - } - string utf8 = ""; - switch (field_type) { - case FieldDescriptor::TYPE_STRING: - utf8 = GetUtf8Suffix(field, options); - if (!utf8.empty()) { - string name = "nullptr"; - if (HasDescriptorMethods(field->file(), options)) { - name = field->full_name(); - } - format("ctx->extra_parse_data().SetFieldName(\"$1$\");\n", name); - } - [[clang::fallthrough]]; - case FieldDescriptor::TYPE_BYTES: { - if (field->options().ctype() == FieldOptions::STRING || - (IsProto1(field->file(), options) && - field->options().ctype() == FieldOptions::STRING_PIECE)) { - format( - "parser_till_end = ::$proto_ns$::internal::StringParser$1$;\n" - "$string$* str = msg->$2$_$3$();\n" - "str->clear();\n", - utf8, - field->is_repeated() && !field->is_map() && - !field->is_packable() - ? "add" - : "mutable", - FieldName(field)); - } else if (field->options().ctype() == FieldOptions::CORD) { - string cord_parser = "CordParser" + utf8; - format( - "parser_till_end = ::$proto_ns$::internal::$1$;\n" - "auto* str = msg->$2$_$3$();\n" - "str->Clear();\n", - cord_parser, - field->is_repeated() && !field->is_map() ? "add" : "mutable", - FieldName(field)); - } else if (field->options().ctype() == FieldOptions::STRING_PIECE) { - format( - "parser_till_end = " - "::$proto_ns$::internal::StringPieceParser$1$;\n" - "::$proto_ns$::internal::StringPieceField* str = " - "msg->$2$_$3$();\n" - "str->Clear();\n", - utf8, - field->is_repeated() && !field->is_map() ? "add" : "mutable", - FieldName(field)); - } - format("object = str;\n"); - break; - } - case FieldDescriptor::TYPE_MESSAGE: { - GOOGLE_CHECK(field->message_type()); - if (IsImplicitWeakField(field, options, scc_analyzer)) { - if (!field->is_repeated()) { - format("object = HasBitSetters::mutable_$1$(msg);\n", - FieldName(field)); - } else { - format( - "object = " - "CastToBase(&msg->$1$_)->AddWeak(reinterpret_cast(&$2$::_$3$_default_instance_));\n", - FieldName(field), Namespace(field->message_type()), - ClassName(field->message_type())); - } - format( - "parser_till_end = static_cast<::$proto_ns$::MessageLite*>(" - "object)->_ParseFunc();\n"); - break; - } else if (IsWeak(field, options)) { - if (IsProto1(field->file(), options)) { - format("object = msg->internal_mutable_$1$();\n", - FieldName(field)); - } else { - format( - "object = msg->_weak_field_map_.MutableMessage($1$, " - "_$classname$_default_instance_.$2$_);\n", - field->number(), FieldName(field)); - } - format( - "parser_till_end = static_cast<::$proto_ns$::MessageLite*>(" - "object)->_ParseFunc();\n"); - break; - } - format( - "parser_till_end = $1$::_InternalParse;\n" - "object = msg->$2$_$3$();\n", - QualifiedClassName(field->message_type()), - field->is_repeated() && !field->is_map() ? "add" : "mutable", - FieldName(field)); - break; - } - default: - GOOGLE_LOG(FATAL) << "Illegal combination for length delimited wiretype " - << " filed type is " << field->type(); - } - } - format( - "if (size > end - ptr) goto len_delim_till_end;\n" - "auto newend = ptr + size;\n" - "if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) " - "goto error;\n" - "ptr = newend;\n"); + GenerateLengthDelim(field, options, scc_analyzer, format); break; } case WireFormatLite::WIRETYPE_START_GROUP: { format( "parser_till_end = $1$::_InternalParse;\n" "object = msg->$2$_$3$();\n" - "if (!ctx->PrepareGroup(tag, &depth)) goto error;\n" + "bool ok = ctx->PrepareGroup(tag, &depth);\n" + "$GOOGLE_PROTOBUF$_PARSER_ASSERT(ok);\n" "ptr = parser_till_end(ptr, end, object, ctx);\n" - "if (!ptr) goto error;\n" + "$GOOGLE_PROTOBUF$_PARSER_ASSERT(ptr);\n" "if (ctx->GroupContinues(depth)) goto group_continues;\n", QualifiedClassName(field->message_type()), field->is_repeated() ? "add" : "mutable", FieldName(field)); @@ -1413,8 +1470,8 @@ void GenerateCaseBody(internal::WireFormatLite::WireType wiretype, uint64 mask = (1ull << (cnt * 8)) - 1; format.Outdent(); format( - "} while((*reinterpret_cast(ptr) & $1$) == $2$ && " - "(ptr += $3$));\n", + "} while ((::$proto_ns$::io::UnalignedLoad<$uint64$>(ptr) & $1$) == " + "$2$ && (ptr += $3$));\n", mask, y, cnt); } format("break;\n"); @@ -1491,9 +1548,8 @@ void GenerateParserLoop(const Descriptor* descriptor, const Options& options, " while (ptr < end) {\n" " $uint32$ tag;\n" " ptr = Varint::Parse32Inline(ptr, &tag);\n" - " if (!ptr) goto error;\n" - " switch (tag >> 3) {\n" - " case 0: goto error;\n"); + " $GOOGLE_PROTOBUF$_PARSER_ASSERT(ptr);\n" + " switch (tag >> 3) {\n"); format.Indent(); format.Indent(); @@ -1526,8 +1582,9 @@ void GenerateParserLoop(const Descriptor* descriptor, const Options& options, format( "default: {\n" "handle_unusual: (void)&&handle_unusual;\n" - " if ((tag & 7) == 4) {\n" - " if (!ctx->ValidEndGroup(tag)) goto error;\n" + " if ((tag & 7) == 4 || tag == 0) {\n" + " bool ok = ctx->ValidEndGroup(tag);\n" + " $GOOGLE_PROTOBUF$_PARSER_ASSERT(ok);\n" " return ptr;\n" " }\n"); if (IsMapEntryMessage(descriptor)) { @@ -1579,8 +1636,6 @@ void GenerateParserLoop(const Descriptor* descriptor, const Options& options, " } // switch\n" " } // while\n" " return ptr;\n" - "error:\n" - " return nullptr;\n" "len_delim_till_end: (void)&&len_delim_till_end;\n" " return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},\n" " {parser_till_end, object}, size);\n" diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.h b/src/google/protobuf/compiler/cpp/cpp_helpers.h index c01329fa2a..b8431aedb4 100644 --- a/src/google/protobuf/compiler/cpp/cpp_helpers.h +++ b/src/google/protobuf/compiler/cpp/cpp_helpers.h @@ -55,19 +55,16 @@ namespace protobuf { namespace compiler { namespace cpp { -inline string ProtobufNamespace(const Options& options) { +inline std::string ProtobufNamespace(const Options& options) { return options.opensource_runtime ? "google::protobuf" : "proto2"; } -inline string MacroPrefix(const Options& options) { +inline std::string MacroPrefix(const Options& options) { return options.opensource_runtime ? "GOOGLE_PROTOBUF" : "GOOGLE_PROTOBUF"; } -inline string DeprecatedAttribute(const Options& options, bool deprecated) { - if (!deprecated) { - return ""; - } - return MacroPrefix(options) + "_DEPRECATED "; +inline std::string DeprecatedAttribute(const Options& options, bool deprecated) { + return deprecated ? "PROTOBUF_DEPRECATED " : ""; } // Commonly-used separator comments. Thick is a line of '=', thin is a line @@ -79,35 +76,35 @@ inline bool IsProto1(const FileDescriptor* file, const Options& options) { return false; } -void SetCommonVars(const Options& options, std::map* variables); +void SetCommonVars(const Options& options, std::map* variables); -bool GetBootstrapBasename(const Options& options, const string& basename, - string* bootstrap_basename); +bool GetBootstrapBasename(const Options& options, const std::string& basename, + std::string* bootstrap_basename); bool MaybeBootstrap(const Options& options, GeneratorContext* generator_context, - bool bootstrap_flag, string* basename); + bool bootstrap_flag, std::string* basename); bool IsBootstrapProto(const Options& options, const FileDescriptor* file); // Name space of the proto file. This namespace is such that the string // "::some_name" is the correct fully qualified namespace. // This means if the package is empty the namespace is "", and otherwise // the namespace is "::foo::bar::...::baz" without trailing semi-colons. -string Namespace(const string& package); -inline string Namespace(const FileDescriptor* d) { +std::string Namespace(const std::string& package); +inline std::string Namespace(const FileDescriptor* d) { return Namespace(d->package()); } -string Namespace(const Descriptor* d); -string Namespace(const FieldDescriptor* d); -string Namespace(const EnumDescriptor* d); +std::string Namespace(const Descriptor* d); +std::string Namespace(const FieldDescriptor* d); +std::string Namespace(const EnumDescriptor* d); // Returns true if it's safe to reset "field" to zero. bool CanInitializeByZeroing(const FieldDescriptor* field); -string ClassName(const Descriptor* descriptor); -string ClassName(const EnumDescriptor* enum_descriptor); +std::string ClassName(const Descriptor* descriptor); +std::string ClassName(const EnumDescriptor* enum_descriptor); -string QualifiedClassName(const Descriptor* d); -string QualifiedClassName(const EnumDescriptor* d); +std::string QualifiedClassName(const Descriptor* d); +std::string QualifiedClassName(const EnumDescriptor* d); // DEPRECATED just use ClassName or QualifiedClassName, a boolean is very // unreadable at the callsite. @@ -119,33 +116,33 @@ string QualifiedClassName(const EnumDescriptor* d); // ::foo::bar::Baz_Qux // While the non-qualified version would be: // Baz_Qux -inline string ClassName(const Descriptor* descriptor, bool qualified) { +inline std::string ClassName(const Descriptor* descriptor, bool qualified) { return qualified ? QualifiedClassName(descriptor) : ClassName(descriptor); } -inline string ClassName(const EnumDescriptor* descriptor, bool qualified) { +inline std::string ClassName(const EnumDescriptor* descriptor, bool qualified) { return qualified ? QualifiedClassName(descriptor) : ClassName(descriptor); } // Fully qualified name of the default_instance of this message. -string DefaultInstanceName(const Descriptor* descriptor); +std::string DefaultInstanceName(const Descriptor* descriptor); // Returns the name of a no-op function that we can call to introduce a linker // dependency on the given message type. This is used to implement implicit weak // fields. -string ReferenceFunctionName(const Descriptor* descriptor); +std::string ReferenceFunctionName(const Descriptor* descriptor); // Name of the base class: google::protobuf::Message or google::protobuf::MessageLite. -string SuperClassName(const Descriptor* descriptor, const Options& options); +std::string SuperClassName(const Descriptor* descriptor, const Options& options); // Get the (unqualified) name that should be used for this field in C++ code. // The name is coerced to lower-case to emulate proto1 behavior. People // should be using lowercase-with-underscores style for proto field names // anyway, so normally this just returns field->name(). -string FieldName(const FieldDescriptor* field); +std::string FieldName(const FieldDescriptor* field); // Get the sanitized name that should be used for the given enum in C++ code. -string EnumValueName(const EnumValueDescriptor* enum_value); +std::string EnumValueName(const EnumValueDescriptor* enum_value); // Returns an estimate of the compiler's alignment for the field. This // can't guarantee to be correct because the generated code could be compiled on @@ -155,7 +152,7 @@ int EstimateAlignmentSize(const FieldDescriptor* field); // Get the unqualified name that should be used for a field's field // number constant. -string FieldConstantName(const FieldDescriptor *field); +std::string FieldConstantName(const FieldDescriptor *field); // Returns the scope where the field was defined (for extensions, this is // different from the message type to which the field applies). @@ -166,51 +163,51 @@ inline const Descriptor* FieldScope(const FieldDescriptor* field) { // Returns the fully-qualified type name field->message_type(). Usually this // is just ClassName(field->message_type(), true); -string FieldMessageTypeName(const FieldDescriptor* field); +std::string FieldMessageTypeName(const FieldDescriptor* field); // Strips ".proto" or ".protodevel" from the end of a filename. -LIBPROTOC_EXPORT string StripProto(const string& filename); +PROTOC_EXPORT std::string StripProto(const std::string& filename); // Get the C++ type name for a primitive type (e.g. "double", "::google::protobuf::int32", etc.). const char* PrimitiveTypeName(FieldDescriptor::CppType type); -string PrimitiveTypeName(const Options& options, FieldDescriptor::CppType type); +std::string PrimitiveTypeName(const Options& options, FieldDescriptor::CppType type); // Get the declared type name in CamelCase format, as is used e.g. for the // methods of WireFormat. For example, TYPE_INT32 becomes "Int32". const char* DeclaredTypeMethodName(FieldDescriptor::Type type); // Return the code that evaluates to the number when compiled. -string Int32ToString(int number); +std::string Int32ToString(int number); // Return the code that evaluates to the number when compiled. -string Int64ToString(const Options& options, int64 number); +std::string Int64ToString(const Options& options, int64 number); // Get code that evaluates to the field's default value. -string DefaultValue(const Options& options, const FieldDescriptor* field); +std::string DefaultValue(const Options& options, const FieldDescriptor* field); // Compatibility function for callers outside proto2. -string DefaultValue(const FieldDescriptor* field); +std::string DefaultValue(const FieldDescriptor* field); // Convert a file name into a valid identifier. -string FilenameIdentifier(const string& filename); +std::string FilenameIdentifier(const std::string& filename); // For each .proto file generates a unique name. To prevent collisions of // symbols in the global namespace -string UniqueName(const string& name, const string& filename, +std::string UniqueName(const std::string& name, const std::string& filename, const Options& options); -inline string UniqueName(const string& name, const FileDescriptor* d, +inline std::string UniqueName(const std::string& name, const FileDescriptor* d, const Options& options) { return UniqueName(name, d->name(), options); } -inline string UniqueName(const string& name, const Descriptor* d, +inline std::string UniqueName(const std::string& name, const Descriptor* d, const Options& options) { return UniqueName(name, d->file(), options); } -inline string UniqueName(const string& name, const EnumDescriptor* d, +inline std::string UniqueName(const std::string& name, const EnumDescriptor* d, const Options& options) { return UniqueName(name, d->file(), options); } -inline string UniqueName(const string& name, const ServiceDescriptor* d, +inline std::string UniqueName(const std::string& name, const ServiceDescriptor* d, const Options& options) { return UniqueName(name, d->file(), options); } @@ -222,32 +219,32 @@ inline Options InternalRuntimeOptions() { options.opensource_runtime = false; return options; } -inline string UniqueName(const string& name, const string& filename) { +inline std::string UniqueName(const std::string& name, const std::string& filename) { return UniqueName(name, filename, InternalRuntimeOptions()); } -inline string UniqueName(const string& name, const FileDescriptor* d) { +inline std::string UniqueName(const std::string& name, const FileDescriptor* d) { return UniqueName(name, d->name(), InternalRuntimeOptions()); } -inline string UniqueName(const string& name, const Descriptor* d) { +inline std::string UniqueName(const std::string& name, const Descriptor* d) { return UniqueName(name, d->file(), InternalRuntimeOptions()); } -inline string UniqueName(const string& name, const EnumDescriptor* d) { +inline std::string UniqueName(const std::string& name, const EnumDescriptor* d) { return UniqueName(name, d->file(), InternalRuntimeOptions()); } -inline string UniqueName(const string& name, const ServiceDescriptor* d) { +inline std::string UniqueName(const std::string& name, const ServiceDescriptor* d) { return UniqueName(name, d->file(), InternalRuntimeOptions()); } // Return the qualified C++ name for a file level symbol. -string QualifiedFileLevelSymbol(const string& package, const string& name); +std::string QualifiedFileLevelSymbol(const std::string& package, const std::string& name); // Escape C++ trigraphs by escaping question marks to \? -string EscapeTrigraphs(const string& to_escape); +std::string EscapeTrigraphs(const std::string& to_escape); // Escaped function name to eliminate naming conflict. -string SafeFunctionName(const Descriptor* descriptor, +std::string SafeFunctionName(const Descriptor* descriptor, const FieldDescriptor* field, - const string& prefix); + const std::string& prefix); // Returns true if generated messages have public unknown fields accessors inline bool PublicUnknownFieldsAccessors(const Descriptor* message) { @@ -355,6 +352,8 @@ inline bool HasFastArraySerialization(const FileDescriptor* file, inline bool IsProto2MessageSet(const Descriptor* descriptor, const Options& options) { return !options.opensource_runtime && + !options.enforce_lite && + !options.lite_implicit_weak_fields && descriptor->options().message_set_wire_format() && descriptor->full_name() == "google.protobuf.bridge.MessageSet"; } @@ -362,6 +361,8 @@ inline bool IsProto2MessageSet(const Descriptor* descriptor, inline bool IsProto2MessageSetFile(const FileDescriptor* file, const Options& options) { return !options.opensource_runtime && + !options.enforce_lite && + !options.lite_implicit_weak_fields && file->name() == "net/proto2/bridge/proto/message_set.proto"; } @@ -372,7 +373,7 @@ inline bool IsMapEntryMessage(const Descriptor* descriptor) { // Returns true if the field's CPPTYPE is string or message. bool IsStringOrMessage(const FieldDescriptor* field); -string UnderscoresToCamelCase(const string& input, bool cap_next_letter); +std::string UnderscoresToCamelCase(const std::string& input, bool cap_next_letter); inline bool HasFieldPresence(const FileDescriptor* file) { return file->syntax() != FileDescriptor::SYNTAX_PROTO3; @@ -401,11 +402,11 @@ inline bool IsCrossFileMessage(const FieldDescriptor* field) { field->message_type()->file() != field->file(); } -inline string MessageCreateFunction(const Descriptor* d) { +inline std::string MessageCreateFunction(const Descriptor* d) { return SupportsArenas(d) ? "CreateMessage" : "Create"; } -inline string MakeDefaultName(const FieldDescriptor* field) { +inline std::string MakeDefaultName(const FieldDescriptor* field) { return "_i_give_permission_to_break_this_code_default_" + FieldName(field) + "_"; } @@ -455,7 +456,7 @@ struct MessageAnalysis { // quadratic performance, if we do this per message we would get O(V*(V+E)). // Logically this is just only used in message.cc, but in the header for // FileGenerator to help share it. -class LIBPROTOC_EXPORT MessageSCCAnalyzer { +class PROTOC_EXPORT MessageSCCAnalyzer { public: explicit MessageSCCAnalyzer(const Options& options) : options_(options) {} @@ -528,18 +529,18 @@ bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options, // "__declspec(export) void fun();" // // which is convenient to prevent double, leading or trailing spaces. -class LIBPROTOC_EXPORT Formatter { +class PROTOC_EXPORT Formatter { public: explicit Formatter(io::Printer* printer) : printer_(printer) {} - Formatter(io::Printer* printer, const std::map& vars) + Formatter(io::Printer* printer, const std::map& vars) : printer_(printer), vars_(vars) {} template - void Set(const string& key, const T& value) { + void Set(const std::string& key, const T& value) { vars_[key] = ToString(value); } - void AddMap(const std::map& vars) { + void AddMap(const std::map& vars) { for (const auto& keyval : vars) vars_[keyval.first] = keyval.second; } @@ -552,7 +553,7 @@ class LIBPROTOC_EXPORT Formatter { void Outdent() const { printer_->Outdent(); } io::Printer* printer() const { return printer_; } - class LIBPROTOC_EXPORT SaveState { + class PROTOC_EXPORT SaveState { public: explicit SaveState(Formatter* format) : format_(format), vars_(format->vars_) {} @@ -560,28 +561,28 @@ class LIBPROTOC_EXPORT Formatter { private: Formatter* format_; - std::map vars_; + std::map vars_; }; private: io::Printer* printer_; - std::map vars_; + std::map vars_; // Convenience overloads to accept different types as arguments. - static string ToString(const string& s) { return s; } + static std::string ToString(const std::string& s) { return s; } template ::value>::type> - static string ToString(I x) { + static std::string ToString(I x) { return SimpleItoa(x); } - static string ToString(strings::Hex x) { return StrCat(x); } - static string ToString(const FieldDescriptor* d) { return Payload(d); } - static string ToString(const Descriptor* d) { return Payload(d); } - static string ToString(const EnumDescriptor* d) { return Payload(d); } - static string ToString(const EnumValueDescriptor* d) { return Payload(d); } + static std::string ToString(strings::Hex x) { return StrCat(x); } + static std::string ToString(const FieldDescriptor* d) { return Payload(d); } + static std::string ToString(const Descriptor* d) { return Payload(d); } + static std::string ToString(const EnumDescriptor* d) { return Payload(d); } + static std::string ToString(const EnumValueDescriptor* d) { return Payload(d); } template - static string Payload(const Descriptor* descriptor) { + static std::string Payload(const Descriptor* descriptor) { std::vector path; descriptor->GetLocationPath(&path); GeneratedCodeInfo::Annotation annotation; @@ -593,18 +594,18 @@ class LIBPROTOC_EXPORT Formatter { } }; -class LIBPROTOC_EXPORT NamespaceOpener { +class PROTOC_EXPORT NamespaceOpener { public: explicit NamespaceOpener(const Formatter& format) : printer_(format.printer()) {} - NamespaceOpener(const string& name, const Formatter& format) + NamespaceOpener(const std::string& name, const Formatter& format) : NamespaceOpener(format) { ChangeTo(name); } ~NamespaceOpener() { ChangeTo(""); } - void ChangeTo(const string& name) { - std::vector new_stack_ = + void ChangeTo(const std::string& name) { + std::vector new_stack_ = Split(name, "::", true); int len = std::min(name_stack_.size(), new_stack_.size()); int common_idx = 0; @@ -623,10 +624,10 @@ class LIBPROTOC_EXPORT NamespaceOpener { private: io::Printer* printer_; - std::vector name_stack_; + std::vector name_stack_; }; -string GetUtf8Suffix(const FieldDescriptor* field, const Options& options); +std::string GetUtf8Suffix(const FieldDescriptor* field, const Options& options); void GenerateUtf8CheckCodeForString(const FieldDescriptor* field, const Options& options, bool for_parse, const char* parameters, diff --git a/src/google/protobuf/compiler/cpp/cpp_map_field.cc b/src/google/protobuf/compiler/cpp/cpp_map_field.cc index 4ab407d2a2..3114bbf7df 100644 --- a/src/google/protobuf/compiler/cpp/cpp_map_field.cc +++ b/src/google/protobuf/compiler/cpp/cpp_map_field.cc @@ -177,54 +177,49 @@ GenerateMergeFromCodedStream(io::Printer* printer) const { descriptor_->message_type()->FindFieldByName("key"); const FieldDescriptor* value_field = descriptor_->message_type()->FindFieldByName("value"); - bool using_entry = false; string key; string value; + format( + "$map_classname$::Parser< ::$proto_ns$::internal::MapField$lite$<\n" + " $map_classname$,\n" + " $key_cpp$, $val_cpp$,\n" + " ::$proto_ns$::internal::WireFormatLite::$key_wire_type$,\n" + " ::$proto_ns$::internal::WireFormatLite::$val_wire_type$,\n" + " $default_enum_value$ >,\n" + " ::$proto_ns$::Map< $key_cpp$, $val_cpp$ > >" + " parser(&$name$_);\n"); if (IsProto3Field(descriptor_) || value_field->type() != FieldDescriptor::TYPE_ENUM) { format( - "$map_classname$::Parser< ::$proto_ns$::internal::MapField$lite$<\n" - " $map_classname$,\n" - " $key_cpp$, $val_cpp$,\n" - " ::$proto_ns$::internal::WireFormatLite::$key_wire_type$,\n" - " ::$proto_ns$::internal::WireFormatLite::$val_wire_type$,\n" - " $default_enum_value$ >,\n" - " ::$proto_ns$::Map< $key_cpp$, $val_cpp$ > >" - " parser(&$name$_);\n" "DO_(::$proto_ns$::internal::WireFormatLite::ReadMessageNoVirtual(\n" " input, &parser));\n"); key = "parser.key()"; value = "parser.value()"; } else { - using_entry = true; key = "entry->key()"; value = "entry->value()"; - format("::std::unique_ptr<$map_classname$> entry($name$_.NewEntry());\n"); + format("auto entry = parser.NewEntry();\n"); format( - "{\n" - " ::std::string data;\n" - " DO_(::$proto_ns$::internal::WireFormatLite::ReadString(input, " + "::std::string data;\n" + "DO_(::$proto_ns$::internal::WireFormatLite::ReadString(input, " "&data));\n" - " DO_(entry->ParseFromString(data));\n" - " if ($val_cpp$_IsValid(*entry->mutable_value())) {\n" - " (*mutable_$name$())[entry->key()] =\n" - " static_cast< $val_cpp$ >(*entry->mutable_value());\n" - " } else {\n"); + "DO_(entry->ParseFromString(data));\n" + "if ($val_cpp$_IsValid(*entry->mutable_value())) {\n" + " (*mutable_$name$())[entry->key()] =\n" + " static_cast< $val_cpp$ >(*entry->mutable_value());\n" + "} else {\n"); if (HasDescriptorMethods(descriptor_->file(), options_)) { format( - " mutable_unknown_fields()" + " mutable_unknown_fields()" "->AddLengthDelimited($number$, data);\n"); } else { format( - " unknown_fields_stream.WriteVarint32($tag$u);\n" - " unknown_fields_stream.WriteVarint32(\n" - " static_cast< ::google::protobuf::uint32>(data.size()));\n" - " unknown_fields_stream.WriteString(data);\n"); + " unknown_fields_stream.WriteVarint32($tag$u);\n" + " unknown_fields_stream.WriteVarint32(\n" + " static_cast< ::google::protobuf::uint32>(data.size()));\n" + " unknown_fields_stream.WriteString(data);\n"); } - - format( - " }\n" - "}\n"); + format("}\n"); } if (key_field->type() == FieldDescriptor::TYPE_STRING) { @@ -242,11 +237,6 @@ GenerateMergeFromCodedStream(io::Printer* printer) const { .data(), format); } - - // If entry is allocated by arena, its desctructor should be avoided. - if (using_entry && SupportsArenas(descriptor_)) { - format("if (entry->GetArena() != NULL) entry.release();\n"); - } } static void GenerateSerializationLoop(const Formatter& format, diff --git a/src/google/protobuf/compiler/cpp/cpp_message.cc b/src/google/protobuf/compiler/cpp/cpp_message.cc index e219d78432..4af5403240 100644 --- a/src/google/protobuf/compiler/cpp/cpp_message.cc +++ b/src/google/protobuf/compiler/cpp/cpp_message.cc @@ -554,7 +554,7 @@ void ColdChunkSkipper::OnStartChunk(int chunk, int cached_has_bit_index, } // Emit has_bit check for each has_bit_dword index. - format("if ($GOOGLE_PROTOBUF$_PREDICT_FALSE("); + format("if (PROTOBUF_PREDICT_FALSE("); int first_word = HasbitWord(chunk, 0); while (chunk < limit_chunk_) { uint32 mask = 0; @@ -940,8 +940,8 @@ void MessageGenerator::GenerateClassDefinition(io::Printer* printer) { " $default_enum_value$ > {\n" "public:\n" "#if $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n" - " static const char* _InternalParse(const char* begin, const char* " - "end, void* object, ::$proto_ns$::internal::ParseContext* ctx);\n" + "static bool _ParseMap(const char* begin, const " + "char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);\n" "#endif // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n" " typedef ::$proto_ns$::internal::MapEntry$lite$<$classname$, \n" " $key_cpp$, $val_cpp$,\n" @@ -1514,23 +1514,17 @@ bool MessageGenerator::GenerateParseTable(io::Printer* printer, size_t offset, // If we don't have field presence, then _has_bits_ does not exist. format("-1,\n"); } else { - format( - "$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET(\n" - " $classtype$, _has_bits_),\n"); + format("PROTOBUF_FIELD_OFFSET($classtype$, _has_bits_),\n"); } if (descriptor_->oneof_decl_count() > 0) { - format( - "$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET(\n" - " $classtype$, _oneof_case_),\n"); + format("PROTOBUF_FIELD_OFFSET($classtype$, _oneof_case_),\n"); } else { format("-1, // no _oneof_case_\n"); } if (descriptor_->extension_range_count() > 0) { - format( - "$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET($classtype$, " - "_extensions_),\n"); + format("PROTOBUF_FIELD_OFFSET($classtype$, _extensions_),\n"); } else { format("-1, // no _extensions_\n"); } @@ -1538,8 +1532,7 @@ bool MessageGenerator::GenerateParseTable(io::Printer* printer, size_t offset, // TODO(ckennelly): Consolidate this with the calculation for // AuxillaryParseTableField. format( - "$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET(\n" - " $classtype$, _internal_metadata_),\n" + "PROTOBUF_FIELD_OFFSET($classtype$, _internal_metadata_),\n" "&$package_ns$::_$classname$_default_instance_,\n"); if (UseUnknownFieldSet(descriptor_->file(), options_)) { @@ -1650,10 +1643,10 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) { Formatter::SaveState saver(&format); format.AddMap(vars); format( - "{$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET(" + "{PROTOBUF_FIELD_OFFSET(" "::$proto_ns$::internal::MapEntryHelper<$classtype$::" "SuperType>, $field_name$_), $tag$," - "$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET(" + "PROTOBUF_FIELD_OFFSET(" "::$proto_ns$::internal::MapEntryHelper<$classtype$::" "SuperType>, _has_bits_) * 8 + $hasbit$, $type$, " "$ptr$},\n"); @@ -1661,8 +1654,7 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) { return 2; } format( - "{$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET($classtype$, " - "_cached_size_), 0, 0, 0, NULL},\n"); + "{PROTOBUF_FIELD_OFFSET($classtype$, _cached_size_), 0, 0, 0, NULL},\n"); std::vector sorted_extensions; for (int i = 0; i < descriptor_->extension_range_count(); ++i) { sorted_extensions.push_back(descriptor_->extension_range(i)); @@ -1677,8 +1669,7 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) { const Descriptor::ExtensionRange* range = sorted_extensions[extension_idx]; format( - "{$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET($classtype$, " - "_extensions_), " + "{PROTOBUF_FIELD_OFFSET($classtype$, _extensions_), " "$1$, $2$, ::$proto_ns$::internal::FieldMetadata::kSpecial, " "reinterpret_cast(::$proto_ns$::internal::ExtensionSerializer)},\n", @@ -1703,8 +1694,7 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) { if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { if (IsMapEntryMessage(field->message_type())) { format( - "{$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET($" - "classtype$, $field_name$_), $1$, $2$, " + "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), $1$, $2$, " "::$proto_ns$::internal::FieldMetadata::kSpecial, " "reinterpret_cast(static_cast< " "::$proto_ns$::internal::SpecialSerializer>(" @@ -1745,7 +1735,7 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) { if (field->options().weak()) { // TODO(gerbens) merge weak fields into ranges format( - "{$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET(" + "{PROTOBUF_FIELD_OFFSET(" "$classtype$, _weak_field_map_), $1$, $1$, " "::$proto_ns$::internal::FieldMetadata::kSpecial, " "reinterpret_castcontaining_oneof()->index()); format( - "{$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET($classtype$, " - "$field_name$_), " - "$1$, $GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET($classtype$, " - "_oneof_case_) + $oneofoffset$, $2$, $3$},\n", + "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), $1$," + " PROTOBUF_FIELD_OFFSET($classtype$, _oneof_case_) + " + "$oneofoffset$, $2$, $3$},\n", tag, type, ptr); } else if (HasFieldPresence(descriptor_->file()) && has_bit_indices_[field->index()] != -1) { format.Set("hasbitsoffset", has_bit_indices_[field->index()]); format( - "{$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET($classtype$, " - "$field_name$_), " - "$1$, $GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET($classtype$, " - "_has_bits_) * 8 + $hasbitsoffset$, $2$, $3$},\n", + "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), " + "$1$, PROTOBUF_FIELD_OFFSET($classtype$, _has_bits_) * 8 + " + "$hasbitsoffset$, $2$, $3$},\n", tag, type, ptr); } else { format( - "{$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET($classtype$, " - "$field_name$_), " + "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), " "$1$, ~0u, $2$, $3$},\n", tag, type, ptr); } @@ -1783,8 +1770,7 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) { ? "UnknownFieldSetSerializer" : "UnknownFieldSerializerLite"; format( - "{$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET($classtype$, " - "_internal_metadata_), 0, ~0u, " + "{PROTOBUF_FIELD_OFFSET($classtype$, _internal_metadata_), 0, ~0u, " "::$proto_ns$::internal::FieldMetadata::kSpecial, reinterpret_cast(::$proto_ns$::internal::$1$)},\n", serializer); @@ -1876,12 +1862,62 @@ void MessageGenerator::GenerateClassMethods(io::Printer* printer) { "}\n" "\n"); } - // TODO(gerbens) make maps parse :( format( "#if $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n" - "const char* $classname$::_InternalParse(const char* begin, const " - "char* end, void* object, ::$proto_ns$::internal::ParseContext* ctx) { " - "return end; }\n" + "bool $classname$::_ParseMap(const char* begin, const " + "char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) {\n" + " using MF = ::$proto_ns$::internal::MapField$1$<\n" + " $classname$, EntryKeyType, EntryValueType,\n" + " kEntryKeyFieldType, kEntryValueFieldType,\n" + " kEntryDefaultEnumValue>;\n" + " auto mf = static_cast(object);\n" + " Parser> " + "parser(mf);\n" + "#define DO_(x) if (!(x)) return false\n", + HasDescriptorMethods(descriptor_->file(), options_) ? "" : "Lite"); + const FieldDescriptor* key = descriptor_->FindFieldByName("key"); + const FieldDescriptor* val = descriptor_->FindFieldByName("value"); + GOOGLE_CHECK(val); + string key_string; + string value_string; + if (HasFieldPresence(descriptor_->file()) && + val->type() == FieldDescriptor::TYPE_ENUM) { + format( + " DO_(parser.ParseMapEnumValidation(\n" + " begin, end, ctx->extra_parse_data().field_number,\n" + " static_cast<::google::protobuf::internal::InternalMetadataWithArena$1$*>(" + "ctx->extra_parse_data().unknown_fields), $2$_IsValid));\n", + HasDescriptorMethods(descriptor_->file(), options_) ? "" : "Lite", + QualifiedClassName(val->enum_type())); + key_string = "parser.entry_key()"; + value_string = "parser.entry_value()"; + } else { + format(" DO_(parser.ParseMap(begin, end));\n"); + key_string = "parser.key()"; + value_string = "parser.value()"; + } + format.Indent(); + if (key->type() == FieldDescriptor::TYPE_STRING) { + GenerateUtf8CheckCodeForString( + key, options_, true, + StrCat(key_string, ".data(), static_cast(", key_string, + ".length()),\n") + .data(), + format); + } + if (val->type() == FieldDescriptor::TYPE_STRING) { + GenerateUtf8CheckCodeForString( + val, options_, true, + StrCat(value_string, ".data(), static_cast(", value_string, + ".length()),\n") + .data(), + format); + } + format.Outdent(); + format( + "#undef DO_\n" + " return true;\n" + "}\n" "#endif // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n"); format("\n"); return; @@ -2138,8 +2174,7 @@ size_t MessageGenerator::GenerateParseOffsets(io::Printer* printer) { format( "{\n" - " $GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET(\n" - " $classtype$, $name$_),\n" + " PROTOBUF_FIELD_OFFSET($classtype$, $name$_),\n" " static_cast<$uint32$>($presence$),\n" " $nwtype$, $pwtype$, $ptype$, $tag_size$\n" "},\n"); @@ -2236,33 +2271,23 @@ std::pair MessageGenerator::GenerateOffsets( Formatter format(printer, variables_); if (HasFieldPresence(descriptor_->file()) || IsMapEntryMessage(descriptor_)) { - format( - "$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET($classtype$, " - "_has_bits_),\n"); + format("PROTOBUF_FIELD_OFFSET($classtype$, _has_bits_),\n"); } else { format("~0u, // no _has_bits_\n"); } - format( - "$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET($classtype$, " - "_internal_metadata_),\n"); + format("PROTOBUF_FIELD_OFFSET($classtype$, _internal_metadata_),\n"); if (descriptor_->extension_range_count() > 0) { - format( - "$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET($classtype$, " - "_extensions_),\n"); + format("PROTOBUF_FIELD_OFFSET($classtype$, _extensions_),\n"); } else { format("~0u, // no _extensions_\n"); } if (descriptor_->oneof_decl_count() > 0) { - format( - "$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET(" - "$classtype$, _oneof_case_[0]),\n"); + format("PROTOBUF_FIELD_OFFSET($classtype$, _oneof_case_[0]),\n"); } else { format("~0u, // no _oneof_case_\n"); } if (num_weak_fields_ > 0) { - format( - "$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET($classtype$," - " _weak_field_map_),\n"); + format("PROTOBUF_FIELD_OFFSET($classtype$, _weak_field_map_),\n"); } else { format("~0u, // no _weak_field_map_\n"); } @@ -2275,9 +2300,7 @@ std::pair MessageGenerator::GenerateOffsets( format("offsetof($classtype$DefaultTypeInternal, $1$_)", FieldName(field)); } else { - format( - "$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET($classtype$, $1$_)", - FieldName(field)); + format("PROTOBUF_FIELD_OFFSET($classtype$, $1$_)", FieldName(field)); } uint32 tag = field_generators_.get(field).CalculateFieldTag(); @@ -2289,9 +2312,7 @@ std::pair MessageGenerator::GenerateOffsets( } for (auto oneof : OneOfRange(descriptor_)) { - format( - "$GOOGLE_PROTOBUF$_GENERATED_MESSAGE_FIELD_OFFSET($classtype$, $1$_),\n", - oneof->name()); + format("PROTOBUF_FIELD_OFFSET($classtype$, $1$_),\n", oneof->name()); } if (IsMapEntryMessage(descriptor_)) { @@ -2687,7 +2708,7 @@ void MessageGenerator::GenerateSourceInProto2Namespace(io::Printer* printer) { Formatter format(printer, variables_); format( "template<> " - "$GOOGLE_PROTOBUF$_ATTRIBUTE_NOINLINE " + "PROTOBUF_NOINLINE " "$classtype$* Arena::CreateMaybeMessage< $classtype$ >(Arena* arena) {\n" " return Arena::$1$Internal< $classtype$ >(arena);\n" "}\n", @@ -3334,8 +3355,9 @@ void MessageGenerator::GenerateMergeFromCodedStream(io::Printer* printer) { "const char* $classname$::_InternalParse(const char* begin, const " "char* end, void* object,\n" " ::$proto_ns$::internal::ParseContext* ctx) {\n" + " auto msg = static_cast<$classname$*>(object);\n" " return ::$proto_ns$::internal::ParseMessageSet(begin, end, " - "static_cast<$classname$*>(object), ctx);\n" + "msg, &msg->_extensions_, &msg->_internal_metadata_, ctx);\n" "}\n" "const char* $classname$::InternalParseMessageSetItem(const char* " "begin, const char* end, void* object,\n" @@ -3396,7 +3418,7 @@ void MessageGenerator::GenerateMergeFromCodedStream(io::Printer* printer) { format( "#define DO_(EXPRESSION) if " - "(!$GOOGLE_PROTOBUF$_PREDICT_TRUE(EXPRESSION)) goto failure\n" + "(!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure\n" " $uint32$ tag;\n"); if (!UseUnknownFieldSet(descriptor_->file(), options_)) { @@ -3801,11 +3823,12 @@ void MessageGenerator::GenerateSerializeWithCachedSizesToArray( " target = _extensions_." "InternalSerializeMessageSetWithCachedSizesToArray(\n" " deterministic, target);\n"); + GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file(), options_)); std::map vars; SetUnknkownFieldsVariable(descriptor_, options_, &vars); format.AddMap(vars); format( - " target = ::$proto_ns$::internal::\n" + " target = ::$proto_ns$::internal::WireFormat::\n" " SerializeUnknownMessageSetItemsToArray(\n" " $unknown_fields$, target);\n"); format( diff --git a/src/google/protobuf/compiler/cpp/cpp_message.h b/src/google/protobuf/compiler/cpp/cpp_message.h index 170a70cd08..6bef8d5664 100644 --- a/src/google/protobuf/compiler/cpp/cpp_message.h +++ b/src/google/protobuf/compiler/cpp/cpp_message.h @@ -63,7 +63,7 @@ class MessageGenerator { public: // See generator.cc for the meaning of dllexport_decl. MessageGenerator(const Descriptor* descriptor, - const std::map& vars, + const std::map& vars, int index_in_file_messages, const Options& options, MessageSCCAnalyzer* scc_analyzer); ~MessageGenerator(); @@ -194,7 +194,7 @@ class MessageGenerator { const Descriptor* descriptor_; int index_in_file_messages_; - string classname_; + std::string classname_; Options options_; FieldGeneratorMap field_generators_; // optimized_order_ is the order we layout the message's fields in the @@ -216,7 +216,7 @@ class MessageGenerator { MessageSCCAnalyzer* scc_analyzer_; - std::map variables_; + std::map variables_; friend class FileGenerator; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator); diff --git a/src/google/protobuf/compiler/cpp/cpp_options.h b/src/google/protobuf/compiler/cpp/cpp_options.h index 6a364debee..84c18622a4 100644 --- a/src/google/protobuf/compiler/cpp/cpp_options.h +++ b/src/google/protobuf/compiler/cpp/cpp_options.h @@ -35,7 +35,6 @@ #include -#include namespace google { namespace protobuf { namespace compiler { @@ -45,7 +44,7 @@ namespace cpp { // Generator options (see generator.cc for a description of each): struct Options { - string dllexport_decl; + std::string dllexport_decl; bool safe_boundary_check = false; bool proto_h = false; bool transitive_pb_h = true; @@ -58,8 +57,8 @@ struct Options { bool opensource_runtime = false; bool opensource_include_paths = false; int num_cc_files = 0; - string annotation_pragma_name; - string annotation_guard_name; + std::string annotation_pragma_name; + std::string annotation_guard_name; const AccessInfoMap* access_info_map = nullptr; }; diff --git a/src/google/protobuf/compiler/cpp/cpp_service.h b/src/google/protobuf/compiler/cpp/cpp_service.h index 3acbe637c5..2952e413b8 100644 --- a/src/google/protobuf/compiler/cpp/cpp_service.h +++ b/src/google/protobuf/compiler/cpp/cpp_service.h @@ -57,7 +57,7 @@ class ServiceGenerator { public: // See generator.cc for the meaning of dllexport_decl. explicit ServiceGenerator(const ServiceDescriptor* descriptor, - const std::map& vars, + const std::map& vars, const Options& options); ~ServiceGenerator(); @@ -109,7 +109,7 @@ class ServiceGenerator { void GenerateStubMethods(io::Printer* printer); const ServiceDescriptor* descriptor_; - std::map vars_; + std::map vars_; int index_in_metadata_; diff --git a/src/google/protobuf/compiler/cpp/cpp_unittest.inc b/src/google/protobuf/compiler/cpp/cpp_unittest.inc index 0604731f09..898b1fbb94 100644 --- a/src/google/protobuf/compiler/cpp/cpp_unittest.inc +++ b/src/google/protobuf/compiler/cpp/cpp_unittest.inc @@ -78,6 +78,8 @@ #include #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -203,7 +205,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, ExtremeSmallIntegerDefault) { const UNITTEST::TestExtremeDefaultValues& extreme_default = UNITTEST::TestExtremeDefaultValues::default_instance(); EXPECT_EQ(~0x7fffffff, kint32min); - EXPECT_EQ(GOOGLE_LONGLONG(~0x7fffffffffffffff), kint64min); + EXPECT_EQ(PROTOBUF_LONGLONG(~0x7fffffffffffffff), kint64min); EXPECT_EQ(kint32min, extreme_default.really_small_int32()); EXPECT_EQ(kint64min, extreme_default.really_small_int64()); } @@ -656,7 +658,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, CopyAssignmentOperator) { TestUtil::ExpectAllFieldsSet(message2); } -#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || GOOGLE_PROTOBUF_RTTI +#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || PROTOBUF_RTTI TEST(GENERATED_MESSAGE_TEST_NAME, UpcastCopyFrom) { // Test the CopyFrom method that takes in the generic const Message& // parameter. @@ -2267,3 +2269,5 @@ TEST(DESCRIPTOR_INIT_TEST_NAME, Initialized) { } // namespace compiler } // namespace protobuf } // namespace google + +#include diff --git a/src/google/protobuf/compiler/csharp/csharp_generator.h b/src/google/protobuf/compiler/csharp/csharp_generator.h index c8b1952913..dc7319b196 100644 --- a/src/google/protobuf/compiler/csharp/csharp_generator.h +++ b/src/google/protobuf/compiler/csharp/csharp_generator.h @@ -37,6 +37,8 @@ #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -46,9 +48,9 @@ namespace csharp { // header. If you create your own protocol compiler binary and you want // it to support C# output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT Generator +class PROTOC_EXPORT Generator : public google::protobuf::compiler::CodeGenerator { -public: + public: virtual bool Generate( const FileDescriptor* file, const string& parameter, @@ -61,4 +63,6 @@ public: } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_GENERATOR_H__ diff --git a/src/google/protobuf/compiler/csharp/csharp_helpers.h b/src/google/protobuf/compiler/csharp/csharp_helpers.h index 8dd265bcf3..ec0b1c77d1 100644 --- a/src/google/protobuf/compiler/csharp/csharp_helpers.h +++ b/src/google/protobuf/compiler/csharp/csharp_helpers.h @@ -42,6 +42,8 @@ #include #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -96,7 +98,8 @@ std::string UnderscoresToPascalCase(const std::string& input); // Note that we wouldn't normally want to export this (we're not expecting // it to be used outside libprotoc itself) but this exposes it for testing. -std::string LIBPROTOC_EXPORT GetEnumValueName(const std::string& enum_name, const std::string& enum_value_name); +std::string PROTOC_EXPORT GetEnumValueName(const std::string& enum_name, + const std::string& enum_value_name); // TODO(jtattermusch): perhaps we could move this to strutil std::string StringToBase64(const std::string& input); @@ -145,4 +148,7 @@ inline bool IsWrapperType(const FieldDescriptor* descriptor) { } // namespace compiler } // namespace protobuf } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_HELPERS_H__ diff --git a/src/google/protobuf/compiler/csharp/csharp_names.h b/src/google/protobuf/compiler/csharp/csharp_names.h index 21758f2882..87a16515d7 100644 --- a/src/google/protobuf/compiler/csharp/csharp_names.h +++ b/src/google/protobuf/compiler/csharp/csharp_names.h @@ -41,6 +41,8 @@ #include #include +#include + namespace google { namespace protobuf { @@ -57,14 +59,14 @@ namespace csharp { // // Returns: // The namespace to use for given file descriptor. -string LIBPROTOC_EXPORT GetFileNamespace(const FileDescriptor* descriptor); +string PROTOC_EXPORT GetFileNamespace(const FileDescriptor* descriptor); // Requires: // descriptor != NULL // // Returns: // The fully-qualified C# class name. -string LIBPROTOC_EXPORT GetClassName(const Descriptor* descriptor); +string PROTOC_EXPORT GetClassName(const Descriptor* descriptor); // Requires: // descriptor != NULL @@ -73,7 +75,7 @@ string LIBPROTOC_EXPORT GetClassName(const Descriptor* descriptor); // The fully-qualified name of the C# class that provides // access to the file descriptor. Proto compiler generates // such class for each .proto file processed. -string LIBPROTOC_EXPORT GetReflectionClassName(const FileDescriptor* descriptor); +string PROTOC_EXPORT GetReflectionClassName(const FileDescriptor* descriptor); // Generates output file name for given file descriptor. If generate_directories // is true, the output file will be put under directory corresponding to file's @@ -89,16 +91,16 @@ string LIBPROTOC_EXPORT GetReflectionClassName(const FileDescriptor* descriptor) // The file name to use as output file for given file descriptor. In case // of failure, this function will return empty string and error parameter // will contain the error message. -string LIBPROTOC_EXPORT GetOutputFile( - const google::protobuf::FileDescriptor* descriptor, - const string file_extension, - const bool generate_directories, - const string base_namespace, - string* error); +string PROTOC_EXPORT +GetOutputFile(const google::protobuf::FileDescriptor* descriptor, + const string file_extension, const bool generate_directories, + const string base_namespace, string* error); } // namespace csharp } // namespace compiler } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_NAMES_H__ diff --git a/src/google/protobuf/compiler/importer.h b/src/google/protobuf/compiler/importer.h index 5f27907845..cf6b0123e3 100644 --- a/src/google/protobuf/compiler/importer.h +++ b/src/google/protobuf/compiler/importer.h @@ -45,6 +45,8 @@ #include #include +#include + namespace google { namespace protobuf { @@ -73,7 +75,7 @@ class DiskSourceTree; // // Note: This class does not implement FindFileContainingSymbol() or // FindFileContainingExtension(); these will always return false. -class LIBPROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabase { +class PROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabase { public: SourceTreeDescriptorDatabase(SourceTree* source_tree); ~SourceTreeDescriptorDatabase(); @@ -96,11 +98,11 @@ class LIBPROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabas } // implements DescriptorDatabase ----------------------------------- - bool FindFileByName(const string& filename, + bool FindFileByName(const std::string& filename, FileDescriptorProto* output) override; - bool FindFileContainingSymbol(const string& symbol_name, + bool FindFileContainingSymbol(const std::string& symbol_name, FileDescriptorProto* output) override; - bool FindFileContainingExtension(const string& containing_type, + bool FindFileContainingExtension(const std::string& containing_type, int field_number, FileDescriptorProto* output) override; @@ -110,19 +112,20 @@ class LIBPROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabas SourceTree* source_tree_; MultiFileErrorCollector* error_collector_; - class LIBPROTOBUF_EXPORT ValidationErrorCollector : public DescriptorPool::ErrorCollector { + class PROTOBUF_EXPORT ValidationErrorCollector + : public DescriptorPool::ErrorCollector { public: ValidationErrorCollector(SourceTreeDescriptorDatabase* owner); ~ValidationErrorCollector(); // implements ErrorCollector --------------------------------------- - void AddError(const string& filename, const string& element_name, + void AddError(const std::string& filename, const std::string& element_name, const Message* descriptor, ErrorLocation location, - const string& message) override; + const std::string& message) override; - void AddWarning(const string& filename, const string& element_name, + void AddWarning(const std::string& filename, const std::string& element_name, const Message* descriptor, ErrorLocation location, - const string& message) override; + const std::string& message) override; private: SourceTreeDescriptorDatabase* owner_; @@ -142,7 +145,7 @@ class LIBPROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabas // You may find that SourceTreeDescriptorDatabase is more flexible. // // TODO(kenton): I feel like this class is not well-named. -class LIBPROTOBUF_EXPORT Importer { +class PROTOBUF_EXPORT Importer { public: Importer(SourceTree* source_tree, MultiFileErrorCollector* error_collector); @@ -161,7 +164,7 @@ class LIBPROTOBUF_EXPORT Importer { // you want to see errors for the same files repeatedly, you can use a // separate Importer object to import each one (but use the same // DescriptorPool so that they can be cross-linked). - const FileDescriptor* Import(const string& filename); + const FileDescriptor* Import(const std::string& filename); // The DescriptorPool in which all imported FileDescriptors and their // contents are stored. @@ -169,7 +172,7 @@ class LIBPROTOBUF_EXPORT Importer { return &pool_; } - void AddUnusedImportTrackFile(const string& file_name); + void AddUnusedImportTrackFile(const std::string& file_name); void ClearUnusedImportTrackFiles(); @@ -182,18 +185,18 @@ class LIBPROTOBUF_EXPORT Importer { // If the importer encounters problems while trying to import the proto files, // it reports them to a MultiFileErrorCollector. -class LIBPROTOBUF_EXPORT MultiFileErrorCollector { +class PROTOBUF_EXPORT MultiFileErrorCollector { public: inline MultiFileErrorCollector() {} virtual ~MultiFileErrorCollector(); // Line and column numbers are zero-based. A line number of -1 indicates // an error with the entire file (e.g. "not found"). - virtual void AddError(const string& filename, int line, int column, - const string& message) = 0; + virtual void AddError(const std::string& filename, int line, int column, + const std::string& message) = 0; - virtual void AddWarning(const string& filename, int line, int column, - const string& message) {} + virtual void AddWarning(const std::string& filename, int line, int column, + const std::string& message) {} private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MultiFileErrorCollector); @@ -203,7 +206,7 @@ class LIBPROTOBUF_EXPORT MultiFileErrorCollector { // Used by the default implementation of Importer to resolve import statements // Most users will probably want to use the DiskSourceTree implementation, // below. -class LIBPROTOBUF_EXPORT SourceTree { +class PROTOBUF_EXPORT SourceTree { public: inline SourceTree() {} virtual ~SourceTree(); @@ -212,14 +215,14 @@ class LIBPROTOBUF_EXPORT SourceTree { // found. The caller takes ownership of the returned object. The filename // must be a path relative to the root of the source tree and must not // contain "." or ".." components. - virtual io::ZeroCopyInputStream* Open(const string& filename) = 0; + virtual io::ZeroCopyInputStream* Open(const std::string& filename) = 0; // If Open() returns NULL, calling this method immediately will return an // description of the error. // Subclasses should implement this method and return a meaningful value for // better error reporting. // TODO(xiaofeng): change this to a pure virtual function. - virtual string GetLastErrorMessage(); + virtual std::string GetLastErrorMessage(); private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SourceTree); @@ -228,7 +231,7 @@ class LIBPROTOBUF_EXPORT SourceTree { // An implementation of SourceTree which loads files from locations on disk. // Multiple mappings can be set up to map locations in the DiskSourceTree to // locations in the physical filesystem. -class LIBPROTOBUF_EXPORT DiskSourceTree : public SourceTree { +class PROTOBUF_EXPORT DiskSourceTree : public SourceTree { public: DiskSourceTree(); ~DiskSourceTree(); @@ -249,7 +252,7 @@ class LIBPROTOBUF_EXPORT DiskSourceTree : public SourceTree { // // disk_path may be an absolute path or relative to the current directory, // just like a path you'd pass to open(). - void MapPath(const string& virtual_path, const string& disk_path); + void MapPath(const std::string& virtual_path, const std::string& disk_path); // Return type for DiskFileToVirtualFile(). enum DiskFileToVirtualFileResult { @@ -280,39 +283,39 @@ class LIBPROTOBUF_EXPORT DiskSourceTree : public SourceTree { // * NO_MAPPING: Indicates that no mapping was found which contains this // file. DiskFileToVirtualFileResult - DiskFileToVirtualFile(const string& disk_file, - string* virtual_file, - string* shadowing_disk_file); + DiskFileToVirtualFile(const std::string& disk_file, + std::string* virtual_file, + std::string* shadowing_disk_file); // Given a virtual path, find the path to the file on disk. // Return true and update disk_file with the on-disk path if the file exists. // Return false and leave disk_file untouched if the file doesn't exist. - bool VirtualFileToDiskFile(const string& virtual_file, string* disk_file); + bool VirtualFileToDiskFile(const std::string& virtual_file, std::string* disk_file); // implements SourceTree ------------------------------------------- - io::ZeroCopyInputStream* Open(const string& filename) override; + io::ZeroCopyInputStream* Open(const std::string& filename) override; - string GetLastErrorMessage() override; + std::string GetLastErrorMessage() override; private: struct Mapping { - string virtual_path; - string disk_path; + std::string virtual_path; + std::string disk_path; - inline Mapping(const string& virtual_path_param, - const string& disk_path_param) + inline Mapping(const std::string& virtual_path_param, + const std::string& disk_path_param) : virtual_path(virtual_path_param), disk_path(disk_path_param) {} }; std::vector mappings_; - string last_error_message_; + std::string last_error_message_; // Like Open(), but returns the on-disk path in disk_file if disk_file is // non-NULL and the file could be successfully opened. - io::ZeroCopyInputStream* OpenVirtualFile(const string& virtual_file, - string* disk_file); + io::ZeroCopyInputStream* OpenVirtualFile(const std::string& virtual_file, + std::string* disk_file); // Like Open() but given the actual on-disk path. - io::ZeroCopyInputStream* OpenDiskFile(const string& filename); + io::ZeroCopyInputStream* OpenDiskFile(const std::string& filename); GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DiskSourceTree); }; @@ -321,4 +324,6 @@ class LIBPROTOBUF_EXPORT DiskSourceTree : public SourceTree { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_IMPORTER_H__ diff --git a/src/google/protobuf/compiler/java/java_doc_comment.h b/src/google/protobuf/compiler/java/java_doc_comment.h index 112c3bc3c1..ef9b3a9072 100644 --- a/src/google/protobuf/compiler/java/java_doc_comment.h +++ b/src/google/protobuf/compiler/java/java_doc_comment.h @@ -37,6 +37,8 @@ #include +#include + namespace google { namespace protobuf { namespace io { @@ -61,11 +63,13 @@ void WriteMethodDocComment(io::Printer* printer, const MethodDescriptor* method); // Exposed for testing only. -LIBPROTOC_EXPORT string EscapeJavadoc(const string& input); +PROTOC_EXPORT std::string EscapeJavadoc(const std::string& input); } // namespace java } // namespace compiler } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_DOC_COMMENT_H__ diff --git a/src/google/protobuf/compiler/java/java_enum_field.h b/src/google/protobuf/compiler/java/java_enum_field.h index 842da59270..723102d8a0 100644 --- a/src/google/protobuf/compiler/java/java_enum_field.h +++ b/src/google/protobuf/compiler/java/java_enum_field.h @@ -81,11 +81,11 @@ class ImmutableEnumFieldGenerator : public ImmutableFieldGenerator { void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; const int builderBitIndex_; Context* context_; @@ -142,11 +142,11 @@ class RepeatedImmutableEnumFieldGenerator : public ImmutableFieldGenerator { void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; private: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; const int builderBitIndex_; Context* context_; diff --git a/src/google/protobuf/compiler/java/java_enum_field_lite.h b/src/google/protobuf/compiler/java/java_enum_field_lite.h index 6bda426fb2..bf25ffaafe 100644 --- a/src/google/protobuf/compiler/java/java_enum_field_lite.h +++ b/src/google/protobuf/compiler/java/java_enum_field_lite.h @@ -79,11 +79,11 @@ class ImmutableEnumFieldLiteGenerator : public ImmutableFieldLiteGenerator { void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; Context* context_; ClassNameResolver* name_resolver_; @@ -136,11 +136,11 @@ class RepeatedImmutableEnumFieldLiteGenerator void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; private: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; Context* context_; ClassNameResolver* name_resolver_; diff --git a/src/google/protobuf/compiler/java/java_extension.h b/src/google/protobuf/compiler/java/java_extension.h index 7a58373f35..1f11324c49 100644 --- a/src/google/protobuf/compiler/java/java_extension.h +++ b/src/google/protobuf/compiler/java/java_extension.h @@ -80,9 +80,9 @@ class ExtensionGenerator { protected: static void InitTemplateVars(const FieldDescriptor* descriptor, - const string& scope, bool immutable, + const std::string& scope, bool immutable, ClassNameResolver* name_resolver, - std::map* vars_pointer); + std::map* vars_pointer); private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator); @@ -102,7 +102,7 @@ class ImmutableExtensionGenerator : public ExtensionGenerator { const FieldDescriptor* descriptor_; Context* context_; ClassNameResolver* name_resolver_; - string scope_; + std::string scope_; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableExtensionGenerator); diff --git a/src/google/protobuf/compiler/java/java_extension_lite.h b/src/google/protobuf/compiler/java/java_extension_lite.h index 34716f9d84..eaa90a4b9f 100644 --- a/src/google/protobuf/compiler/java/java_extension_lite.h +++ b/src/google/protobuf/compiler/java/java_extension_lite.h @@ -63,7 +63,7 @@ class ImmutableExtensionLiteGenerator : public ExtensionGenerator { const FieldDescriptor* descriptor_; Context* context_; ClassNameResolver* name_resolver_; - string scope_; + std::string scope_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableExtensionLiteGenerator); }; diff --git a/src/google/protobuf/compiler/java/java_field.h b/src/google/protobuf/compiler/java/java_field.h index 881427d78c..abefc58972 100644 --- a/src/google/protobuf/compiler/java/java_field.h +++ b/src/google/protobuf/compiler/java/java_field.h @@ -87,7 +87,7 @@ class ImmutableFieldGenerator { virtual void GenerateEqualsCode(io::Printer* printer) const = 0; virtual void GenerateHashCode(io::Printer* printer) const = 0; - virtual string GetBoxedType() const = 0; + virtual std::string GetBoxedType() const = 0; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableFieldGenerator); @@ -118,7 +118,7 @@ class ImmutableFieldLiteGenerator { virtual void GenerateHashCode(io::Printer* printer) const = 0; - virtual string GetBoxedType() const = 0; + virtual std::string GetBoxedType() const = 0; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableFieldLiteGenerator); @@ -171,29 +171,29 @@ FieldGeneratorMap::~FieldGeneratorMap(); // Field information used in FieldGeneartors. struct FieldGeneratorInfo { - string name; - string capitalized_name; - string disambiguated_reason; + std::string name; + std::string capitalized_name; + std::string disambiguated_reason; }; // Oneof information used in OneofFieldGenerators. struct OneofGeneratorInfo { - string name; - string capitalized_name; + std::string name; + std::string capitalized_name; }; // Set some common variables used in variable FieldGenerators. void SetCommonFieldVariables(const FieldDescriptor* descriptor, const FieldGeneratorInfo* info, - std::map* variables); + std::map* variables); // Set some common oneof variables used in OneofFieldGenerators. void SetCommonOneofVariables(const FieldDescriptor* descriptor, const OneofGeneratorInfo* info, - std::map* variables); + std::map* variables); // Print useful comments before a field's accessors. -void PrintExtraFieldInfo(const std::map& variables, +void PrintExtraFieldInfo(const std::map& variables, io::Printer* printer); } // namespace java diff --git a/src/google/protobuf/compiler/java/java_file.cc b/src/google/protobuf/compiler/java/java_file.cc index 5dc2dff87b..5356512ced 100644 --- a/src/google/protobuf/compiler/java/java_file.cc +++ b/src/google/protobuf/compiler/java/java_file.cc @@ -232,7 +232,9 @@ bool FileGenerator::Validate(string* error) { << "will be ignored by protoc in the future and protoc will always " << "generate full runtime code for Java. To use Java Lite runtime, " << "users should use the Java Lite plugin instead. See:\n" - << " https://github.com/protocolbuffers/protobuf/blob/master/java/lite.md"; + << " " + "https://github.com/protocolbuffers/protobuf/blob/master/java/" + "lite.md"; } return true; } diff --git a/src/google/protobuf/compiler/java/java_file.h b/src/google/protobuf/compiler/java/java_file.h index 4158d48b99..9dca82bbcf 100644 --- a/src/google/protobuf/compiler/java/java_file.h +++ b/src/google/protobuf/compiler/java/java_file.h @@ -74,20 +74,20 @@ class FileGenerator { // Checks for problems that would otherwise lead to cryptic compile errors. // Returns true if there are no problems, or writes an error description to // the given string and returns false otherwise. - bool Validate(string* error); + bool Validate(std::string* error); void Generate(io::Printer* printer); // If we aren't putting everything into one file, this will write all the // files other than the outer file (i.e. one for each message, enum, and // service type). - void GenerateSiblings(const string& package_dir, + void GenerateSiblings(const std::string& package_dir, GeneratorContext* generator_context, - std::vector* file_list, - std::vector* annotation_list); + std::vector* file_list, + std::vector* annotation_list); - const string& java_package() { return java_package_; } - const string& classname() { return classname_; } + const std::string& java_package() { return java_package_; } + const std::string& classname() { return classname_; } private: void GenerateDescriptorInitializationCodeForImmutable(io::Printer* printer); @@ -97,8 +97,8 @@ class FileGenerator { bool immutable_api_); const FileDescriptor* file_; - string java_package_; - string classname_; + std::string java_package_; + std::string classname_; std::vector> message_generators_; std::vector> extension_generators_; diff --git a/src/google/protobuf/compiler/java/java_generator.h b/src/google/protobuf/compiler/java/java_generator.h index 6eefdd8431..21873581a7 100644 --- a/src/google/protobuf/compiler/java/java_generator.h +++ b/src/google/protobuf/compiler/java/java_generator.h @@ -40,6 +40,8 @@ #include #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -49,16 +51,16 @@ namespace java { // own protocol compiler binary and you want it to support Java output, you // can do so by registering an instance of this CodeGenerator with the // CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT JavaGenerator : public CodeGenerator { +class PROTOC_EXPORT JavaGenerator : public CodeGenerator { public: JavaGenerator(); ~JavaGenerator(); // implements CodeGenerator ---------------------------------------- bool Generate(const FileDescriptor* file, - const string& parameter, + const std::string& parameter, GeneratorContext* context, - string* error) const; + std::string* error) const; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(JavaGenerator); @@ -69,4 +71,6 @@ class LIBPROTOC_EXPORT JavaGenerator : public CodeGenerator { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_GENERATOR_H__ diff --git a/src/google/protobuf/compiler/java/java_helpers.h b/src/google/protobuf/compiler/java/java_helpers.h index 375bd67d26..93caa3dc9e 100644 --- a/src/google/protobuf/compiler/java/java_helpers.h +++ b/src/google/protobuf/compiler/java/java_helpers.h @@ -60,89 +60,89 @@ extern const char kThinSeparator[]; // annotation_file should be generated from the filename of the source file // being annotated (which in turn must be a Java identifier plus ".java"). void PrintGeneratedAnnotation(io::Printer* printer, char delimiter = '$', - const string& annotation_file = ""); + const std::string& annotation_file = ""); // If a GeneratedMessageLite contains non-lite enums, then its verifier // must be instantiated inline, rather than retrieved from the enum class. void PrintEnumVerifierLogic(io::Printer* printer, const FieldDescriptor* descriptor, - const std::map& variables, + const std::map& variables, const char* var_name, const char* terminating_string, bool enforce_lite); // Converts a name to camel-case. If cap_first_letter is true, capitalize the // first letter. -string UnderscoresToCamelCase(const string& name, bool cap_first_letter); +std::string UnderscoresToCamelCase(const std::string& name, bool cap_first_letter); // Converts the field's name to camel-case, e.g. "foo_bar_baz" becomes // "fooBarBaz" or "FooBarBaz", respectively. -string UnderscoresToCamelCase(const FieldDescriptor* field); -string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field); +std::string UnderscoresToCamelCase(const FieldDescriptor* field); +std::string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field); // Similar, but for method names. (Typically, this merely has the effect // of lower-casing the first letter of the name.) -string UnderscoresToCamelCase(const MethodDescriptor* method); +std::string UnderscoresToCamelCase(const MethodDescriptor* method); // Similar to UnderscoresToCamelCase, but guarentees that the result is a // complete Java identifier by adding a _ if needed. -string CamelCaseFieldName(const FieldDescriptor* field); +std::string CamelCaseFieldName(const FieldDescriptor* field); // Get an identifier that uniquely identifies this type within the file. // This is used to declare static variables related to this type at the // outermost file scope. -string UniqueFileScopeIdentifier(const Descriptor* descriptor); +std::string UniqueFileScopeIdentifier(const Descriptor* descriptor); // Strips ".proto" or ".protodevel" from the end of a filename. -string StripProto(const string& filename); +std::string StripProto(const std::string& filename); // Gets the unqualified class name for the file. For each .proto file, there // will be one Java class containing all the immutable messages and another // Java class containing all the mutable messages. // TODO(xiaofeng): remove the default value after updating client code. -string FileClassName(const FileDescriptor* file, bool immutable = true); +std::string FileClassName(const FileDescriptor* file, bool immutable = true); // Returns the file's Java package name. -string FileJavaPackage(const FileDescriptor* file); -string FileJavaPackage(const FileDescriptor* file, bool immutable); +std::string FileJavaPackage(const FileDescriptor* file); +std::string FileJavaPackage(const FileDescriptor* file, bool immutable); // Returns output directory for the given package name. -string JavaPackageToDir(string package_name); +std::string JavaPackageToDir(std::string package_name); // Converts the given fully-qualified name in the proto namespace to its // fully-qualified name in the Java namespace, given that it is in the given // file. // TODO(xiaofeng): this method is deprecated and should be removed in the // future. -string ToJavaName(const string& full_name, +std::string ToJavaName(const std::string& full_name, const FileDescriptor* file); // TODO(xiaofeng): the following methods are kept for they are exposed // publicly in //net/proto2/compiler/java/public/names.h. They return // immutable names only and should be removed after mutable API is // integrated into google3. -string ClassName(const Descriptor* descriptor); -string ClassName(const EnumDescriptor* descriptor); -string ClassName(const ServiceDescriptor* descriptor); -string ClassName(const FileDescriptor* descriptor); +std::string ClassName(const Descriptor* descriptor); +std::string ClassName(const EnumDescriptor* descriptor); +std::string ClassName(const ServiceDescriptor* descriptor); +std::string ClassName(const FileDescriptor* descriptor); // Comma-separate list of option-specified interfaces implemented by the // Message, to follow the "implements" declaration of the Message definition. -string ExtraMessageInterfaces(const Descriptor* descriptor); +std::string ExtraMessageInterfaces(const Descriptor* descriptor); // Comma-separate list of option-specified interfaces implemented by the // MutableMessage, to follow the "implements" declaration of the MutableMessage // definition. -string ExtraMutableMessageInterfaces(const Descriptor* descriptor); +std::string ExtraMutableMessageInterfaces(const Descriptor* descriptor); // Comma-separate list of option-specified interfaces implemented by the // Builder, to follow the "implements" declaration of the Builder definition. -string ExtraBuilderInterfaces(const Descriptor* descriptor); +std::string ExtraBuilderInterfaces(const Descriptor* descriptor); // Comma-separate list of option-specified interfaces extended by the // MessageOrBuilder, to follow the "extends" declaration of the // MessageOrBuilder definition. -string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor); +std::string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor); // Get the unqualified Java class name for mutable messages. i.e. without // package or outer classnames. -inline string ShortMutableJavaClassName(const Descriptor* descriptor) { +inline std::string ShortMutableJavaClassName(const Descriptor* descriptor) { return descriptor->name(); } @@ -179,14 +179,14 @@ inline bool IsOwnFile(const ServiceDescriptor* descriptor, bool immutable) { // annotation data for that descriptor. `suffix` is usually empty, but may // (e.g.) be "OrBuilder" for some generated interfaces. template -string AnnotationFileName(const Descriptor* descriptor, const string& suffix) { +std::string AnnotationFileName(const Descriptor* descriptor, const std::string& suffix) { return descriptor->name() + suffix + ".java.pb.meta"; } template void MaybePrintGeneratedAnnotation(Context* context, io::Printer* printer, Descriptor* descriptor, bool immutable, - const string& suffix = "") { + const std::string& suffix = "") { if (context->options().annotate_code && IsOwnFile(descriptor, immutable)) { PrintGeneratedAnnotation(printer, '$', AnnotationFileName(descriptor, suffix)); @@ -195,7 +195,7 @@ void MaybePrintGeneratedAnnotation(Context* context, io::Printer* printer, // Get the unqualified name that should be used for a field's field // number constant. -string FieldConstantName(const FieldDescriptor *field); +std::string FieldConstantName(const FieldDescriptor *field); // Returns the type of the FieldDescriptor. // This does nothing interesting for the open source release, but is used for @@ -229,9 +229,9 @@ const char* BoxedPrimitiveTypeName(JavaType type); const char* FieldTypeName(const FieldDescriptor::Type field_type); class ClassNameResolver; -string DefaultValue(const FieldDescriptor* field, bool immutable, +std::string DefaultValue(const FieldDescriptor* field, bool immutable, ClassNameResolver* name_resolver); -inline string ImmutableDefaultValue(const FieldDescriptor* field, +inline std::string ImmutableDefaultValue(const FieldDescriptor* field, ClassNameResolver* name_resolver) { return DefaultValue(field, true, name_resolver); } @@ -267,50 +267,50 @@ inline bool HasGenericServices(const FileDescriptor *file, bool enforce_lite) { // Methods for shared bitfields. // Gets the name of the shared bitfield for the given index. -string GetBitFieldName(int index); +std::string GetBitFieldName(int index); // Gets the name of the shared bitfield for the given bit index. // Effectively, GetBitFieldName(bitIndex / 32) -string GetBitFieldNameForBit(int bitIndex); +std::string GetBitFieldNameForBit(int bitIndex); // Generates the java code for the expression that returns the boolean value // of the bit of the shared bitfields for the given bit index. // Example: "((bitField1_ & 0x04) == 0x04)" -string GenerateGetBit(int bitIndex); +std::string GenerateGetBit(int bitIndex); // Generates the java code for the expression that sets the bit of the shared // bitfields for the given bit index. // Example: "bitField1_ = (bitField1_ | 0x04)" -string GenerateSetBit(int bitIndex); +std::string GenerateSetBit(int bitIndex); // Generates the java code for the expression that clears the bit of the shared // bitfields for the given bit index. // Example: "bitField1_ = (bitField1_ & ~0x04)" -string GenerateClearBit(int bitIndex); +std::string GenerateClearBit(int bitIndex); // Does the same as GenerateGetBit but operates on the bit field on a local // variable. This is used by the builder to copy the value in the builder to // the message. // Example: "((from_bitField1_ & 0x04) == 0x04)" -string GenerateGetBitFromLocal(int bitIndex); +std::string GenerateGetBitFromLocal(int bitIndex); // Does the same as GenerateSetBit but operates on the bit field on a local // variable. This is used by the builder to copy the value in the builder to // the message. // Example: "to_bitField1_ = (to_bitField1_ | 0x04)" -string GenerateSetBitToLocal(int bitIndex); +std::string GenerateSetBitToLocal(int bitIndex); // Does the same as GenerateGetBit but operates on the bit field on a local // variable. This is used by the parsing constructor to record if a repeated // field is mutable. // Example: "((mutable_bitField1_ & 0x04) == 0x04)" -string GenerateGetBitMutableLocal(int bitIndex); +std::string GenerateGetBitMutableLocal(int bitIndex); // Does the same as GenerateSetBit but operates on the bit field on a local // variable. This is used by the parsing constructor to record if a repeated // field is mutable. // Example: "mutable_bitField1_ = (mutable_bitField1_ | 0x04)" -string GenerateSetBitMutableLocal(int bitIndex); +std::string GenerateSetBitMutableLocal(int bitIndex); // Returns whether the JavaType is a reference type. bool IsReferenceType(JavaType type); @@ -398,7 +398,7 @@ inline bool CheckUtf8(const FieldDescriptor* descriptor) { descriptor->file()->options().java_string_check_utf8(); } -inline string GeneratedCodeVersionSuffix() { +inline std::string GeneratedCodeVersionSuffix() { return "V3"; } @@ -410,7 +410,7 @@ inline void WriteIntToUtf16CharSequence(int value, } // Escape a UTF-16 character so it can be embedded in a Java string literal. -void EscapeUtf16ToString(uint16 code, string* output); +void EscapeUtf16ToString(uint16 code, std::string* output); // Only the lowest two bytes of the return value are used. The lowest byte // is the integer value of a j/c/g/protobuf/FieldType enum. For the other diff --git a/src/google/protobuf/compiler/java/java_map_field.h b/src/google/protobuf/compiler/java/java_map_field.h index 90c90eb2d6..b123b0419f 100644 --- a/src/google/protobuf/compiler/java/java_map_field.h +++ b/src/google/protobuf/compiler/java/java_map_field.h @@ -63,11 +63,11 @@ class ImmutableMapFieldGenerator : public ImmutableFieldGenerator { void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; private: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; ClassNameResolver* name_resolver_; void GenerateMapGetters(io::Printer* printer) const; }; diff --git a/src/google/protobuf/compiler/java/java_map_field_lite.h b/src/google/protobuf/compiler/java/java_map_field_lite.h index 710617ae63..df5fe64d50 100644 --- a/src/google/protobuf/compiler/java/java_map_field_lite.h +++ b/src/google/protobuf/compiler/java/java_map_field_lite.h @@ -62,11 +62,11 @@ class ImmutableMapFieldLiteGenerator : public ImmutableFieldLiteGenerator { void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; private: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; Context* context_; ClassNameResolver* name_resolver_; }; diff --git a/src/google/protobuf/compiler/java/java_message_field.h b/src/google/protobuf/compiler/java/java_message_field.h index d70d8270e2..58344e5503 100644 --- a/src/google/protobuf/compiler/java/java_message_field.h +++ b/src/google/protobuf/compiler/java/java_message_field.h @@ -82,11 +82,11 @@ class ImmutableMessageFieldGenerator : public ImmutableFieldGenerator { void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; const int builderBitIndex_; Context* context_; @@ -150,11 +150,11 @@ class RepeatedImmutableMessageFieldGenerator : public ImmutableFieldGenerator { void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; const int builderBitIndex_; Context* context_; diff --git a/src/google/protobuf/compiler/java/java_message_field_lite.h b/src/google/protobuf/compiler/java/java_message_field_lite.h index c9eb30b836..7e78ca4f3f 100644 --- a/src/google/protobuf/compiler/java/java_message_field_lite.h +++ b/src/google/protobuf/compiler/java/java_message_field_lite.h @@ -79,11 +79,11 @@ class ImmutableMessageFieldLiteGenerator : public ImmutableFieldLiteGenerator { void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; Context* context_; ClassNameResolver* name_resolver_; @@ -136,11 +136,11 @@ class RepeatedImmutableMessageFieldLiteGenerator void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; Context* context_; ClassNameResolver* name_resolver_; diff --git a/src/google/protobuf/compiler/java/java_message_lite.cc b/src/google/protobuf/compiler/java/java_message_lite.cc index 85a7453d17..a131e8cca4 100644 --- a/src/google/protobuf/compiler/java/java_message_lite.cc +++ b/src/google/protobuf/compiler/java/java_message_lite.cc @@ -736,14 +736,14 @@ void ImmutableMessageLiteGenerator::GenerateSerializeOneExtensionRange( void ImmutableMessageLiteGenerator::GenerateBuilder(io::Printer* printer) { printer->Print( - "public static Builder newBuilder() {\n" - " return (Builder) DEFAULT_INSTANCE.createBuilder();\n" - "}\n" - "public static Builder newBuilder($classname$ prototype) {\n" - " return (Builder) DEFAULT_INSTANCE.createBuilder(prototype);\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + "public static Builder newBuilder() {\n" + " return (Builder) DEFAULT_INSTANCE.createBuilder();\n" + "}\n" + "public static Builder newBuilder($classname$ prototype) {\n" + " return (Builder) DEFAULT_INSTANCE.createBuilder(prototype);\n" + "}\n" + "\n", + "classname", name_resolver_->GetImmutableClassName(descriptor_)); MessageBuilderLiteGenerator builderGenerator(descriptor_, context_); builderGenerator.Generate(printer); diff --git a/src/google/protobuf/compiler/java/java_name_resolver.h b/src/google/protobuf/compiler/java/java_name_resolver.h index 90684da26d..aa19f0072b 100644 --- a/src/google/protobuf/compiler/java/java_name_resolver.h +++ b/src/google/protobuf/compiler/java/java_name_resolver.h @@ -56,63 +56,63 @@ class ClassNameResolver { ~ClassNameResolver(); // Gets the unqualified outer class name for the file. - string GetFileClassName(const FileDescriptor* file, bool immutable); + std::string GetFileClassName(const FileDescriptor* file, bool immutable); // Gets the unqualified immutable outer class name of a file. - string GetFileImmutableClassName(const FileDescriptor* file); + std::string GetFileImmutableClassName(const FileDescriptor* file); // Gets the unqualified default immutable outer class name of a file // (converted from the proto file's name). - string GetFileDefaultImmutableClassName(const FileDescriptor* file); + std::string GetFileDefaultImmutableClassName(const FileDescriptor* file); // Check whether there is any type defined in the proto file that has // the given class name. bool HasConflictingClassName(const FileDescriptor* file, - const string& classname); + const std::string& classname); // Gets the name of the outer class that holds descriptor information. // Descriptors are shared between immutable messages and mutable messages. // Since both of them are generated optionally, the descriptors need to be // put in another common place. - string GetDescriptorClassName(const FileDescriptor* file); + std::string GetDescriptorClassName(const FileDescriptor* file); // Gets the fully-qualified class name corresponding to the given descriptor. - string GetClassName(const Descriptor* descriptor, bool immutable); - string GetClassName(const EnumDescriptor* descriptor, bool immutable); - string GetClassName(const ServiceDescriptor* descriptor, bool immutable); - string GetClassName(const FileDescriptor* descriptor, bool immutable); + std::string GetClassName(const Descriptor* descriptor, bool immutable); + std::string GetClassName(const EnumDescriptor* descriptor, bool immutable); + std::string GetClassName(const ServiceDescriptor* descriptor, bool immutable); + std::string GetClassName(const FileDescriptor* descriptor, bool immutable); template - string GetImmutableClassName(const DescriptorType* descriptor) { + std::string GetImmutableClassName(const DescriptorType* descriptor) { return GetClassName(descriptor, true); } template - string GetMutableClassName(const DescriptorType* descriptor) { + std::string GetMutableClassName(const DescriptorType* descriptor) { return GetClassName(descriptor, false); } // Gets the fully qualified name of an extension identifier. - string GetExtensionIdentifierName(const FieldDescriptor* descriptor, + std::string GetExtensionIdentifierName(const FieldDescriptor* descriptor, bool immutable); // Gets the fully qualified name for generated classes in Java convention. // Nested classes will be separated using '$' instead of '.' // For example: // com.package.OuterClass$OuterMessage$InnerMessage - string GetJavaImmutableClassName(const Descriptor* descriptor); - string GetJavaImmutableClassName(const EnumDescriptor* descriptor); + std::string GetJavaImmutableClassName(const Descriptor* descriptor); + std::string GetJavaImmutableClassName(const EnumDescriptor* descriptor); private: // Get the full name of a Java class by prepending the Java package name // or outer class name. - string GetClassFullName(const string& name_without_package, + std::string GetClassFullName(const std::string& name_without_package, const FileDescriptor* file, bool immutable, bool multiple_files); // Get the Java Class style full name of a message. - string GetJavaClassFullName( - const string& name_without_package, + std::string GetJavaClassFullName( + const std::string& name_without_package, const FileDescriptor* file, bool immutable); // Caches the result to provide better performance. - std::map file_immutable_outer_class_names_; + std::map file_immutable_outer_class_names_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ClassNameResolver); }; diff --git a/src/google/protobuf/compiler/java/java_names.h b/src/google/protobuf/compiler/java/java_names.h index 39e8c51f8c..a8efbb49bd 100644 --- a/src/google/protobuf/compiler/java/java_names.h +++ b/src/google/protobuf/compiler/java/java_names.h @@ -57,41 +57,41 @@ namespace java { // // Returns: // The fully-qualified Java class name. -string ClassName(const Descriptor* descriptor); +std::string ClassName(const Descriptor* descriptor); // Requires: // descriptor != NULL // // Returns: // The fully-qualified Java class name. -string ClassName(const EnumDescriptor* descriptor); +std::string ClassName(const EnumDescriptor* descriptor); // Requires: // descriptor != NULL // // Returns: // The fully-qualified Java class name. -string ClassName(const FileDescriptor* descriptor); +std::string ClassName(const FileDescriptor* descriptor); // Requires: // descriptor != NULL // // Returns: // The fully-qualified Java class name. -string ClassName(const ServiceDescriptor* descriptor); +std::string ClassName(const ServiceDescriptor* descriptor); // Requires: // descriptor != NULL // // Returns: // Java package name. -string FileJavaPackage(const FileDescriptor* descriptor); +std::string FileJavaPackage(const FileDescriptor* descriptor); // Requires: // descriptor != NULL // Returns: // Captialized camel case name field name. -string CapitalizedFieldName(const FieldDescriptor* descriptor); +std::string CapitalizedFieldName(const FieldDescriptor* descriptor); // Requires: // descriptor != NULL diff --git a/src/google/protobuf/compiler/java/java_primitive_field.h b/src/google/protobuf/compiler/java/java_primitive_field.h index a13680575e..185a268e03 100644 --- a/src/google/protobuf/compiler/java/java_primitive_field.h +++ b/src/google/protobuf/compiler/java/java_primitive_field.h @@ -82,11 +82,11 @@ class ImmutablePrimitiveFieldGenerator : public ImmutableFieldGenerator { void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; const int builderBitIndex_; Context* context_; @@ -143,11 +143,11 @@ class RepeatedImmutablePrimitiveFieldGenerator void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; private: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; const int builderBitIndex_; Context* context_; diff --git a/src/google/protobuf/compiler/java/java_primitive_field_lite.h b/src/google/protobuf/compiler/java/java_primitive_field_lite.h index c12e458c1f..6c05521f06 100644 --- a/src/google/protobuf/compiler/java/java_primitive_field_lite.h +++ b/src/google/protobuf/compiler/java/java_primitive_field_lite.h @@ -82,11 +82,11 @@ class ImmutablePrimitiveFieldLiteGenerator void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; Context* context_; ClassNameResolver* name_resolver_; @@ -143,11 +143,11 @@ class RepeatedImmutablePrimitiveFieldLiteGenerator void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; private: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; Context* context_; ClassNameResolver* name_resolver_; diff --git a/src/google/protobuf/compiler/java/java_service.h b/src/google/protobuf/compiler/java/java_service.h index f34cd798ff..24b0ccaa02 100644 --- a/src/google/protobuf/compiler/java/java_service.h +++ b/src/google/protobuf/compiler/java/java_service.h @@ -125,7 +125,7 @@ class ImmutableServiceGenerator : public ServiceGenerator { const MethodDescriptor* method); // Return the output type of the method. - string GetOutput(const MethodDescriptor* method); + std::string GetOutput(const MethodDescriptor* method); Context* context_; ClassNameResolver* name_resolver_; diff --git a/src/google/protobuf/compiler/java/java_shared_code_generator.h b/src/google/protobuf/compiler/java/java_shared_code_generator.h index 1eb6feafdd..2f09c3a9d9 100644 --- a/src/google/protobuf/compiler/java/java_shared_code_generator.h +++ b/src/google/protobuf/compiler/java/java_shared_code_generator.h @@ -70,8 +70,8 @@ class SharedCodeGenerator { ~SharedCodeGenerator(); void Generate(GeneratorContext* generator_context, - std::vector* file_list, - std::vector* annotation_file_list); + std::vector* file_list, + std::vector* annotation_file_list); void GenerateDescriptors(io::Printer* printer); diff --git a/src/google/protobuf/compiler/java/java_string_field.h b/src/google/protobuf/compiler/java/java_string_field.h index 7f9fa0ed6e..38fb836530 100644 --- a/src/google/protobuf/compiler/java/java_string_field.h +++ b/src/google/protobuf/compiler/java/java_string_field.h @@ -82,11 +82,11 @@ class ImmutableStringFieldGenerator : public ImmutableFieldGenerator { void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; const int builderBitIndex_; Context* context_; @@ -141,11 +141,11 @@ class RepeatedImmutableStringFieldGenerator : public ImmutableFieldGenerator { void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; private: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; const int builderBitIndex_; Context* context_; diff --git a/src/google/protobuf/compiler/java/java_string_field_lite.h b/src/google/protobuf/compiler/java/java_string_field_lite.h index 684d3b005b..89d5c1ae7b 100644 --- a/src/google/protobuf/compiler/java/java_string_field_lite.h +++ b/src/google/protobuf/compiler/java/java_string_field_lite.h @@ -81,11 +81,11 @@ class ImmutableStringFieldLiteGenerator : public ImmutableFieldLiteGenerator { void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; Context* context_; ClassNameResolver* name_resolver_; @@ -137,11 +137,11 @@ class RepeatedImmutableStringFieldLiteGenerator void GenerateHashCode(io::Printer* printer) const; - string GetBoxedType() const; + std::string GetBoxedType() const; private: const FieldDescriptor* descriptor_; - std::map variables_; + std::map variables_; const int messageBitIndex_; Context* context_; ClassNameResolver* name_resolver_; diff --git a/src/google/protobuf/compiler/js/js_generator.h b/src/google/protobuf/compiler/js/js_generator.h index 21e03bc1e4..4567b07a1f 100644 --- a/src/google/protobuf/compiler/js/js_generator.h +++ b/src/google/protobuf/compiler/js/js_generator.h @@ -40,6 +40,8 @@ #include #include +#include + namespace google { namespace protobuf { @@ -56,9 +58,9 @@ namespace js { struct GeneratorOptions { // Output path. - string output_dir; + std::string output_dir; // Namespace prefix. - string namespace_prefix; + std::string namespace_prefix; // Enable binary-format support? bool binary; // What style of imports should be used. @@ -84,11 +86,11 @@ struct GeneratorOptions { annotate_code(false) {} bool ParseFromOptions( - const std::vector< std::pair< string, string > >& options, - string* error); + const std::vector< std::pair< std::string, std::string > >& options, + std::string* error); // Returns the file name extension to use for generated code. - string GetFileNameExtension() const { + std::string GetFileNameExtension() const { return import_style == kImportClosure ? extension : "_pb.js"; } @@ -113,11 +115,11 @@ struct GeneratorOptions { bool testonly; // Create a library with name _lib.js rather than a separate .js file // per type? - string library; + std::string library; // Error if there are two types that would generate the same output file? bool error_on_name_conflict; // The extension to use for output file names. - string extension; + std::string extension; // Create a separate output file for each input file? bool one_output_file_per_input_file; // If true, we should build .meta files that contain annotations for @@ -129,15 +131,15 @@ struct GeneratorOptions { // header. If you create your own protocol compiler binary and you want it to // support JavaScript output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT Generator : public CodeGenerator { +class PROTOC_EXPORT Generator : public CodeGenerator { public: Generator() {} virtual ~Generator() {} virtual bool Generate(const FileDescriptor* file, - const string& parameter, + const std::string& parameter, GeneratorContext* context, - string* error) const { + std::string* error) const { *error = "Unimplemented Generate() method. Call GenerateAll() instead."; return false; } @@ -145,9 +147,9 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { virtual bool HasGenerateAll() const { return true; } virtual bool GenerateAll(const std::vector& files, - const string& parameter, + const std::string& parameter, GeneratorContext* context, - string* error) const; + std::string* error) const; private: void GenerateHeader(const GeneratorOptions& options, @@ -157,28 +159,28 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { void FindProvides(const GeneratorOptions& options, io::Printer* printer, const std::vector& file, - std::set* provided) const; + std::set* provided) const; void FindProvidesForFile(const GeneratorOptions& options, io::Printer* printer, const FileDescriptor* file, - std::set* provided) const; + std::set* provided) const; void FindProvidesForMessage(const GeneratorOptions& options, io::Printer* printer, const Descriptor* desc, - std::set* provided) const; + std::set* provided) const; void FindProvidesForEnum(const GeneratorOptions& options, io::Printer* printer, const EnumDescriptor* enumdesc, - std::set* provided) const; + std::set* provided) const; // For extension fields at file scope. void FindProvidesForFields(const GeneratorOptions& options, io::Printer* printer, const std::vector& fields, - std::set* provided) const; + std::set* provided) const; // Print the goog.provides() found by the methods above. void GenerateProvides(const GeneratorOptions& options, io::Printer* printer, - std::set* provided) const; + std::set* provided) const; // Generate goog.setTestOnly() if indicated. void GenerateTestOnly(const GeneratorOptions& options, @@ -188,34 +190,34 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { void GenerateRequiresForLibrary( const GeneratorOptions& options, io::Printer* printer, const std::vector& files, - std::set* provided) const; + std::set* provided) const; void GenerateRequiresForMessage(const GeneratorOptions& options, io::Printer* printer, const Descriptor* desc, - std::set* provided) const; + std::set* provided) const; // For extension fields at file scope. void GenerateRequiresForExtensions( const GeneratorOptions& options, io::Printer* printer, const std::vector& fields, - std::set* provided) const; + std::set* provided) const; void GenerateRequiresImpl(const GeneratorOptions& options, - io::Printer* printer, std::set* required, - std::set* forwards, - std::set* provided, bool require_jspb, + io::Printer* printer, std::set* required, + std::set* forwards, + std::set* provided, bool require_jspb, bool require_extension, bool require_map) const; void FindRequiresForMessage(const GeneratorOptions& options, const Descriptor* desc, - std::set* required, - std::set* forwards, + std::set* required, + std::set* forwards, bool* have_message) const; void FindRequiresForField(const GeneratorOptions& options, const FieldDescriptor* field, - std::set* required, - std::set* forwards) const; + std::set* required, + std::set* forwards) const; void FindRequiresForExtension(const GeneratorOptions& options, const FieldDescriptor* field, - std::set* required, - std::set* forwards) const; + std::set* required, + std::set* forwards) const; void GenerateFile(const GeneratorOptions& options, io::Printer* printer, @@ -331,4 +333,6 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_JS_GENERATOR_H__ diff --git a/src/google/protobuf/compiler/mock_code_generator.h b/src/google/protobuf/compiler/mock_code_generator.h index 3b59bc4b17..e6370b345e 100644 --- a/src/google/protobuf/compiler/mock_code_generator.h +++ b/src/google/protobuf/compiler/mock_code_generator.h @@ -74,7 +74,7 @@ namespace compiler { // that can later be verified with CheckGeneratedAnnotations. class MockCodeGenerator : public CodeGenerator { public: - MockCodeGenerator(const string& name); + MockCodeGenerator(const std::string& name); virtual ~MockCodeGenerator(); // Expect (via gTest) that a MockCodeGenerator with the given name was called @@ -84,45 +84,45 @@ class MockCodeGenerator : public CodeGenerator { // should have inserted lines into this file. // |parsed_file_list| is a comma-separated list of names of the files // that are being compiled together in this run. - static void ExpectGenerated(const string& name, - const string& parameter, - const string& insertions, - const string& file, - const string& first_message_name, - const string& parsed_file_list, - const string& output_directory); + static void ExpectGenerated(const std::string& name, + const std::string& parameter, + const std::string& insertions, + const std::string& file, + const std::string& first_message_name, + const std::string& parsed_file_list, + const std::string& output_directory); // Checks that the correct text ranges were annotated by the // MockCodeGenerator_Annotate directive. - static void CheckGeneratedAnnotations(const string& name, - const string& file, - const string& output_directory); + static void CheckGeneratedAnnotations(const std::string& name, + const std::string& file, + const std::string& output_directory); // Get the name of the file which would be written by the given generator. - static string GetOutputFileName(const string& generator_name, + static std::string GetOutputFileName(const std::string& generator_name, const FileDescriptor* file); - static string GetOutputFileName(const string& generator_name, - const string& file); + static std::string GetOutputFileName(const std::string& generator_name, + const std::string& file); // implements CodeGenerator ---------------------------------------- virtual bool Generate(const FileDescriptor* file, - const string& parameter, + const std::string& parameter, GeneratorContext* context, - string* error) const; + std::string* error) const; private: - string name_; + std::string name_; - static string GetOutputFileContent(const string& generator_name, - const string& parameter, + static std::string GetOutputFileContent(const std::string& generator_name, + const std::string& parameter, const FileDescriptor* file, GeneratorContext *context); - static string GetOutputFileContent(const string& generator_name, - const string& parameter, - const string& file, - const string& parsed_file_list, - const string& first_message_name); + static std::string GetOutputFileContent(const std::string& generator_name, + const std::string& parameter, + const std::string& file, + const std::string& parsed_file_list, + const std::string& first_message_name); }; } // namespace compiler diff --git a/src/google/protobuf/compiler/objectivec/objectivec_generator.h b/src/google/protobuf/compiler/objectivec/objectivec_generator.h index 3e43f732d8..ac20cfdb47 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_generator.h +++ b/src/google/protobuf/compiler/objectivec/objectivec_generator.h @@ -36,6 +36,8 @@ #include #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -45,7 +47,7 @@ namespace objectivec { // header. If you create your own protocol compiler binary and you want it to // support ObjectiveC output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT ObjectiveCGenerator : public CodeGenerator { +class PROTOC_EXPORT ObjectiveCGenerator : public CodeGenerator { public: ObjectiveCGenerator(); ~ObjectiveCGenerator(); @@ -69,4 +71,7 @@ class LIBPROTOC_EXPORT ObjectiveCGenerator : public CodeGenerator { } // namespace compiler } // namespace protobuf } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_GENERATOR_H__ diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h index 8999aa595e..e7f21f2861 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h +++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h @@ -39,6 +39,8 @@ #include #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -53,66 +55,67 @@ struct Options { }; // Escape C++ trigraphs by escaping question marks to "\?". -string LIBPROTOC_EXPORT EscapeTrigraphs(const string& to_escape); +string PROTOC_EXPORT EscapeTrigraphs(const string& to_escape); // Strips ".proto" or ".protodevel" from the end of a filename. -string LIBPROTOC_EXPORT StripProto(const string& filename); +string PROTOC_EXPORT StripProto(const string& filename); // Remove white space from either end of a StringPiece. -void LIBPROTOC_EXPORT StringPieceTrimWhitespace(StringPiece* input); +void PROTOC_EXPORT StringPieceTrimWhitespace(StringPiece* input); // Returns true if the name requires a ns_returns_not_retained attribute applied // to it. -bool LIBPROTOC_EXPORT IsRetainedName(const string& name); +bool PROTOC_EXPORT IsRetainedName(const string& name); // Returns true if the name starts with "init" and will need to have special // handling under ARC. -bool LIBPROTOC_EXPORT IsInitName(const string& name); +bool PROTOC_EXPORT IsInitName(const string& name); // Gets the objc_class_prefix. -string LIBPROTOC_EXPORT FileClassPrefix(const FileDescriptor* file); +string PROTOC_EXPORT FileClassPrefix(const FileDescriptor* file); // Gets the path of the file we're going to generate (sans the .pb.h // extension). The path will be dependent on the objectivec package // declared in the proto package. -string LIBPROTOC_EXPORT FilePath(const FileDescriptor* file); +string PROTOC_EXPORT FilePath(const FileDescriptor* file); // Just like FilePath(), but without the directory part. -string LIBPROTOC_EXPORT FilePathBasename(const FileDescriptor* file); +string PROTOC_EXPORT FilePathBasename(const FileDescriptor* file); // Gets the name of the root class we'll generate in the file. This class // is not meant for external consumption, but instead contains helpers that // the rest of the classes need -string LIBPROTOC_EXPORT FileClassName(const FileDescriptor* file); +string PROTOC_EXPORT FileClassName(const FileDescriptor* file); // These return the fully-qualified class name corresponding to the given // descriptor. -string LIBPROTOC_EXPORT ClassName(const Descriptor* descriptor); -string LIBPROTOC_EXPORT ClassName(const Descriptor* descriptor, string* out_suffix_added); -string LIBPROTOC_EXPORT EnumName(const EnumDescriptor* descriptor); +string PROTOC_EXPORT ClassName(const Descriptor* descriptor); +string PROTOC_EXPORT ClassName(const Descriptor* descriptor, + string* out_suffix_added); +string PROTOC_EXPORT EnumName(const EnumDescriptor* descriptor); // Returns the fully-qualified name of the enum value corresponding to the // the descriptor. -string LIBPROTOC_EXPORT EnumValueName(const EnumValueDescriptor* descriptor); +string PROTOC_EXPORT EnumValueName(const EnumValueDescriptor* descriptor); // Returns the name of the enum value corresponding to the descriptor. -string LIBPROTOC_EXPORT EnumValueShortName(const EnumValueDescriptor* descriptor); +string PROTOC_EXPORT EnumValueShortName(const EnumValueDescriptor* descriptor); // Reverse what an enum does. -string LIBPROTOC_EXPORT UnCamelCaseEnumShortName(const string& name); +string PROTOC_EXPORT UnCamelCaseEnumShortName(const string& name); // Returns the name to use for the extension (used as the method off the file's // Root class). -string LIBPROTOC_EXPORT ExtensionMethodName(const FieldDescriptor* descriptor); +string PROTOC_EXPORT ExtensionMethodName(const FieldDescriptor* descriptor); // Returns the transformed field name. -string LIBPROTOC_EXPORT FieldName(const FieldDescriptor* field); -string LIBPROTOC_EXPORT FieldNameCapitalized(const FieldDescriptor* field); +string PROTOC_EXPORT FieldName(const FieldDescriptor* field); +string PROTOC_EXPORT FieldNameCapitalized(const FieldDescriptor* field); // Returns the transformed oneof name. -string LIBPROTOC_EXPORT OneofEnumName(const OneofDescriptor* descriptor); -string LIBPROTOC_EXPORT OneofName(const OneofDescriptor* descriptor); -string LIBPROTOC_EXPORT OneofNameCapitalized(const OneofDescriptor* descriptor); +string PROTOC_EXPORT OneofEnumName(const OneofDescriptor* descriptor); +string PROTOC_EXPORT OneofName(const OneofDescriptor* descriptor); +string PROTOC_EXPORT OneofNameCapitalized(const OneofDescriptor* descriptor); inline bool HasFieldPresence(const FileDescriptor* file) { return file->syntax() != FileDescriptor::SYNTAX_PROTO3; @@ -127,7 +130,8 @@ inline bool IsMapEntryMessage(const Descriptor* descriptor) { } // Reverse of the above. -string LIBPROTOC_EXPORT UnCamelCaseFieldName(const string& name, const FieldDescriptor* field); +string PROTOC_EXPORT UnCamelCaseFieldName(const string& name, + const FieldDescriptor* field); enum ObjectiveCType { OBJECTIVECTYPE_INT32, @@ -175,48 +179,52 @@ string GetOptionalDeprecatedAttribute( } } -string LIBPROTOC_EXPORT GetCapitalizedType(const FieldDescriptor* field); +string PROTOC_EXPORT GetCapitalizedType(const FieldDescriptor* field); -ObjectiveCType LIBPROTOC_EXPORT GetObjectiveCType(FieldDescriptor::Type field_type); +ObjectiveCType PROTOC_EXPORT +GetObjectiveCType(FieldDescriptor::Type field_type); inline ObjectiveCType GetObjectiveCType(const FieldDescriptor* field) { return GetObjectiveCType(field->type()); } -bool LIBPROTOC_EXPORT IsPrimitiveType(const FieldDescriptor* field); -bool LIBPROTOC_EXPORT IsReferenceType(const FieldDescriptor* field); +bool PROTOC_EXPORT IsPrimitiveType(const FieldDescriptor* field); +bool PROTOC_EXPORT IsReferenceType(const FieldDescriptor* field); -string LIBPROTOC_EXPORT GPBGenericValueFieldName(const FieldDescriptor* field); -string LIBPROTOC_EXPORT DefaultValue(const FieldDescriptor* field); -bool LIBPROTOC_EXPORT HasNonZeroDefaultValue(const FieldDescriptor* field); +string PROTOC_EXPORT GPBGenericValueFieldName(const FieldDescriptor* field); +string PROTOC_EXPORT DefaultValue(const FieldDescriptor* field); +bool PROTOC_EXPORT HasNonZeroDefaultValue(const FieldDescriptor* field); -string LIBPROTOC_EXPORT BuildFlagsString(const FlagType type, const std::vector& strings); +string PROTOC_EXPORT BuildFlagsString(const FlagType type, + const std::vector& strings); // Builds HeaderDoc/appledoc style comments out of the comments in the .proto // file. -string LIBPROTOC_EXPORT BuildCommentsString(const SourceLocation& location, - bool prefer_single_line); +string PROTOC_EXPORT BuildCommentsString(const SourceLocation& location, + bool prefer_single_line); // The name the commonly used by the library when built as a framework. // This lines up to the name used in the CocoaPod. -extern LIBPROTOC_EXPORT const char* const ProtobufLibraryFrameworkName; +extern PROTOC_EXPORT const char* const ProtobufLibraryFrameworkName; // Returns the CPP symbol name to use as the gate for framework style imports // for the given framework name to use. -string LIBPROTOC_EXPORT ProtobufFrameworkImportSymbol(const string& framework_name); +string PROTOC_EXPORT +ProtobufFrameworkImportSymbol(const string& framework_name); // Checks if the file is one of the proto's bundled with the library. -bool LIBPROTOC_EXPORT IsProtobufLibraryBundledProtoFile(const FileDescriptor* file); +bool PROTOC_EXPORT +IsProtobufLibraryBundledProtoFile(const FileDescriptor* file); // Checks the prefix for the given files and outputs any warnings as needed. If // there are flat out errors, then out_error is filled in with the first error // and the result is false. -bool LIBPROTOC_EXPORT ValidateObjCClassPrefixes(const std::vector& files, - const Options& generation_options, - string* out_error); +bool PROTOC_EXPORT +ValidateObjCClassPrefixes(const std::vector& files, + const Options& generation_options, string* out_error); // Generate decode data needed for ObjC's GPBDecodeTextFormatName() to transform // the input into the expected output. -class LIBPROTOC_EXPORT TextFormatDecodeData { +class PROTOC_EXPORT TextFormatDecodeData { public: TextFormatDecodeData(); ~TextFormatDecodeData(); @@ -237,20 +245,20 @@ class LIBPROTOC_EXPORT TextFormatDecodeData { }; // Helper for parsing simple files. -class LIBPROTOC_EXPORT LineConsumer { +class PROTOC_EXPORT LineConsumer { public: LineConsumer(); virtual ~LineConsumer(); virtual bool ConsumeLine(const StringPiece& line, string* out_error) = 0; }; -bool LIBPROTOC_EXPORT ParseSimpleFile( - const string& path, LineConsumer* line_consumer, string* out_error); - +bool PROTOC_EXPORT ParseSimpleFile(const string& path, + LineConsumer* line_consumer, + string* out_error); // Helper class for parsing framework import mappings and generating // import statements. -class LIBPROTOC_EXPORT ImportWriter { +class PROTOC_EXPORT ImportWriter { public: ImportWriter(const string& generate_for_named_framework, const string& named_framework_to_proto_path_mappings_path, @@ -290,4 +298,7 @@ class LIBPROTOC_EXPORT ImportWriter { } // namespace compiler } // namespace protobuf } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_HELPERS_H__ diff --git a/src/google/protobuf/compiler/parser.h b/src/google/protobuf/compiler/parser.h index b55750ca45..9ae6c6da6d 100644 --- a/src/google/protobuf/compiler/parser.h +++ b/src/google/protobuf/compiler/parser.h @@ -45,6 +45,8 @@ #include #include +#include + namespace google { namespace protobuf { @@ -63,7 +65,7 @@ class SourceLocationTable; // to a FileDescriptorProto. It does not resolve import directives or perform // many other kinds of validation needed to construct a complete // FileDescriptor. -class LIBPROTOBUF_EXPORT Parser { +class PROTOBUF_EXPORT Parser { public: Parser(); ~Parser(); @@ -93,7 +95,7 @@ class LIBPROTOBUF_EXPORT Parser { // Returns the identifier used in the "syntax = " declaration, if one was // seen during the last call to Parse(), or the empty string otherwise. - const string& GetSyntaxIdentifier() { return syntax_identifier_; } + const std::string& GetSyntaxIdentifier() { return syntax_identifier_; } // If set true, input files will be required to begin with a syntax // identifier. Otherwise, files may omit this. If a syntax identifier @@ -163,7 +165,7 @@ class LIBPROTOBUF_EXPORT Parser { // where "text" is the expected token text. bool Consume(const char* text); // Consume a token of type IDENTIFIER and store its text in "output". - bool ConsumeIdentifier(string* output, const char* error); + bool ConsumeIdentifier(std::string* output, const char* error); // Consume an integer and store its value in "output". bool ConsumeInteger(int* output, const char* error); // Consume a signed integer and store its value in "output". @@ -175,7 +177,7 @@ class LIBPROTOBUF_EXPORT Parser { // tokens of either INTEGER or FLOAT type. bool ConsumeNumber(double* output, const char* error); // Consume a string literal and store its (unescaped) value in "output". - bool ConsumeString(string* output, const char* error); + bool ConsumeString(std::string* output, const char* error); // Consume a token representing the end of the statement. Comments between // this token and the next will be harvested for documentation. The given @@ -198,18 +200,18 @@ class LIBPROTOBUF_EXPORT Parser { // Error logging helpers // Invokes error_collector_->AddError(), if error_collector_ is not NULL. - void AddError(int line, int column, const string& error); + void AddError(int line, int column, const std::string& error); // Invokes error_collector_->AddError() with the line and column number // of the current token. - void AddError(const string& error); + void AddError(const std::string& error); // Records a location in the SourceCodeInfo.location table (see // descriptor.proto). We use RAII to ensure that the start and end locations // are recorded -- the constructor records the start location and the // destructor records the end location. Since the parser is // recursive-descent, this works out beautifully. - class LIBPROTOBUF_EXPORT LocationRecorder { + class PROTOBUF_EXPORT LocationRecorder { public: // Construct the file's "root" location. LocationRecorder(Parser* parser); @@ -264,8 +266,8 @@ class LIBPROTOBUF_EXPORT Parser { // // TODO(kenton): See comment on TryConsumeEndOfDeclaration(), above, for // why this is const. - void AttachComments(string* leading, string* trailing, - std::vector* detached_comments) const; + void AttachComments(std::string* leading, std::string* trailing, + std::vector* detached_comments) const; private: // Indexes of parent and current location in the parent @@ -313,7 +315,7 @@ class LIBPROTOBUF_EXPORT Parser { bool ParsePackage(FileDescriptorProto* file, const LocationRecorder& root_location, const FileDescriptorProto* containing_file); - bool ParseImport(RepeatedPtrField* dependency, + bool ParseImport(RepeatedPtrField* dependency, RepeatedField* public_dependency, RepeatedField* weak_dependency, const LocationRecorder& root_location, @@ -437,10 +439,10 @@ class LIBPROTOBUF_EXPORT Parser { // Parse a type name and fill in "type" (if it is a primitive) or // "type_name" (if it is not) with the type parsed. bool ParseType(FieldDescriptorProto::Type* type, - string* type_name); + std::string* type_name); // Parse a user-defined type and fill in "type_name" with the name. // If a primitive type is named, it is treated as an error. - bool ParseUserDefinedType(string* type_name); + bool ParseUserDefinedType(std::string* type_name); // Parses field options, i.e. the stuff in square brackets at the end // of a field definition. Also parses default value. @@ -489,7 +491,7 @@ class LIBPROTOBUF_EXPORT Parser { // REQUIRES: LookingAt("{") // When finished successfully, we are looking at the first token past // the ending brace. - bool ParseUninterpretedBlock(string* value); + bool ParseUninterpretedBlock(std::string* value); struct MapField { // Whether the field is a map field. @@ -498,8 +500,8 @@ class LIBPROTOBUF_EXPORT Parser { FieldDescriptorProto::Type key_type; FieldDescriptorProto::Type value_type; // Or the type names string if the types are customized types. - string key_type_name; - string value_type_name; + std::string key_type_name; + std::string value_type_name; MapField() : is_map_field(false) {} }; @@ -524,18 +526,18 @@ class LIBPROTOBUF_EXPORT Parser { bool had_errors_; bool require_syntax_identifier_; bool stop_after_syntax_identifier_; - string syntax_identifier_; + std::string syntax_identifier_; // Leading doc comments for the next declaration. These are not complete // yet; use ConsumeEndOfDeclaration() to get the complete comments. - string upcoming_doc_comments_; + std::string upcoming_doc_comments_; // Detached comments are not connected to any syntax entities. Elements in // this vector are paragraphs of comments separated by empty lines. The // detached comments will be put into the leading_detached_comments field for // the next element (See SourceCodeInfo.Location in descriptor.proto), when // ConsumeEndOfDeclaration() is called. - std::vector upcoming_detached_comments_; + std::vector upcoming_detached_comments_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Parser); }; @@ -548,7 +550,7 @@ class LIBPROTOBUF_EXPORT Parser { // far more complete information about source locations. However, as of this // writing you still need to use SourceLocationTable when integrating with // DescriptorPool. -class LIBPROTOBUF_EXPORT SourceLocationTable { +class PROTOBUF_EXPORT SourceLocationTable { public: SourceLocationTable(); ~SourceLocationTable(); @@ -581,4 +583,6 @@ class LIBPROTOBUF_EXPORT SourceLocationTable { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_PARSER_H__ diff --git a/src/google/protobuf/compiler/php/php_generator.h b/src/google/protobuf/compiler/php/php_generator.h index b851d9b4a2..283767ec4c 100644 --- a/src/google/protobuf/compiler/php/php_generator.h +++ b/src/google/protobuf/compiler/php/php_generator.h @@ -36,12 +36,14 @@ #include +#include + namespace google { namespace protobuf { namespace compiler { namespace php { -class LIBPROTOC_EXPORT Generator +class PROTOC_EXPORT Generator : public google::protobuf::compiler::CodeGenerator { virtual bool Generate( const FileDescriptor* file, @@ -53,11 +55,11 @@ class LIBPROTOC_EXPORT Generator // To skip reserved keywords in php, some generated classname are prefixed. // Other code generators may need following API to figure out the actual // classname. -LIBPROTOC_EXPORT std::string GeneratedClassName( +PROTOC_EXPORT std::string GeneratedClassName( const google::protobuf::Descriptor* desc); -LIBPROTOC_EXPORT std::string GeneratedClassName( +PROTOC_EXPORT std::string GeneratedClassName( const google::protobuf::EnumDescriptor* desc); -LIBPROTOC_EXPORT std::string GeneratedClassName( +PROTOC_EXPORT std::string GeneratedClassName( const google::protobuf::ServiceDescriptor* desc); } // namespace php @@ -65,4 +67,6 @@ LIBPROTOC_EXPORT std::string GeneratedClassName( } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_PHP_GENERATOR_H__ diff --git a/src/google/protobuf/compiler/plugin.h b/src/google/protobuf/compiler/plugin.h index c664917320..48db3c1cc9 100644 --- a/src/google/protobuf/compiler/plugin.h +++ b/src/google/protobuf/compiler/plugin.h @@ -64,7 +64,8 @@ #include -#include +#include + namespace google { namespace protobuf { namespace compiler { @@ -74,17 +75,20 @@ class CodeGeneratorRequest; class CodeGeneratorResponse; // Implements main() for a protoc plugin exposing the given code generator. -LIBPROTOC_EXPORT int PluginMain(int argc, char* argv[], const CodeGenerator* generator); +PROTOC_EXPORT int PluginMain(int argc, char* argv[], + const CodeGenerator* generator); // Generates code using the given code generator. Returns true if the code // generation is successful. If the code geneartion fails, error_msg may be // populated to describe the failure cause. bool GenerateCode(const CodeGeneratorRequest& request, const CodeGenerator& generator, CodeGeneratorResponse* response, - string* error_msg); + std::string* error_msg); } // namespace compiler } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_PLUGIN_H__ diff --git a/src/google/protobuf/compiler/plugin.pb.cc b/src/google/protobuf/compiler/plugin.pb.cc index 7569f27ffe..234be0ddb6 100644 --- a/src/google/protobuf/compiler/plugin.pb.cc +++ b/src/google/protobuf/compiler/plugin.pb.cc @@ -13,10 +13,6 @@ #include #include #include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif // @@protoc_insertion_point(includes) #include @@ -56,7 +52,7 @@ static void InitDefaultsVersion_google_2fprotobuf_2fcompiler_2fplugin_2eproto() ::google::protobuf::compiler::Version::InitAsDefaultInstance(); } -LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto = +PROTOC_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsVersion_google_2fprotobuf_2fcompiler_2fplugin_2eproto}, {}}; static void InitDefaultsCodeGeneratorRequest_google_2fprotobuf_2fcompiler_2fplugin_2eproto() { @@ -70,7 +66,7 @@ static void InitDefaultsCodeGeneratorRequest_google_2fprotobuf_2fcompiler_2fplug ::google::protobuf::compiler::CodeGeneratorRequest::InitAsDefaultInstance(); } -LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<2> scc_info_CodeGeneratorRequest_google_2fprotobuf_2fcompiler_2fplugin_2eproto = +PROTOC_EXPORT ::google::protobuf::internal::SCCInfo<2> scc_info_CodeGeneratorRequest_google_2fprotobuf_2fcompiler_2fplugin_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsCodeGeneratorRequest_google_2fprotobuf_2fcompiler_2fplugin_2eproto}, { &scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, &scc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base,}}; @@ -86,7 +82,7 @@ static void InitDefaultsCodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_ ::google::protobuf::compiler::CodeGeneratorResponse_File::InitAsDefaultInstance(); } -LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_CodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto = +PROTOC_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_CodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto}, {}}; static void InitDefaultsCodeGeneratorResponse_google_2fprotobuf_2fcompiler_2fplugin_2eproto() { @@ -100,7 +96,7 @@ static void InitDefaultsCodeGeneratorResponse_google_2fprotobuf_2fcompiler_2fplu ::google::protobuf::compiler::CodeGeneratorResponse::InitAsDefaultInstance(); } -LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_CodeGeneratorResponse_google_2fprotobuf_2fcompiler_2fplugin_2eproto = +PROTOC_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_CodeGeneratorResponse_google_2fprotobuf_2fcompiler_2fplugin_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsCodeGeneratorResponse_google_2fprotobuf_2fcompiler_2fplugin_2eproto}, { &scc_info_CodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base,}}; @@ -115,55 +111,55 @@ void InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto() { constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto = nullptr; constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto = nullptr; -const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, _internal_metadata_), +const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::Version, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::Version, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, major_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, minor_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, patch_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, suffix_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::Version, major_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::Version, minor_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::Version, patch_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::Version, suffix_), 1, 2, 3, 0, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, file_to_generate_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, parameter_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, proto_file_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, compiler_version_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, file_to_generate_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, parameter_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, proto_file_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, compiler_version_), ~0u, 0, ~0u, 1, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, insertion_point_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, content_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, name_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, insertion_point_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, content_), 0, 1, 2, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, error_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, file_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, error_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, file_), 0, ~0u, }; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, 9, sizeof(::google::protobuf::compiler::Version)}, { 13, 22, sizeof(::google::protobuf::compiler::CodeGeneratorRequest)}, { 26, 34, sizeof(::google::protobuf::compiler::CodeGeneratorResponse_File)}, @@ -323,15 +319,14 @@ const char* Version::_InternalParse(const char* begin, const char* end, void* ob while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional int32 major = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->set_major(value); break; @@ -341,7 +336,7 @@ const char* Version::_InternalParse(const char* begin, const char* end, void* ob if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->set_minor(value); break; @@ -351,7 +346,7 @@ const char* Version::_InternalParse(const char* begin, const char* end, void* ob if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->set_patch(value); break; @@ -360,7 +355,7 @@ const char* Version::_InternalParse(const char* begin, const char* end, void* ob case 4: { if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.compiler.Version.suffix"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_suffix(); @@ -368,14 +363,15 @@ const char* Version::_InternalParse(const char* begin, const char* end, void* ob object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -386,8 +382,6 @@ const char* Version::_InternalParse(const char* begin, const char* end, void* ob } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -399,7 +393,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Version::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.compiler.Version) for (;;) { @@ -806,15 +800,14 @@ const char* CodeGeneratorRequest::_InternalParse(const char* begin, const char* while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // repeated string file_to_generate = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.compiler.CodeGeneratorRequest.file_to_generate"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->add_file_to_generate(); @@ -822,17 +815,17 @@ const char* CodeGeneratorRequest::_InternalParse(const char* begin, const char* object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 10 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1)); break; } // optional string parameter = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.compiler.CodeGeneratorRequest.parameter"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_parameter(); @@ -840,20 +833,22 @@ const char* CodeGeneratorRequest::_InternalParse(const char* begin, const char* object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional .google.protobuf.compiler.Version compiler_version = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::compiler::Version::_InternalParse; object = msg->mutable_compiler_version(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; break; } @@ -862,21 +857,24 @@ const char* CodeGeneratorRequest::_InternalParse(const char* begin, const char* if (static_cast<::google::protobuf::uint8>(tag) != 122) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::FileDescriptorProto::_InternalParse; object = msg->add_proto_file(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 122 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 122 && (ptr += 1)); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -887,8 +885,6 @@ const char* CodeGeneratorRequest::_InternalParse(const char* begin, const char* } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -900,7 +896,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CodeGeneratorRequest::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorRequest) for (;;) { @@ -1322,14 +1318,13 @@ const char* CodeGeneratorResponse_File::_InternalParse(const char* begin, const while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional string name = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.compiler.CodeGeneratorResponse.File.name"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_name(); @@ -1337,15 +1332,15 @@ const char* CodeGeneratorResponse_File::_InternalParse(const char* begin, const object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional string insertion_point = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_insertion_point(); @@ -1353,15 +1348,15 @@ const char* CodeGeneratorResponse_File::_InternalParse(const char* begin, const object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional string content = 15; case 15: { if (static_cast<::google::protobuf::uint8>(tag) != 122) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.compiler.CodeGeneratorResponse.File.content"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_content(); @@ -1369,14 +1364,15 @@ const char* CodeGeneratorResponse_File::_InternalParse(const char* begin, const object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -1387,8 +1383,6 @@ const char* CodeGeneratorResponse_File::_InternalParse(const char* begin, const } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -1400,7 +1394,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CodeGeneratorResponse_File::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorResponse.File) for (;;) { @@ -1772,14 +1766,13 @@ const char* CodeGeneratorResponse::_InternalParse(const char* begin, const char* while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional string error = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.compiler.CodeGeneratorResponse.error"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_error(); @@ -1787,8 +1780,8 @@ const char* CodeGeneratorResponse::_InternalParse(const char* begin, const char* object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15; @@ -1796,21 +1789,24 @@ const char* CodeGeneratorResponse::_InternalParse(const char* begin, const char* if (static_cast<::google::protobuf::uint8>(tag) != 122) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::compiler::CodeGeneratorResponse_File::_InternalParse; object = msg->add_file(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 122 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 122 && (ptr += 1)); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -1821,8 +1817,6 @@ const char* CodeGeneratorResponse::_InternalParse(const char* begin, const char* } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -1834,7 +1828,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CodeGeneratorResponse::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorResponse) for (;;) { @@ -2066,19 +2060,20 @@ void CodeGeneratorResponse::InternalSwap(CodeGeneratorResponse* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::Version* Arena::CreateMaybeMessage< ::google::protobuf::compiler::Version >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::compiler::Version* Arena::CreateMaybeMessage< ::google::protobuf::compiler::Version >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::compiler::Version >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorRequest >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorRequest >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorRequest >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse_File >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse_File >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorResponse_File >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorResponse >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope) +#include diff --git a/src/google/protobuf/compiler/plugin.pb.h b/src/google/protobuf/compiler/plugin.pb.h index 4b7527e5c9..187587ca36 100644 --- a/src/google/protobuf/compiler/plugin.pb.h +++ b/src/google/protobuf/compiler/plugin.pb.h @@ -7,18 +7,19 @@ #include #include -#include -#if GOOGLE_PROTOBUF_VERSION < 3006000 +#include +#if PROTOBUF_VERSION < 3006001 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3006001 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include @@ -33,7 +34,7 @@ #include // @@protoc_insertion_point(includes) #include -#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fcompiler_2fplugin_2eproto LIBPROTOC_EXPORT +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fcompiler_2fplugin_2eproto PROTOC_EXPORT #ifdef major #undef major #endif @@ -42,38 +43,38 @@ #endif // Internal implementation detail -- do not use these members. -struct LIBPROTOC_EXPORT TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto { +struct PROTOC_EXPORT TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto { static const ::google::protobuf::internal::ParseTableField entries[] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::AuxillaryParseTableField aux[] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::ParseTable schema[4] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::FieldMetadata field_metadata[]; static const ::google::protobuf::internal::SerializationTable serialization_table[]; static const ::google::protobuf::uint32 offsets[]; }; -void LIBPROTOC_EXPORT AddDescriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto(); +void PROTOC_EXPORT AddDescriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto(); namespace google { namespace protobuf { namespace compiler { class CodeGeneratorRequest; class CodeGeneratorRequestDefaultTypeInternal; -LIBPROTOC_EXPORT extern CodeGeneratorRequestDefaultTypeInternal _CodeGeneratorRequest_default_instance_; +PROTOC_EXPORT extern CodeGeneratorRequestDefaultTypeInternal _CodeGeneratorRequest_default_instance_; class CodeGeneratorResponse; class CodeGeneratorResponseDefaultTypeInternal; -LIBPROTOC_EXPORT extern CodeGeneratorResponseDefaultTypeInternal _CodeGeneratorResponse_default_instance_; +PROTOC_EXPORT extern CodeGeneratorResponseDefaultTypeInternal _CodeGeneratorResponse_default_instance_; class CodeGeneratorResponse_File; class CodeGeneratorResponse_FileDefaultTypeInternal; -LIBPROTOC_EXPORT extern CodeGeneratorResponse_FileDefaultTypeInternal _CodeGeneratorResponse_File_default_instance_; +PROTOC_EXPORT extern CodeGeneratorResponse_FileDefaultTypeInternal _CodeGeneratorResponse_File_default_instance_; class Version; class VersionDefaultTypeInternal; -LIBPROTOC_EXPORT extern VersionDefaultTypeInternal _Version_default_instance_; +PROTOC_EXPORT extern VersionDefaultTypeInternal _Version_default_instance_; } // namespace compiler -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorRequest>(Arena*); -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorResponse>(Arena*); -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorResponse_File>(Arena*); -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::Version* Arena::CreateMaybeMessage<::google::protobuf::compiler::Version>(Arena*); +template<> PROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorRequest>(Arena*); +template<> PROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorResponse>(Arena*); +template<> PROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorResponse_File>(Arena*); +template<> PROTOC_EXPORT ::google::protobuf::compiler::Version* Arena::CreateMaybeMessage<::google::protobuf::compiler::Version>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -82,7 +83,7 @@ namespace compiler { // =================================================================== -class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.Version) */ { +class PROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.Version) */ { public: Version(); virtual ~Version(); @@ -234,7 +235,7 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_ }; // ------------------------------------------------------------------- -class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorRequest) */ { +class PROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorRequest) */ { public: CodeGeneratorRequest(); virtual ~CodeGeneratorRequest(); @@ -408,7 +409,7 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message }; // ------------------------------------------------------------------- -class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse.File) */ { +class PROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse.File) */ { public: CodeGeneratorResponse_File(); virtual ~CodeGeneratorResponse_File(); @@ -568,7 +569,7 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M }; // ------------------------------------------------------------------- -class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse) */ { +class PROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse) */ { public: CodeGeneratorResponse(); virtual ~CodeGeneratorResponse(); diff --git a/src/google/protobuf/compiler/python/python_generator.h b/src/google/protobuf/compiler/python/python_generator.h index 99a7383280..c21c36da38 100644 --- a/src/google/protobuf/compiler/python/python_generator.h +++ b/src/google/protobuf/compiler/python/python_generator.h @@ -39,6 +39,8 @@ #include +#include + namespace google { namespace protobuf { @@ -58,16 +60,16 @@ namespace python { // If you create your own protocol compiler binary and you want it to support // Python output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT Generator : public CodeGenerator { +class PROTOC_EXPORT Generator : public CodeGenerator { public: Generator(); virtual ~Generator(); // CodeGenerator methods. virtual bool Generate(const FileDescriptor* file, - const string& parameter, + const std::string& parameter, GeneratorContext* generator_context, - string* error) const; + std::string* error) const; private: void PrintImports() const; @@ -84,7 +86,7 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { void PrintFieldDescriptorsInDescriptor( const Descriptor& message_descriptor, bool is_extension, - const string& list_variable_name, + const std::string& list_variable_name, int (Descriptor::*CountFn)() const, const FieldDescriptor* (Descriptor::*GetterFn)(int) const) const; void PrintFieldsInDescriptor(const Descriptor& message_descriptor) const; @@ -94,11 +96,11 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { void PrintNestedDescriptors(const Descriptor& containing_descriptor) const; void PrintMessages() const; - void PrintMessage(const Descriptor& message_descriptor, const string& prefix, - std::vector* to_register) const; + void PrintMessage(const Descriptor& message_descriptor, const std::string& prefix, + std::vector* to_register) const; void PrintNestedMessages(const Descriptor& containing_descriptor, - const string& prefix, - std::vector* to_register) const; + const std::string& prefix, + std::vector* to_register) const; void FixForeignFieldsInDescriptors() const; void FixForeignFieldsInDescriptor( @@ -106,14 +108,14 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { const Descriptor* containing_descriptor) const; void FixForeignFieldsInField(const Descriptor* containing_type, const FieldDescriptor& field, - const string& python_dict_name) const; + const std::string& python_dict_name) const; void AddMessageToFileDescriptor(const Descriptor& descriptor) const; void AddEnumToFileDescriptor(const EnumDescriptor& descriptor) const; void AddExtensionToFileDescriptor(const FieldDescriptor& descriptor) const; void AddServiceToFileDescriptor(const ServiceDescriptor& descriptor) const; - string FieldReferencingExpression(const Descriptor* containing_type, + std::string FieldReferencingExpression(const Descriptor* containing_type, const FieldDescriptor& field, - const string& python_dict_name) const; + const std::string& python_dict_name) const; template void FixContainingTypeInDescriptor( const DescriptorT& descriptor, @@ -133,13 +135,13 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { const ServiceDescriptor& descriptor) const; void PrintEnumValueDescriptor(const EnumValueDescriptor& descriptor) const; - string OptionsValue(const string& serialized_options) const; + std::string OptionsValue(const std::string& serialized_options) const; bool GeneratingDescriptorProto() const; template - string ModuleLevelDescriptorName(const DescriptorT& descriptor) const; - string ModuleLevelMessageName(const Descriptor& descriptor) const; - string ModuleLevelServiceDescriptorName( + std::string ModuleLevelDescriptorName(const DescriptorT& descriptor) const; + std::string ModuleLevelMessageName(const Descriptor& descriptor) const; + std::string ModuleLevelServiceDescriptorName( const ServiceDescriptor& descriptor) const; template @@ -153,13 +155,13 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { void FixOptionsForMessage(const Descriptor& descriptor) const; void CopyPublicDependenciesAliases( - const string& copy_from, const FileDescriptor* file) const; + const std::string& copy_from, const FileDescriptor* file) const; // Very coarse-grained lock to ensure that Generate() is reentrant. // Guards file_, printer_ and file_descriptor_serialized_. mutable Mutex mutex_; mutable const FileDescriptor* file_; // Set in Generate(). Under mutex_. - mutable string file_descriptor_serialized_; + mutable std::string file_descriptor_serialized_; mutable io::Printer* printer_; // Set in Generate(). Under mutex_. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Generator); @@ -170,4 +172,6 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_PYTHON_GENERATOR_H__ diff --git a/src/google/protobuf/compiler/ruby/ruby_generator.h b/src/google/protobuf/compiler/ruby/ruby_generator.h index 8c1dfa2671..521697fb1e 100644 --- a/src/google/protobuf/compiler/ruby/ruby_generator.h +++ b/src/google/protobuf/compiler/ruby/ruby_generator.h @@ -37,6 +37,8 @@ #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -46,7 +48,7 @@ namespace ruby { // If you create your own protocol compiler binary and you want it to support // Ruby output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT Generator +class PROTOC_EXPORT Generator : public google::protobuf::compiler::CodeGenerator { virtual bool Generate( const FileDescriptor* file, @@ -60,5 +62,7 @@ class LIBPROTOC_EXPORT Generator } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_RUBY_GENERATOR_H__ diff --git a/src/google/protobuf/compiler/scc.h b/src/google/protobuf/compiler/scc.h index 69a47f1bc1..c8cf77d655 100644 --- a/src/google/protobuf/compiler/scc.h +++ b/src/google/protobuf/compiler/scc.h @@ -35,6 +35,8 @@ #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -52,7 +54,7 @@ struct SCC { // This class is used for analyzing the SCC for each message, to ensure linear // instead of quadratic performance, if we do this per message we would get // O(V*(V+E)). -class LIBPROTOC_EXPORT SCCAnalyzer { +class PROTOC_EXPORT SCCAnalyzer { public: explicit SCCAnalyzer() : index_(0) {} @@ -92,4 +94,6 @@ class LIBPROTOC_EXPORT SCCAnalyzer { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_SCC_H__ diff --git a/src/google/protobuf/compiler/subprocess.h b/src/google/protobuf/compiler/subprocess.h index dad5daba20..977abff7b5 100644 --- a/src/google/protobuf/compiler/subprocess.h +++ b/src/google/protobuf/compiler/subprocess.h @@ -44,6 +44,8 @@ #include +#include + namespace google { namespace protobuf { @@ -52,7 +54,7 @@ class Message; namespace compiler { // Utility class for launching sub-processes. -class LIBPROTOC_EXPORT Subprocess { +class PROTOC_EXPORT Subprocess { public: Subprocess(); ~Subprocess(); @@ -64,19 +66,19 @@ class LIBPROTOC_EXPORT Subprocess { // Start the subprocess. Currently we don't provide a way to specify // arguments as protoc plugins don't have any. - void Start(const string& program, SearchMode search_mode); + void Start(const std::string& program, SearchMode search_mode); // Serialize the input message and pipe it to the subprocess's stdin, then // close the pipe. Meanwhile, read from the subprocess's stdout and parse // the data into *output. All this is done carefully to avoid deadlocks. // Returns true if successful. On any sort of error, returns false and sets // *error to a description of the problem. - bool Communicate(const Message& input, Message* output, string* error); + bool Communicate(const Message& input, Message* output, std::string* error); #ifdef _WIN32 // Given an error code, returns a human-readable error message. This is // defined here so that CommandLineInterface can share it. - static string Win32ErrorMessage(DWORD error_code); + static std::string Win32ErrorMessage(DWORD error_code); #endif private: @@ -104,4 +106,6 @@ class LIBPROTOC_EXPORT Subprocess { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_SUBPROCESS_H__ diff --git a/src/google/protobuf/compiler/zip_writer.h b/src/google/protobuf/compiler/zip_writer.h index 03db4d573c..a99bb78ce7 100644 --- a/src/google/protobuf/compiler/zip_writer.h +++ b/src/google/protobuf/compiler/zip_writer.h @@ -73,12 +73,12 @@ class ZipWriter { ZipWriter(io::ZeroCopyOutputStream* raw_output); ~ZipWriter(); - bool Write(const string& filename, const string& contents); + bool Write(const std::string& filename, const std::string& contents); bool WriteDirectory(); private: struct FileInfo { - string name; + std::string name; uint32 offset; uint32 size; uint32 crc32; diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index 5486ab92c3..26f2b8c85d 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -70,6 +70,8 @@ #undef PACKAGE // autoheader #defines this. :( +#include + namespace google { namespace protobuf { @@ -776,7 +778,7 @@ class FileDescriptorTables { FieldsByNumberMap fields_by_number_; // Not including extensions. EnumValuesByNumberMap enum_values_by_number_; mutable EnumValuesByNumberMap unknown_enum_values_by_number_ - GOOGLE_GUARDED_BY(unknown_enum_values_mu_); + PROTOBUF_GUARDED_BY(unknown_enum_values_mu_); // Populated on first request to save space, hence constness games. mutable internal::once_flag locations_by_path_once_; diff --git a/src/google/protobuf/descriptor.h b/src/google/protobuf/descriptor.h index 08caab2eb0..cf0a52bb0c 100644 --- a/src/google/protobuf/descriptor.h +++ b/src/google/protobuf/descriptor.h @@ -62,11 +62,17 @@ #include #include +#include + // TYPE_BOOL is defined in the MacOS's ConditionalMacros.h. #ifdef TYPE_BOOL #undef TYPE_BOOL #endif // TYPE_BOOL +#ifdef SWIG +#define PROTOBUF_EXPORT +#endif + namespace google { namespace protobuf { @@ -147,9 +153,9 @@ struct SourceLocation { // Doc comments found at the source location. // See the comments in SourceCodeInfo.Location (descriptor.proto) for details. - string leading_comments; - string trailing_comments; - std::vector leading_detached_comments; + std::string leading_comments; + std::string trailing_comments; + std::vector leading_detached_comments; }; // Options when generating machine-parsable output from a descriptor with @@ -175,7 +181,7 @@ struct DebugStringOptions { // which is needed when a pool has lazily_build_dependencies_ set. // Must be instantiated as mutable in a descriptor. namespace internal { -class LIBPROTOBUF_EXPORT LazyDescriptor { +class PROTOBUF_EXPORT LazyDescriptor { public: // Init function to be called at init time of a descriptor containing // a LazyDescriptor. @@ -197,7 +203,7 @@ class LIBPROTOBUF_EXPORT LazyDescriptor { // build time if the symbol wasn't found and building of the file containing // that type is delayed because lazily_build_dependencies_ is set on the pool. // Should not be called after Set() has been called. - void SetLazy(const string& name, const FileDescriptor* file); + void SetLazy(const std::string& name, const FileDescriptor* file); // Returns the current value of the descriptor, thread-safe. If SetLazy(...) // has been called, will do a one-time cross link of the type specified, @@ -213,7 +219,7 @@ class LIBPROTOBUF_EXPORT LazyDescriptor { void Once(); const Descriptor* descriptor_; - const string* name_; + const std::string* name_; internal::once_flag* once_; const FileDescriptor* file_; }; @@ -224,17 +230,17 @@ class LIBPROTOBUF_EXPORT LazyDescriptor { // Message::GetDescriptor(). Generated message classes also have a // static method called descriptor() which returns the type's descriptor. // Use DescriptorPool to construct your own descriptors. -class LIBPROTOBUF_EXPORT Descriptor { +class PROTOBUF_EXPORT Descriptor { public: // The name of the message type, not including its scope. - const string& name() const; + const std::string& name() const; // The fully-qualified name of the message type, scope delimited by // periods. For example, message type "Foo" which is declared in package // "bar" has full name "bar.Foo". If a type "Baz" is nested within // Foo, Baz's full_name is "bar.Foo.Baz". To get only the part that // comes after the last '.', use name(). - const string& full_name() const; + const std::string& full_name() const; // Index of this descriptor within the file or containing type's message // type array. @@ -260,11 +266,11 @@ class LIBPROTOBUF_EXPORT Descriptor { // Write the contents of this decriptor in a human-readable form. Output // will be suitable for re-parsing. - string DebugString() const; + std::string DebugString() const; // Similar to DebugString(), but additionally takes options (e.g., // include original user comments in output). - string DebugStringWithOptions(const DebugStringOptions& options) const; + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Returns true if this is a placeholder for an unknown type. This will // only be the case if this descriptor comes from a DescriptorPool @@ -283,20 +289,20 @@ class LIBPROTOBUF_EXPORT Descriptor { // exists. const FieldDescriptor* FindFieldByNumber(int number) const; // Looks up a field by name. Returns NULL if no such field exists. - const FieldDescriptor* FindFieldByName(const string& name) const; + const FieldDescriptor* FindFieldByName(const std::string& name) const; // Looks up a field by lowercased name (as returned by lowercase_name()). // This lookup may be ambiguous if multiple field names differ only by case, // in which case the field returned is chosen arbitrarily from the matches. const FieldDescriptor* FindFieldByLowercaseName( - const string& lowercase_name) const; + const std::string& lowercase_name) const; // Looks up a field by camel-case name (as returned by camelcase_name()). // This lookup may be ambiguous if multiple field names differ in a way that // leads them to have identical camel-case names, in which case the field // returned is chosen arbitrarily from the matches. const FieldDescriptor* FindFieldByCamelcaseName( - const string& camelcase_name) const; + const std::string& camelcase_name) const; // The number of oneofs in this message type. int oneof_decl_count() const; @@ -305,7 +311,7 @@ class LIBPROTOBUF_EXPORT Descriptor { const OneofDescriptor* oneof_decl(int index) const; // Looks up a oneof by name. Returns NULL if no such oneof exists. - const OneofDescriptor* FindOneofByName(const string& name) const; + const OneofDescriptor* FindOneofByName(const std::string& name) const; // Nested type stuff ----------------------------------------------- @@ -317,7 +323,7 @@ class LIBPROTOBUF_EXPORT Descriptor { // Looks up a nested type by name. Returns NULL if no such nested type // exists. - const Descriptor* FindNestedTypeByName(const string& name) const; + const Descriptor* FindNestedTypeByName(const std::string& name) const; // Enum stuff ------------------------------------------------------ @@ -328,11 +334,11 @@ class LIBPROTOBUF_EXPORT Descriptor { const EnumDescriptor* enum_type(int index) const; // Looks up an enum type by name. Returns NULL if no such enum type exists. - const EnumDescriptor* FindEnumTypeByName(const string& name) const; + const EnumDescriptor* FindEnumTypeByName(const std::string& name) const; // Looks up an enum value by name, among all enum types in this message. // Returns NULL if no such value exists. - const EnumValueDescriptor* FindEnumValueByName(const string& name) const; + const EnumValueDescriptor* FindEnumValueByName(const std::string& name) const; // Extensions ------------------------------------------------------ @@ -372,15 +378,15 @@ class LIBPROTOBUF_EXPORT Descriptor { // Looks up a named extension (which extends some *other* message type) // defined within this message type's scope. - const FieldDescriptor* FindExtensionByName(const string& name) const; + const FieldDescriptor* FindExtensionByName(const std::string& name) const; // Similar to FindFieldByLowercaseName(), but finds extensions defined within // this message type's scope. - const FieldDescriptor* FindExtensionByLowercaseName(const string& name) const; + const FieldDescriptor* FindExtensionByLowercaseName(const std::string& name) const; // Similar to FindFieldByCamelcaseName(), but finds extensions defined within // this message type's scope. - const FieldDescriptor* FindExtensionByCamelcaseName(const string& name) const; + const FieldDescriptor* FindExtensionByCamelcaseName(const std::string& name) const; // Reserved fields ------------------------------------------------- @@ -407,10 +413,10 @@ class LIBPROTOBUF_EXPORT Descriptor { int reserved_name_count() const; // Gets a reserved name by index, where 0 <= index < reserved_name_count(). - const string& reserved_name(int index) const; + const std::string& reserved_name(int index) const; // Returns true if the field name is reserved. - bool IsReservedName(const string& name) const; + bool IsReservedName(const std::string& name) const; // Source Location --------------------------------------------------- @@ -436,7 +442,7 @@ class LIBPROTOBUF_EXPORT Descriptor { // correct depth. Takes |options| to control debug-string options, and // |include_opening_clause| to indicate whether the "message ... " part of the // clause has already been generated (this varies depending on context). - void DebugString(int depth, string *contents, + void DebugString(int depth, std::string *contents, const DebugStringOptions& options, bool include_opening_clause) const; @@ -444,8 +450,8 @@ class LIBPROTOBUF_EXPORT Descriptor { // to this descriptor from the file root. void GetLocationPath(std::vector* output) const; - const string* name_; - const string* full_name_; + const std::string* name_; + const std::string* full_name_; const FileDescriptor* file_; const Descriptor* containing_type_; const MessageOptions* options_; @@ -458,7 +464,7 @@ class LIBPROTOBUF_EXPORT Descriptor { ExtensionRange* extension_ranges_; FieldDescriptor* extensions_; ReservedRange* reserved_ranges_; - const string** reserved_names_; + const std::string** reserved_names_; int field_count_; int oneof_decl_count_; @@ -503,7 +509,7 @@ class LIBPROTOBUF_EXPORT Descriptor { // Reflection::FindKnownExtensionByName() or // Reflection::FindKnownExtensionByNumber(). // Use DescriptorPool to construct your own descriptors. -class LIBPROTOBUF_EXPORT FieldDescriptor { +class PROTOBUF_EXPORT FieldDescriptor { public: // Identifies a field type. 0 is reserved for errors. The order is weird // for historical reasons. Types 12 and up are new in proto2. @@ -576,9 +582,9 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // Users may not declare fields that use reserved numbers. static const int kLastReservedNumber = 19999; - const string& name() const; // Name of this field within the message. - const string& full_name() const; // Fully-qualified name of the field. - const string& json_name() const; // JSON name of this field. + const std::string& name() const; // Name of this field within the message. + const std::string& full_name() const; // Fully-qualified name of the field. + const std::string& json_name() const; // JSON name of this field. const FileDescriptor* file() const;// File in which this field was defined. bool is_extension() const; // Is this an extension field? int number() const; // Declared tag number. @@ -589,7 +595,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // field names should be lowercased anyway according to the protobuf style // guide, so this only makes a difference when dealing with old .proto files // which do not follow the guide.) - const string& lowercase_name() const; + const std::string& lowercase_name() const; // Same as name() except converted to camel-case. In this conversion, any // time an underscore appears in the name, it is removed and the next @@ -600,7 +606,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // fooBar -> fooBar // This (and especially the FindFieldByCamelcaseName() method) can be useful // when parsing formats which prefer to use camel-case naming style. - const string& camelcase_name() const; + const std::string& camelcase_name() const; Type type() const; // Declared type of this field. const char* type_name() const; // Name of the declared type. @@ -657,7 +663,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { const EnumValueDescriptor* default_value_enum() const; // Get the field default value if cpp_type() == CPPTYPE_STRING. If no // explicit default was defined, the default is the empty string. - const string& default_value_string() const; + const std::string& default_value_string() const; // The Descriptor for the message of which this is a field. For extensions, // this is the extended type. Never NULL. @@ -695,10 +701,10 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { void CopyTo(FieldDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Helper method to get the CppType for a particular Type. static CppType TypeToCppType(Type type); @@ -732,15 +738,15 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // See Descriptor::DebugString(). enum PrintLabelFlag { PRINT_LABEL, OMIT_LABEL }; void DebugString(int depth, PrintLabelFlag print_label_flag, - string* contents, const DebugStringOptions& options) const; + std::string* contents, const DebugStringOptions& options) const; // formats the default value appropriately and returns it as a string. // Must have a default value to call this. If quote_string_type is true, then // types of CPPTYPE_STRING whill be surrounded by quotes and CEscaped. - string DefaultValueAsString(bool quote_string_type) const; + std::string DefaultValueAsString(bool quote_string_type) const; // Helper function that returns the field type name for DebugString. - string FieldTypeNameDebugString() const; + std::string FieldTypeNameDebugString() const; // Walks up the descriptor tree to generate the source location path // to this descriptor from the file root. @@ -749,13 +755,13 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // Returns true if this is a map message type. bool is_map_message_type() const; - const string* name_; - const string* full_name_; - const string* lowercase_name_; - const string* camelcase_name_; + const std::string* name_; + const std::string* full_name_; + const std::string* lowercase_name_; + const std::string* camelcase_name_; // If has_json_name_ is true, it's the value specified by the user. // Otherwise, it has the same value as camelcase_name_. - const string* json_name_; + const std::string* json_name_; const FileDescriptor* file_; internal::once_flag* type_once_; static void TypeOnceInit(const FieldDescriptor* to_init); @@ -775,8 +781,8 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { mutable const Descriptor* message_type_; mutable const EnumDescriptor* enum_type_; const FieldOptions* options_; - const string* type_name_; - const string* default_value_enum_name_; + const std::string* type_name_; + const std::string* default_value_enum_name_; // IMPORTANT: If you add a new field, make sure to search for all instances // of Allocate() and AllocateArray() in // descriptor.cc and update them to initialize the field. @@ -791,7 +797,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { bool default_value_bool_; mutable const EnumValueDescriptor* default_value_enum_; - const string* default_value_string_; + const std::string* default_value_string_; }; static const CppType kTypeToCppTypeMap[MAX_TYPE + 1]; @@ -813,10 +819,10 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // Describes a oneof defined in a message type. -class LIBPROTOBUF_EXPORT OneofDescriptor { +class PROTOBUF_EXPORT OneofDescriptor { public: - const string& name() const; // Name of this oneof. - const string& full_name() const; // Fully-qualified name of the oneof. + const std::string& name() const; // Name of this oneof. + const std::string& full_name() const; // Fully-qualified name of the oneof. // Index of this oneof within the message's oneof array. int index() const; @@ -838,10 +844,10 @@ class LIBPROTOBUF_EXPORT OneofDescriptor { void CopyTo(OneofDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Source Location --------------------------------------------------- @@ -858,15 +864,15 @@ class LIBPROTOBUF_EXPORT OneofDescriptor { friend class compiler::cpp::Formatter; // See Descriptor::DebugString(). - void DebugString(int depth, string* contents, + void DebugString(int depth, std::string* contents, const DebugStringOptions& options) const; // Walks up the descriptor tree to generate the source location path // to this descriptor from the file root. void GetLocationPath(std::vector* output) const; - const string* name_; - const string* full_name_; + const std::string* name_; + const std::string* full_name_; const Descriptor* containing_type_; bool is_extendable_; int field_count_; @@ -887,13 +893,13 @@ class LIBPROTOBUF_EXPORT OneofDescriptor { // Describes an enum type defined in a .proto file. To get the EnumDescriptor // for a generated enum type, call TypeName_descriptor(). Use DescriptorPool // to construct your own descriptors. -class LIBPROTOBUF_EXPORT EnumDescriptor { +class PROTOBUF_EXPORT EnumDescriptor { public: // The name of this enum type in the containing scope. - const string& name() const; + const std::string& name() const; // The fully-qualified name of the enum type, scope delimited by periods. - const string& full_name() const; + const std::string& full_name() const; // Index of this enum within the file or containing message's enum array. int index() const; @@ -909,7 +915,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptor { const EnumValueDescriptor* value(int index) const; // Looks up a value by name. Returns NULL if no such value exists. - const EnumValueDescriptor* FindValueByName(const string& name) const; + const EnumValueDescriptor* FindValueByName(const std::string& name) const; // Looks up a value by number. Returns NULL if no such value exists. If // multiple values have this number, the first one defined is returned. const EnumValueDescriptor* FindValueByNumber(int number) const; @@ -928,10 +934,10 @@ class LIBPROTOBUF_EXPORT EnumDescriptor { void CopyTo(EnumDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Returns true if this is a placeholder for an unknown enum. This will // only be the case if this descriptor comes from a DescriptorPool @@ -964,10 +970,10 @@ class LIBPROTOBUF_EXPORT EnumDescriptor { int reserved_name_count() const; // Gets a reserved name by index, where 0 <= index < reserved_name_count(). - const string& reserved_name(int index) const; + const std::string& reserved_name(int index) const; // Returns true if the field name is reserved. - bool IsReservedName(const string& name) const; + bool IsReservedName(const std::string& name) const; // Source Location --------------------------------------------------- @@ -996,15 +1002,15 @@ class LIBPROTOBUF_EXPORT EnumDescriptor { // See Descriptor::DebugString(). - void DebugString(int depth, string *contents, + void DebugString(int depth, std::string *contents, const DebugStringOptions& options) const; // Walks up the descriptor tree to generate the source location path // to this descriptor from the file root. void GetLocationPath(std::vector* output) const; - const string* name_; - const string* full_name_; + const std::string* name_; + const std::string* full_name_; const FileDescriptor* file_; const Descriptor* containing_type_; const EnumOptions* options_; @@ -1020,7 +1026,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptor { int reserved_range_count_; int reserved_name_count_; EnumDescriptor::ReservedRange* reserved_ranges_; - const string** reserved_names_; + const std::string** reserved_names_; // IMPORTANT: If you add a new field, make sure to search for all instances // of Allocate() and AllocateArray() in @@ -1043,9 +1049,9 @@ class LIBPROTOBUF_EXPORT EnumDescriptor { // for its type, then use EnumDescriptor::FindValueByName() or // EnumDescriptor::FindValueByNumber(). Use DescriptorPool to construct // your own descriptors. -class LIBPROTOBUF_EXPORT EnumValueDescriptor { +class PROTOBUF_EXPORT EnumValueDescriptor { public: - const string& name() const; // Name of this enum constant. + const std::string& name() const; // Name of this enum constant. int index() const; // Index within the enums's Descriptor. int number() const; // Numeric value of this enum constant. @@ -1054,7 +1060,7 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptor { // "google.protobuf.FieldDescriptorProto.TYPE_INT32", NOT // "google.protobuf.FieldDescriptorProto.Type.TYPE_INT32". This is to conform // with C++ scoping rules for enums. - const string& full_name() const; + const std::string& full_name() const; // The .proto file in which this value was defined. Never NULL. const FileDescriptor* file() const; @@ -1071,10 +1077,10 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptor { void CopyTo(EnumValueDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Source Location --------------------------------------------------- @@ -1092,15 +1098,15 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptor { friend class compiler::cpp::Formatter; // See Descriptor::DebugString(). - void DebugString(int depth, string *contents, + void DebugString(int depth, std::string *contents, const DebugStringOptions& options) const; // Walks up the descriptor tree to generate the source location path // to this descriptor from the file root. void GetLocationPath(std::vector* output) const; - const string* name_; - const string* full_name_; + const std::string* name_; + const std::string* full_name_; int number_; const EnumDescriptor* type_; const EnumValueOptions* options_; @@ -1121,12 +1127,12 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptor { // call Service::GetDescriptor(). Generated service classes also have a // static method called descriptor() which returns the type's // ServiceDescriptor. Use DescriptorPool to construct your own descriptors. -class LIBPROTOBUF_EXPORT ServiceDescriptor { +class PROTOBUF_EXPORT ServiceDescriptor { public: // The name of the service, not including its containing scope. - const string& name() const; + const std::string& name() const; // The fully-qualified name of the service, scope delimited by periods. - const string& full_name() const; + const std::string& full_name() const; // Index of this service within the file's services array. int index() const; @@ -1146,15 +1152,15 @@ class LIBPROTOBUF_EXPORT ServiceDescriptor { const MethodDescriptor* method(int index) const; // Look up a MethodDescriptor by name. - const MethodDescriptor* FindMethodByName(const string& name) const; + const MethodDescriptor* FindMethodByName(const std::string& name) const; // See Descriptor::CopyTo(). void CopyTo(ServiceDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Source Location --------------------------------------------------- @@ -1172,14 +1178,14 @@ class LIBPROTOBUF_EXPORT ServiceDescriptor { friend class compiler::cpp::Formatter; // See Descriptor::DebugString(). - void DebugString(string *contents, const DebugStringOptions& options) const; + void DebugString(std::string *contents, const DebugStringOptions& options) const; // Walks up the descriptor tree to generate the source location path // to this descriptor from the file root. void GetLocationPath(std::vector* output) const; - const string* name_; - const string* full_name_; + const std::string* name_; + const std::string* full_name_; const FileDescriptor* file_; const ServiceOptions* options_; MethodDescriptor* methods_; @@ -1201,12 +1207,12 @@ class LIBPROTOBUF_EXPORT ServiceDescriptor { // a service, first get its ServiceDescriptor, then call // ServiceDescriptor::FindMethodByName(). Use DescriptorPool to construct your // own descriptors. -class LIBPROTOBUF_EXPORT MethodDescriptor { +class PROTOBUF_EXPORT MethodDescriptor { public: // Name of this method, not including containing scope. - const string& name() const; + const std::string& name() const; // The fully-qualified name of the method, scope delimited by periods. - const string& full_name() const; + const std::string& full_name() const; // Index within the service's Descriptor. int index() const; @@ -1235,10 +1241,10 @@ class LIBPROTOBUF_EXPORT MethodDescriptor { void CopyTo(MethodDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Source Location --------------------------------------------------- @@ -1256,15 +1262,15 @@ class LIBPROTOBUF_EXPORT MethodDescriptor { friend class compiler::cpp::Formatter; // See Descriptor::DebugString(). - void DebugString(int depth, string *contents, + void DebugString(int depth, std::string *contents, const DebugStringOptions& options) const; // Walks up the descriptor tree to generate the source location path // to this descriptor from the file root. void GetLocationPath(std::vector* output) const; - const string* name_; - const string* full_name_; + const std::string* name_; + const std::string* full_name_; const ServiceDescriptor* service_; mutable internal::LazyDescriptor input_type_; mutable internal::LazyDescriptor output_type_; @@ -1286,14 +1292,14 @@ class LIBPROTOBUF_EXPORT MethodDescriptor { // Describes a whole .proto file. To get the FileDescriptor for a compiled-in // file, get the descriptor for something defined in that file and call // descriptor->file(). Use DescriptorPool to construct your own descriptors. -class LIBPROTOBUF_EXPORT FileDescriptor { +class PROTOBUF_EXPORT FileDescriptor { public: // The filename, relative to the source tree. // e.g. "foo/bar/baz.proto" - const string& name() const; + const std::string& name() const; // The package, e.g. "google.protobuf.compiler". - const string& package() const; + const std::string& package() const; // The DescriptorPool in which this FileDescriptor and all its contents were // allocated. Never NULL. @@ -1364,22 +1370,22 @@ class LIBPROTOBUF_EXPORT FileDescriptor { static const char* SyntaxName(Syntax syntax); // Find a top-level message type by name. Returns NULL if not found. - const Descriptor* FindMessageTypeByName(const string& name) const; + const Descriptor* FindMessageTypeByName(const std::string& name) const; // Find a top-level enum type by name. Returns NULL if not found. - const EnumDescriptor* FindEnumTypeByName(const string& name) const; + const EnumDescriptor* FindEnumTypeByName(const std::string& name) const; // Find an enum value defined in any top-level enum by name. Returns NULL if // not found. - const EnumValueDescriptor* FindEnumValueByName(const string& name) const; + const EnumValueDescriptor* FindEnumValueByName(const std::string& name) const; // Find a service definition by name. Returns NULL if not found. - const ServiceDescriptor* FindServiceByName(const string& name) const; + const ServiceDescriptor* FindServiceByName(const std::string& name) const; // Find a top-level extension definition by name. Returns NULL if not found. - const FieldDescriptor* FindExtensionByName(const string& name) const; + const FieldDescriptor* FindExtensionByName(const std::string& name) const; // Similar to FindExtensionByName(), but searches by lowercased-name. See // Descriptor::FindFieldByLowercaseName(). - const FieldDescriptor* FindExtensionByLowercaseName(const string& name) const; + const FieldDescriptor* FindExtensionByLowercaseName(const std::string& name) const; // Similar to FindExtensionByName(), but searches by camelcased-name. See // Descriptor::FindFieldByCamelcaseName(). - const FieldDescriptor* FindExtensionByCamelcaseName(const string& name) const; + const FieldDescriptor* FindExtensionByCamelcaseName(const std::string& name) const; // See Descriptor::CopyTo(). // Notes: @@ -1394,10 +1400,10 @@ class LIBPROTOBUF_EXPORT FileDescriptor { void CopyJsonNameTo(FileDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Returns true if this is a placeholder for an unknown file. This will // only be the case if this descriptor comes from a DescriptorPool @@ -1419,8 +1425,8 @@ class LIBPROTOBUF_EXPORT FileDescriptor { private: typedef FileOptions OptionsType; - const string* name_; - const string* package_; + const std::string* name_; + const std::string* package_; const DescriptorPool* pool_; internal::once_flag* dependencies_once_; static void DependenciesOnceInit(const FileDescriptor* to_init); @@ -1443,7 +1449,7 @@ class LIBPROTOBUF_EXPORT FileDescriptor { bool finished_building_; mutable const FileDescriptor** dependencies_; - const string** dependencies_names_; + const std::string** dependencies_names_; int* public_dependencies_; int* weak_dependencies_; Descriptor* message_types_; @@ -1500,7 +1506,7 @@ class LIBPROTOBUF_EXPORT FileDescriptor { // // You can also search for descriptors within a DescriptorPool by name, and // extensions by number. -class LIBPROTOBUF_EXPORT DescriptorPool { +class PROTOBUF_EXPORT DescriptorPool { public: // Create a normal, empty DescriptorPool. DescriptorPool(); @@ -1542,28 +1548,28 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // Find a FileDescriptor in the pool by file name. Returns NULL if not // found. - const FileDescriptor* FindFileByName(const string& name) const; + const FileDescriptor* FindFileByName(const std::string& name) const; // Find the FileDescriptor in the pool which defines the given symbol. // If any of the Find*ByName() methods below would succeed, then this is // equivalent to calling that method and calling the result's file() method. // Otherwise this returns NULL. const FileDescriptor* FindFileContainingSymbol( - const string& symbol_name) const; + const std::string& symbol_name) const; // Looking up descriptors ------------------------------------------ // These find descriptors by fully-qualified name. These will find both // top-level descriptors and nested descriptors. They return NULL if not // found. - const Descriptor* FindMessageTypeByName(const string& name) const; - const FieldDescriptor* FindFieldByName(const string& name) const; - const FieldDescriptor* FindExtensionByName(const string& name) const; - const OneofDescriptor* FindOneofByName(const string& name) const; - const EnumDescriptor* FindEnumTypeByName(const string& name) const; - const EnumValueDescriptor* FindEnumValueByName(const string& name) const; - const ServiceDescriptor* FindServiceByName(const string& name) const; - const MethodDescriptor* FindMethodByName(const string& name) const; + const Descriptor* FindMessageTypeByName(const std::string& name) const; + const FieldDescriptor* FindFieldByName(const std::string& name) const; + const FieldDescriptor* FindExtensionByName(const std::string& name) const; + const OneofDescriptor* FindOneofByName(const std::string& name) const; + const EnumDescriptor* FindEnumTypeByName(const std::string& name) const; + const EnumValueDescriptor* FindEnumValueByName(const std::string& name) const; + const ServiceDescriptor* FindServiceByName(const std::string& name) const; + const MethodDescriptor* FindMethodByName(const std::string& name) const; // Finds an extension of the given type by number. The extendee must be // a member of this DescriptorPool or one of its underlays. @@ -1583,7 +1589,7 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // When converting a FileDescriptorProto to a FileDescriptor, various // errors might be detected in the input. The caller may handle these // programmatically by implementing an ErrorCollector. - class LIBPROTOBUF_EXPORT ErrorCollector { + class PROTOBUF_EXPORT ErrorCollector { public: inline ErrorCollector() {} virtual ~ErrorCollector(); @@ -1607,21 +1613,21 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // Reports an error in the FileDescriptorProto. Use this function if the // problem occurred should interrupt building the FileDescriptorProto. virtual void AddError( - const string& filename, // File name in which the error occurred. - const string& element_name, // Full name of the erroneous element. + const std::string& filename, // File name in which the error occurred. + const std::string& element_name, // Full name of the erroneous element. const Message* descriptor, // Descriptor of the erroneous element. ErrorLocation location, // One of the location constants, above. - const string& message // Human-readable error message. + const std::string& message // Human-readable error message. ) = 0; // Reports a warning in the FileDescriptorProto. Use this function if the // problem occurred should NOT interrupt building the FileDescriptorProto. virtual void AddWarning( - const string& /*filename*/, // File name in which the error occurred. - const string& /*element_name*/, // Full name of the erroneous element. + const std::string& /*filename*/, // File name in which the error occurred. + const std::string& /*element_name*/, // Full name of the erroneous element. const Message* /*descriptor*/, // Descriptor of the erroneous element. ErrorLocation /*location*/, // One of the location constants, above. - const string& /*message*/ // Human-readable error message. + const std::string& /*message*/ // Human-readable error message. ) {} private: @@ -1734,12 +1740,12 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // For internal (unit test) use only: Returns true if a FileDescriptor has // been constructed for the given file, false otherwise. Useful for testing // lazy descriptor initialization behavior. - bool InternalIsFileLoaded(const string& filename) const; + bool InternalIsFileLoaded(const std::string& filename) const; // Add a file to unused_import_track_files_. DescriptorBuilder will log // warnings for those files if there is any unused import. - void AddUnusedImportTrackFile(const string& file_name); + void AddUnusedImportTrackFile(const std::string& file_name); void ClearUnusedImportTrackFiles(); private: @@ -1757,14 +1763,14 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // Return true if the given name is a sub-symbol of any non-package // descriptor that already exists in the descriptor pool. (The full // definition of such types is already known.) - bool IsSubSymbolOfBuiltType(const string& name) const; + bool IsSubSymbolOfBuiltType(const std::string& name) const; // Tries to find something in the fallback database and link in the // corresponding proto file. Returns true if successful, in which case // the caller should search for the thing again. These are declared // const because they are called by (semantically) const methods. - bool TryFindFileInFallbackDatabase(const string& name) const; - bool TryFindSymbolInFallbackDatabase(const string& name) const; + bool TryFindFileInFallbackDatabase(const std::string& name) const; + bool TryFindSymbolInFallbackDatabase(const std::string& name) const; bool TryFindExtensionInFallbackDatabase(const Descriptor* containing_type, int field_number) const; @@ -1779,11 +1785,11 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // symbol is defined if necessary. Will create a placeholder if the type // doesn't exist in the fallback database, or the file doesn't build // successfully. - Symbol CrossLinkOnDemandHelper(const string& name, bool expecting_enum) const; + Symbol CrossLinkOnDemandHelper(const std::string& name, bool expecting_enum) const; // Create a placeholder FileDescriptor of the specified name - FileDescriptor* NewPlaceholderFile(const string& name) const; - FileDescriptor* NewPlaceholderFileWithMutexHeld(const string& name) const; + FileDescriptor* NewPlaceholderFile(const std::string& name) const; + FileDescriptor* NewPlaceholderFileWithMutexHeld(const std::string& name) const; enum PlaceholderType { PLACEHOLDER_MESSAGE, @@ -1791,9 +1797,9 @@ class LIBPROTOBUF_EXPORT DescriptorPool { PLACEHOLDER_EXTENDABLE_MESSAGE }; // Create a placeholder Descriptor of the specified name - Symbol NewPlaceholder(const string& name, + Symbol NewPlaceholder(const std::string& name, PlaceholderType placeholder_type) const; - Symbol NewPlaceholderWithMutexHeld(const string& name, + Symbol NewPlaceholderWithMutexHeld(const std::string& name, PlaceholderType placeholder_type) const; // If fallback_database_ is NULL, this is NULL. Otherwise, this is a mutex @@ -1815,7 +1821,7 @@ class LIBPROTOBUF_EXPORT DescriptorPool { bool allow_unknown_; bool enforce_weak_; bool disallow_enforce_utf8_; - std::set unused_import_track_files_; + std::set unused_import_track_files_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DescriptorPool); }; @@ -1829,7 +1835,7 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // Strings fields are stored as pointers but returned as const references. #define PROTOBUF_DEFINE_STRING_ACCESSOR(CLASS, FIELD) \ - inline const string& CLASS::FIELD() const { return *FIELD##_; } + inline const std::string& CLASS::FIELD() const { return *FIELD##_; } // Arrays take an index parameter, obviously. #define PROTOBUF_DEFINE_ARRAY_ACCESSOR(CLASS, FIELD, TYPE) \ @@ -1969,7 +1975,7 @@ inline bool Descriptor::IsReservedNumber(int number) const { return FindReservedRangeContainingNumber(number) != NULL; } -inline bool Descriptor::IsReservedName(const string& name) const { +inline bool Descriptor::IsReservedName(const std::string& name) const { for (int i = 0; i < reserved_name_count(); i++) { if (name == reserved_name(i)) { return true; @@ -1980,7 +1986,7 @@ inline bool Descriptor::IsReservedName(const string& name) const { // Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because reserved_names_ is actually // an array of pointers rather than the usual array of objects. -inline const string& Descriptor::reserved_name(int index) const { +inline const std::string& Descriptor::reserved_name(int index) const { return *reserved_names_[index]; } @@ -1988,7 +1994,7 @@ inline bool EnumDescriptor::IsReservedNumber(int number) const { return FindReservedRangeContainingNumber(number) != NULL; } -inline bool EnumDescriptor::IsReservedName(const string& name) const { +inline bool EnumDescriptor::IsReservedName(const std::string& name) const { for (int i = 0; i < reserved_name_count(); i++) { if (name == reserved_name(i)) { return true; @@ -1999,7 +2005,7 @@ inline bool EnumDescriptor::IsReservedName(const string& name) const { // Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because reserved_names_ is actually // an array of pointers rather than the usual array of objects. -inline const string& EnumDescriptor::reserved_name(int index) const { +inline const std::string& EnumDescriptor::reserved_name(int index) const { return *reserved_names_[index]; } @@ -2140,4 +2146,6 @@ inline const FieldDescriptor* OneofDescriptor::field(int index) const { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_DESCRIPTOR_H__ diff --git a/src/google/protobuf/descriptor.pb.cc b/src/google/protobuf/descriptor.pb.cc index 01accf9411..f85ed13698 100644 --- a/src/google/protobuf/descriptor.pb.cc +++ b/src/google/protobuf/descriptor.pb.cc @@ -13,10 +13,6 @@ #include #include #include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif // @@protoc_insertion_point(includes) #include @@ -168,7 +164,7 @@ static void InitDefaultsFileDescriptorSet_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::FileDescriptorSet::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FileDescriptorSet_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FileDescriptorSet_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFileDescriptorSet_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -183,7 +179,7 @@ static void InitDefaultsFileDescriptorProto_google_2fprotobuf_2fdescriptor_2epro ::google::protobuf::FileDescriptorProto::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<6> scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<6> scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 6, InitDefaultsFileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_DescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, &scc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, @@ -203,7 +199,7 @@ static void InitDefaultsDescriptorProto_ExtensionRange_google_2fprotobuf_2fdescr ::google::protobuf::DescriptorProto_ExtensionRange::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_DescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_DescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsDescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_ExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -218,7 +214,7 @@ static void InitDefaultsDescriptorProto_ReservedRange_google_2fprotobuf_2fdescri ::google::protobuf::DescriptorProto_ReservedRange::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_DescriptorProto_ReservedRange_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_DescriptorProto_ReservedRange_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDescriptorProto_ReservedRange_google_2fprotobuf_2fdescriptor_2eproto}, {}}; static void InitDefaultsDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() { @@ -232,7 +228,7 @@ static void InitDefaultsDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() ::google::protobuf::DescriptorProto::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<6> scc_info_DescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<6> scc_info_DescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 6, InitDefaultsDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, &scc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, @@ -252,7 +248,7 @@ static void InitDefaultsExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2ep ::google::protobuf::ExtensionRangeOptions::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_ExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_ExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -267,7 +263,7 @@ static void InitDefaultsFieldDescriptorProto_google_2fprotobuf_2fdescriptor_2epr ::google::protobuf::FieldDescriptorProto::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_FieldOptions_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -282,7 +278,7 @@ static void InitDefaultsOneofDescriptorProto_google_2fprotobuf_2fdescriptor_2epr ::google::protobuf::OneofDescriptorProto::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_OneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_OneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsOneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_OneofOptions_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -297,7 +293,7 @@ static void InitDefaultsEnumDescriptorProto_EnumReservedRange_google_2fprotobuf_ ::google::protobuf::EnumDescriptorProto_EnumReservedRange::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_EnumDescriptorProto_EnumReservedRange_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_EnumDescriptorProto_EnumReservedRange_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsEnumDescriptorProto_EnumReservedRange_google_2fprotobuf_2fdescriptor_2eproto}, {}}; static void InitDefaultsEnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() { @@ -311,7 +307,7 @@ static void InitDefaultsEnumDescriptorProto_google_2fprotobuf_2fdescriptor_2epro ::google::protobuf::EnumDescriptorProto::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<3> scc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<3> scc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsEnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_EnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, &scc_info_EnumOptions_google_2fprotobuf_2fdescriptor_2eproto.base, @@ -328,7 +324,7 @@ static void InitDefaultsEnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_ ::google::protobuf::EnumValueDescriptorProto::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_EnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -343,7 +339,7 @@ static void InitDefaultsServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2e ::google::protobuf::ServiceDescriptorProto::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<2> scc_info_ServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<2> scc_info_ServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_MethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base, &scc_info_ServiceOptions_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -359,7 +355,7 @@ static void InitDefaultsMethodDescriptorProto_google_2fprotobuf_2fdescriptor_2ep ::google::protobuf::MethodDescriptorProto::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_MethodOptions_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -374,7 +370,7 @@ static void InitDefaultsFileOptions_google_2fprotobuf_2fdescriptor_2eproto() { ::google::protobuf::FileOptions::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FileOptions_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FileOptions_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFileOptions_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -389,7 +385,7 @@ static void InitDefaultsMessageOptions_google_2fprotobuf_2fdescriptor_2eproto() ::google::protobuf::MessageOptions::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MessageOptions_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MessageOptions_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMessageOptions_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -404,7 +400,7 @@ static void InitDefaultsFieldOptions_google_2fprotobuf_2fdescriptor_2eproto() { ::google::protobuf::FieldOptions::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FieldOptions_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FieldOptions_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFieldOptions_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -419,7 +415,7 @@ static void InitDefaultsOneofOptions_google_2fprotobuf_2fdescriptor_2eproto() { ::google::protobuf::OneofOptions::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_OneofOptions_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_OneofOptions_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsOneofOptions_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -434,7 +430,7 @@ static void InitDefaultsEnumOptions_google_2fprotobuf_2fdescriptor_2eproto() { ::google::protobuf::EnumOptions::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumOptions_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumOptions_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumOptions_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -449,7 +445,7 @@ static void InitDefaultsEnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto( ::google::protobuf::EnumValueOptions::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -464,7 +460,7 @@ static void InitDefaultsServiceOptions_google_2fprotobuf_2fdescriptor_2eproto() ::google::protobuf::ServiceOptions::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_ServiceOptions_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_ServiceOptions_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsServiceOptions_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -479,7 +475,7 @@ static void InitDefaultsMethodOptions_google_2fprotobuf_2fdescriptor_2eproto() { ::google::protobuf::MethodOptions::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MethodOptions_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MethodOptions_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethodOptions_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -494,7 +490,7 @@ static void InitDefaultsUninterpretedOption_NamePart_google_2fprotobuf_2fdescrip ::google::protobuf::UninterpretedOption_NamePart::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_UninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_UninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsUninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto}, {}}; static void InitDefaultsUninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto() { @@ -508,7 +504,7 @@ static void InitDefaultsUninterpretedOption_google_2fprotobuf_2fdescriptor_2epro ::google::protobuf::UninterpretedOption::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsUninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_UninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -523,7 +519,7 @@ static void InitDefaultsSourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2 ::google::protobuf::SourceCodeInfo_Location::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_SourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_SourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsSourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto}, {}}; static void InitDefaultsSourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto() { @@ -537,7 +533,7 @@ static void InitDefaultsSourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto() ::google::protobuf::SourceCodeInfo::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_SourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_SourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsSourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_SourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -552,7 +548,7 @@ static void InitDefaultsGeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescrip ::google::protobuf::GeneratedCodeInfo_Annotation::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_GeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_GeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsGeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto}, {}}; static void InitDefaultsGeneratedCodeInfo_google_2fprotobuf_2fdescriptor_2eproto() { @@ -566,7 +562,7 @@ static void InitDefaultsGeneratedCodeInfo_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::GeneratedCodeInfo::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_GeneratedCodeInfo_google_2fprotobuf_2fdescriptor_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_GeneratedCodeInfo_google_2fprotobuf_2fdescriptor_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsGeneratedCodeInfo_google_2fprotobuf_2fdescriptor_2eproto}, { &scc_info_GeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto.base,}}; @@ -604,31 +600,31 @@ void InitDefaults_google_2fprotobuf_2fdescriptor_2eproto() { const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors_google_2fprotobuf_2fdescriptor_2eproto[6]; constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fdescriptor_2eproto = nullptr; -const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fdescriptor_2eproto::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorSet, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorSet, _internal_metadata_), +const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fdescriptor_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorSet, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorSet, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorSet, file_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorSet, file_), ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, package_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, dependency_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, public_dependency_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, weak_dependency_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, message_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, enum_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, service_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, extension_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, options_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, source_code_info_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, syntax_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, name_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, package_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, dependency_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, public_dependency_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, weak_dependency_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, message_type_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, enum_type_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, service_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, extension_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, source_code_info_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, syntax_), 0, 1, ~0u, @@ -641,41 +637,41 @@ const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fdescriptor_2epr 3, 4, 2, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, start_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, end_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, options_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, start_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, end_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, options_), 1, 2, 0, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ReservedRange, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ReservedRange, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto_ReservedRange, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto_ReservedRange, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ReservedRange, start_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ReservedRange, end_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto_ReservedRange, start_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto_ReservedRange, end_), 0, 1, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, field_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, extension_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, nested_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, enum_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, extension_range_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, oneof_decl_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, options_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, reserved_range_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, reserved_name_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, name_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, field_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, extension_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, nested_type_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, enum_type_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, extension_range_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, oneof_decl_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, reserved_range_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, reserved_name_), 0, ~0u, ~0u, @@ -686,28 +682,28 @@ const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fdescriptor_2epr 1, ~0u, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ExtensionRangeOptions, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ExtensionRangeOptions, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ExtensionRangeOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::ExtensionRangeOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::ExtensionRangeOptions, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::ExtensionRangeOptions, _extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ExtensionRangeOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::ExtensionRangeOptions, uninterpreted_option_), ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, number_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, label_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, type_name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, extendee_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, default_value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, oneof_index_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, json_name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, name_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, number_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, label_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, type_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, type_name_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, extendee_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, default_value_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, oneof_index_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, json_name_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, options_), 0, 6, 8, @@ -718,104 +714,104 @@ const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fdescriptor_2epr 7, 4, 5, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofDescriptorProto, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofDescriptorProto, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::OneofDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::OneofDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofDescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::OneofDescriptorProto, name_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::OneofDescriptorProto, options_), 0, 1, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto_EnumReservedRange, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto_EnumReservedRange, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto_EnumReservedRange, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto_EnumReservedRange, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto_EnumReservedRange, start_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto_EnumReservedRange, end_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto_EnumReservedRange, start_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto_EnumReservedRange, end_), 0, 1, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, options_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, reserved_range_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, reserved_name_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, name_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, value_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, reserved_range_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, reserved_name_), 0, ~0u, 1, ~0u, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, number_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, name_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, number_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, options_), 0, 2, 1, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, method_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, name_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, method_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, options_), 0, ~0u, 1, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, input_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, output_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, options_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, client_streaming_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, server_streaming_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, name_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, input_type_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, output_type_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, client_streaming_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, server_streaming_), 0, 1, 2, 3, 4, 5, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, _extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, java_package_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, java_outer_classname_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, java_multiple_files_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, java_generate_equals_and_hash_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, java_string_check_utf8_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, optimize_for_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, go_package_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, cc_generic_services_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, java_generic_services_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, py_generic_services_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, php_generic_services_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, deprecated_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, cc_enable_arenas_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, objc_class_prefix_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, csharp_namespace_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, swift_prefix_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, php_class_prefix_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, php_namespace_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, php_metadata_namespace_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, ruby_package_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, java_package_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, java_outer_classname_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, java_multiple_files_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, java_generate_equals_and_hash_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, java_string_check_utf8_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, optimize_for_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, go_package_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, cc_generic_services_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, java_generic_services_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, py_generic_services_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, php_generic_services_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, deprecated_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, cc_enable_arenas_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, objc_class_prefix_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, csharp_namespace_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, swift_prefix_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, php_class_prefix_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, php_namespace_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, php_metadata_namespace_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, ruby_package_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, uninterpreted_option_), 0, 1, 10, @@ -837,33 +833,33 @@ const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fdescriptor_2epr 8, 9, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MessageOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MessageOptions, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MessageOptions, _extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, message_set_wire_format_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, no_standard_descriptor_accessor_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, deprecated_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, map_entry_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MessageOptions, message_set_wire_format_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MessageOptions, no_standard_descriptor_accessor_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MessageOptions, deprecated_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MessageOptions, map_entry_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MessageOptions, uninterpreted_option_), 0, 1, 2, 3, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, _extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, ctype_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, packed_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, jstype_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, lazy_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, deprecated_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, weak_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, ctype_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, packed_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, jstype_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, lazy_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, deprecated_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, weak_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, uninterpreted_option_), 0, 1, 5, @@ -871,74 +867,74 @@ const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fdescriptor_2epr 3, 4, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofOptions, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofOptions, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::OneofOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::OneofOptions, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::OneofOptions, _extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::OneofOptions, uninterpreted_option_), ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumOptions, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumOptions, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumOptions, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumOptions, _extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumOptions, allow_alias_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumOptions, deprecated_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumOptions, allow_alias_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumOptions, deprecated_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumOptions, uninterpreted_option_), 0, 1, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueOptions, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueOptions, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValueOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValueOptions, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValueOptions, _extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueOptions, deprecated_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValueOptions, deprecated_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValueOptions, uninterpreted_option_), 0, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceOptions, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceOptions, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::ServiceOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::ServiceOptions, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::ServiceOptions, _extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceOptions, deprecated_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::ServiceOptions, deprecated_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::ServiceOptions, uninterpreted_option_), 0, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodOptions, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodOptions, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodOptions, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodOptions, _extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodOptions, deprecated_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodOptions, idempotency_level_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodOptions, deprecated_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodOptions, idempotency_level_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodOptions, uninterpreted_option_), 0, 1, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption_NamePart, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption_NamePart, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption_NamePart, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption_NamePart, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption_NamePart, name_part_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption_NamePart, is_extension_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption_NamePart, name_part_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption_NamePart, is_extension_), 0, 1, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, identifier_value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, positive_int_value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, negative_int_value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, double_value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, string_value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, aggregate_value_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption, name_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption, identifier_value_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption, positive_int_value_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption, negative_int_value_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption, double_value_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption, string_value_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption, aggregate_value_), ~0u, 0, 3, @@ -946,50 +942,50 @@ const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fdescriptor_2epr 5, 1, 2, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, path_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, span_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, leading_comments_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, trailing_comments_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, leading_detached_comments_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, path_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, span_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, leading_comments_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, trailing_comments_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, leading_detached_comments_), ~0u, ~0u, 0, 1, ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::SourceCodeInfo, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::SourceCodeInfo, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo, location_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::SourceCodeInfo, location_), ~0u, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, path_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, source_file_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, begin_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, end_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, path_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, source_file_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, begin_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, end_), ~0u, 0, 1, 2, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo, _has_bits_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo, annotation_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo, annotation_), ~0u, }; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, 6, sizeof(::google::protobuf::FileDescriptorSet)}, { 7, 24, sizeof(::google::protobuf::FileDescriptorProto)}, { 36, 44, sizeof(::google::protobuf::DescriptorProto_ExtensionRange)}, @@ -1477,29 +1473,31 @@ const char* FileDescriptorSet::_InternalParse(const char* begin, const char* end while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // repeated .google.protobuf.FileDescriptorProto file = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::FileDescriptorProto::_InternalParse; object = msg->add_file(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 10 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1)); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -1510,8 +1508,6 @@ const char* FileDescriptorSet::_InternalParse(const char* begin, const char* end } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -1523,7 +1519,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool FileDescriptorSet::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FileDescriptorSet) for (;;) { @@ -1938,14 +1934,13 @@ const char* FileDescriptorProto::_InternalParse(const char* begin, const char* e while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional string name = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FileDescriptorProto.name"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_name(); @@ -1953,15 +1948,15 @@ const char* FileDescriptorProto::_InternalParse(const char* begin, const char* e object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional string package = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FileDescriptorProto.package"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_package(); @@ -1969,8 +1964,8 @@ const char* FileDescriptorProto::_InternalParse(const char* begin, const char* e object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // repeated string dependency = 3; @@ -1978,7 +1973,7 @@ const char* FileDescriptorProto::_InternalParse(const char* begin, const char* e if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FileDescriptorProto.dependency"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->add_dependency(); @@ -1986,10 +1981,10 @@ const char* FileDescriptorProto::_InternalParse(const char* begin, const char* e object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 26 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 26 && (ptr += 1)); break; } // repeated .google.protobuf.DescriptorProto message_type = 4; @@ -1997,15 +1992,17 @@ const char* FileDescriptorProto::_InternalParse(const char* begin, const char* e if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::DescriptorProto::_InternalParse; object = msg->add_message_type(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 34 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 34 && (ptr += 1)); break; } // repeated .google.protobuf.EnumDescriptorProto enum_type = 5; @@ -2013,15 +2010,17 @@ const char* FileDescriptorProto::_InternalParse(const char* begin, const char* e if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::EnumDescriptorProto::_InternalParse; object = msg->add_enum_type(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 42 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 42 && (ptr += 1)); break; } // repeated .google.protobuf.ServiceDescriptorProto service = 6; @@ -2029,15 +2028,17 @@ const char* FileDescriptorProto::_InternalParse(const char* begin, const char* e if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::ServiceDescriptorProto::_InternalParse; object = msg->add_service(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 50 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 50 && (ptr += 1)); break; } // repeated .google.protobuf.FieldDescriptorProto extension = 7; @@ -2045,27 +2046,31 @@ const char* FileDescriptorProto::_InternalParse(const char* begin, const char* e if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::FieldDescriptorProto::_InternalParse; object = msg->add_extension(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 58 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 58 && (ptr += 1)); break; } // optional .google.protobuf.FileOptions options = 8; case 8: { if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::FileOptions::_InternalParse; object = msg->mutable_options(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; break; } @@ -2073,12 +2078,14 @@ const char* FileDescriptorProto::_InternalParse(const char* begin, const char* e case 9: { if (static_cast<::google::protobuf::uint8>(tag) != 74) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::SourceCodeInfo::_InternalParse; object = msg->mutable_source_code_info(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; break; } @@ -2088,21 +2095,21 @@ const char* FileDescriptorProto::_InternalParse(const char* begin, const char* e do { ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->add_public_dependency(value); if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 80 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 80 && (ptr += 1)); break; } else if (static_cast<::google::protobuf::uint8>(tag) != 82) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::internal::PackedInt32Parser; object = msg->mutable_public_dependency(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // repeated int32 weak_dependency = 11; @@ -2111,28 +2118,28 @@ const char* FileDescriptorProto::_InternalParse(const char* begin, const char* e do { ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->add_weak_dependency(value); if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 88 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 88 && (ptr += 1)); break; } else if (static_cast<::google::protobuf::uint8>(tag) != 90) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::internal::PackedInt32Parser; object = msg->mutable_weak_dependency(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional string syntax = 12; case 12: { if (static_cast<::google::protobuf::uint8>(tag) != 98) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FileDescriptorProto.syntax"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_syntax(); @@ -2140,14 +2147,15 @@ const char* FileDescriptorProto::_InternalParse(const char* begin, const char* e object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -2158,8 +2166,6 @@ const char* FileDescriptorProto::_InternalParse(const char* begin, const char* e } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -2171,7 +2177,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool FileDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FileDescriptorProto) for (;;) { @@ -2967,15 +2973,14 @@ const char* DescriptorProto_ExtensionRange::_InternalParse(const char* begin, co while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional int32 start = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->set_start(value); break; @@ -2985,7 +2990,7 @@ const char* DescriptorProto_ExtensionRange::_InternalParse(const char* begin, co if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->set_end(value); break; @@ -2994,19 +2999,22 @@ const char* DescriptorProto_ExtensionRange::_InternalParse(const char* begin, co case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::ExtensionRangeOptions::_InternalParse; object = msg->mutable_options(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -3017,8 +3025,6 @@ const char* DescriptorProto_ExtensionRange::_InternalParse(const char* begin, co } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -3030,7 +3036,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool DescriptorProto_ExtensionRange::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.DescriptorProto.ExtensionRange) for (;;) { @@ -3392,15 +3398,14 @@ const char* DescriptorProto_ReservedRange::_InternalParse(const char* begin, con while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional int32 start = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->set_start(value); break; @@ -3410,15 +3415,16 @@ const char* DescriptorProto_ReservedRange::_InternalParse(const char* begin, con if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->set_end(value); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -3429,8 +3435,6 @@ const char* DescriptorProto_ReservedRange::_InternalParse(const char* begin, con } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -3442,7 +3446,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool DescriptorProto_ReservedRange::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.DescriptorProto.ReservedRange) for (;;) { @@ -3832,14 +3836,13 @@ const char* DescriptorProto::_InternalParse(const char* begin, const char* end, while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional string name = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.DescriptorProto.name"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_name(); @@ -3847,8 +3850,8 @@ const char* DescriptorProto::_InternalParse(const char* begin, const char* end, object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // repeated .google.protobuf.FieldDescriptorProto field = 2; @@ -3856,15 +3859,17 @@ const char* DescriptorProto::_InternalParse(const char* begin, const char* end, if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::FieldDescriptorProto::_InternalParse; object = msg->add_field(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 18 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1)); break; } // repeated .google.protobuf.DescriptorProto nested_type = 3; @@ -3872,15 +3877,17 @@ const char* DescriptorProto::_InternalParse(const char* begin, const char* end, if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::DescriptorProto::_InternalParse; object = msg->add_nested_type(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 26 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 26 && (ptr += 1)); break; } // repeated .google.protobuf.EnumDescriptorProto enum_type = 4; @@ -3888,15 +3895,17 @@ const char* DescriptorProto::_InternalParse(const char* begin, const char* end, if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::EnumDescriptorProto::_InternalParse; object = msg->add_enum_type(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 34 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 34 && (ptr += 1)); break; } // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5; @@ -3904,15 +3913,17 @@ const char* DescriptorProto::_InternalParse(const char* begin, const char* end, if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::DescriptorProto_ExtensionRange::_InternalParse; object = msg->add_extension_range(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 42 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 42 && (ptr += 1)); break; } // repeated .google.protobuf.FieldDescriptorProto extension = 6; @@ -3920,27 +3931,31 @@ const char* DescriptorProto::_InternalParse(const char* begin, const char* end, if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::FieldDescriptorProto::_InternalParse; object = msg->add_extension(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 50 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 50 && (ptr += 1)); break; } // optional .google.protobuf.MessageOptions options = 7; case 7: { if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::MessageOptions::_InternalParse; object = msg->mutable_options(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; break; } @@ -3949,15 +3964,17 @@ const char* DescriptorProto::_InternalParse(const char* begin, const char* end, if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::OneofDescriptorProto::_InternalParse; object = msg->add_oneof_decl(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 66 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 66 && (ptr += 1)); break; } // repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9; @@ -3965,15 +3982,17 @@ const char* DescriptorProto::_InternalParse(const char* begin, const char* end, if (static_cast<::google::protobuf::uint8>(tag) != 74) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::DescriptorProto_ReservedRange::_InternalParse; object = msg->add_reserved_range(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 74 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 74 && (ptr += 1)); break; } // repeated string reserved_name = 10; @@ -3981,7 +4000,7 @@ const char* DescriptorProto::_InternalParse(const char* begin, const char* end, if (static_cast<::google::protobuf::uint8>(tag) != 82) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.DescriptorProto.reserved_name"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->add_reserved_name(); @@ -3989,16 +4008,17 @@ const char* DescriptorProto::_InternalParse(const char* begin, const char* end, object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 82 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 82 && (ptr += 1)); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -4009,8 +4029,6 @@ const char* DescriptorProto::_InternalParse(const char* begin, const char* end, } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -4022,7 +4040,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool DescriptorProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.DescriptorProto) for (;;) { @@ -4691,29 +4709,31 @@ const char* ExtensionRangeOptions::_InternalParse(const char* begin, const char* while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; case 999: { if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::UninterpretedOption::_InternalParse; object = msg->add_uninterpreted_option(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 65535) == 16058 && (ptr += 2)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 65535) == 16058 && (ptr += 2)); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } if ((8000u <= tag)) { @@ -4731,8 +4751,6 @@ const char* ExtensionRangeOptions::_InternalParse(const char* begin, const char* } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -4744,7 +4762,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool ExtensionRangeOptions::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.ExtensionRangeOptions) for (;;) { @@ -5176,14 +5194,13 @@ const char* FieldDescriptorProto::_InternalParse(const char* begin, const char* while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional string name = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FieldDescriptorProto.name"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_name(); @@ -5191,15 +5208,15 @@ const char* FieldDescriptorProto::_InternalParse(const char* begin, const char* object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional string extendee = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FieldDescriptorProto.extendee"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_extendee(); @@ -5207,8 +5224,8 @@ const char* FieldDescriptorProto::_InternalParse(const char* begin, const char* object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional int32 number = 3; @@ -5216,7 +5233,7 @@ const char* FieldDescriptorProto::_InternalParse(const char* begin, const char* if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->set_number(value); break; @@ -5226,7 +5243,7 @@ const char* FieldDescriptorProto::_InternalParse(const char* begin, const char* if (static_cast<::google::protobuf::uint8>(tag) != 32) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); if (!::google::protobuf::FieldDescriptorProto_Label_IsValid(val)) { ::google::protobuf::internal::WriteVarint(4, val, msg->mutable_unknown_fields()); break; @@ -5240,7 +5257,7 @@ const char* FieldDescriptorProto::_InternalParse(const char* begin, const char* if (static_cast<::google::protobuf::uint8>(tag) != 40) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); if (!::google::protobuf::FieldDescriptorProto_Type_IsValid(val)) { ::google::protobuf::internal::WriteVarint(5, val, msg->mutable_unknown_fields()); break; @@ -5253,7 +5270,7 @@ const char* FieldDescriptorProto::_InternalParse(const char* begin, const char* case 6: { if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FieldDescriptorProto.type_name"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_type_name(); @@ -5261,15 +5278,15 @@ const char* FieldDescriptorProto::_InternalParse(const char* begin, const char* object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional string default_value = 7; case 7: { if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FieldDescriptorProto.default_value"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_default_value(); @@ -5277,20 +5294,22 @@ const char* FieldDescriptorProto::_InternalParse(const char* begin, const char* object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional .google.protobuf.FieldOptions options = 8; case 8: { if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::FieldOptions::_InternalParse; object = msg->mutable_options(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; break; } @@ -5299,7 +5318,7 @@ const char* FieldDescriptorProto::_InternalParse(const char* begin, const char* if (static_cast<::google::protobuf::uint8>(tag) != 72) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->set_oneof_index(value); break; @@ -5308,7 +5327,7 @@ const char* FieldDescriptorProto::_InternalParse(const char* begin, const char* case 10: { if (static_cast<::google::protobuf::uint8>(tag) != 82) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FieldDescriptorProto.json_name"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_json_name(); @@ -5316,14 +5335,15 @@ const char* FieldDescriptorProto::_InternalParse(const char* begin, const char* object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -5334,8 +5354,6 @@ const char* FieldDescriptorProto::_InternalParse(const char* begin, const char* } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -5347,7 +5365,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool FieldDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FieldDescriptorProto) for (;;) { @@ -6070,14 +6088,13 @@ const char* OneofDescriptorProto::_InternalParse(const char* begin, const char* while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional string name = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.OneofDescriptorProto.name"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_name(); @@ -6085,27 +6102,30 @@ const char* OneofDescriptorProto::_InternalParse(const char* begin, const char* object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional .google.protobuf.OneofOptions options = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::OneofOptions::_InternalParse; object = msg->mutable_options(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -6116,8 +6136,6 @@ const char* OneofDescriptorProto::_InternalParse(const char* begin, const char* } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -6129,7 +6147,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool OneofDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.OneofDescriptorProto) for (;;) { @@ -6470,15 +6488,14 @@ const char* EnumDescriptorProto_EnumReservedRange::_InternalParse(const char* be while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional int32 start = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->set_start(value); break; @@ -6488,15 +6505,16 @@ const char* EnumDescriptorProto_EnumReservedRange::_InternalParse(const char* be if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->set_end(value); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -6507,8 +6525,6 @@ const char* EnumDescriptorProto_EnumReservedRange::_InternalParse(const char* be } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -6520,7 +6536,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool EnumDescriptorProto_EnumReservedRange::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumDescriptorProto.EnumReservedRange) for (;;) { @@ -6890,14 +6906,13 @@ const char* EnumDescriptorProto::_InternalParse(const char* begin, const char* e while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional string name = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.EnumDescriptorProto.name"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_name(); @@ -6905,8 +6920,8 @@ const char* EnumDescriptorProto::_InternalParse(const char* begin, const char* e object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // repeated .google.protobuf.EnumValueDescriptorProto value = 2; @@ -6914,27 +6929,31 @@ const char* EnumDescriptorProto::_InternalParse(const char* begin, const char* e if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::EnumValueDescriptorProto::_InternalParse; object = msg->add_value(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 18 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1)); break; } // optional .google.protobuf.EnumOptions options = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::EnumOptions::_InternalParse; object = msg->mutable_options(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; break; } @@ -6943,15 +6962,17 @@ const char* EnumDescriptorProto::_InternalParse(const char* begin, const char* e if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::EnumDescriptorProto_EnumReservedRange::_InternalParse; object = msg->add_reserved_range(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 34 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 34 && (ptr += 1)); break; } // repeated string reserved_name = 5; @@ -6959,7 +6980,7 @@ const char* EnumDescriptorProto::_InternalParse(const char* begin, const char* e if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.EnumDescriptorProto.reserved_name"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->add_reserved_name(); @@ -6967,16 +6988,17 @@ const char* EnumDescriptorProto::_InternalParse(const char* begin, const char* e object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 42 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 42 && (ptr += 1)); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -6987,8 +7009,6 @@ const char* EnumDescriptorProto::_InternalParse(const char* begin, const char* e } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -7000,7 +7020,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool EnumDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumDescriptorProto) for (;;) { @@ -7512,14 +7532,13 @@ const char* EnumValueDescriptorProto::_InternalParse(const char* begin, const ch while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional string name = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.EnumValueDescriptorProto.name"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_name(); @@ -7527,8 +7546,8 @@ const char* EnumValueDescriptorProto::_InternalParse(const char* begin, const ch object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional int32 number = 2; @@ -7536,7 +7555,7 @@ const char* EnumValueDescriptorProto::_InternalParse(const char* begin, const ch if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->set_number(value); break; @@ -7545,19 +7564,22 @@ const char* EnumValueDescriptorProto::_InternalParse(const char* begin, const ch case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::EnumValueOptions::_InternalParse; object = msg->mutable_options(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -7568,8 +7590,6 @@ const char* EnumValueDescriptorProto::_InternalParse(const char* begin, const ch } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -7581,7 +7601,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool EnumValueDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumValueDescriptorProto) for (;;) { @@ -7995,14 +8015,13 @@ const char* ServiceDescriptorProto::_InternalParse(const char* begin, const char while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional string name = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.ServiceDescriptorProto.name"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_name(); @@ -8010,8 +8029,8 @@ const char* ServiceDescriptorProto::_InternalParse(const char* begin, const char object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // repeated .google.protobuf.MethodDescriptorProto method = 2; @@ -8019,34 +8038,39 @@ const char* ServiceDescriptorProto::_InternalParse(const char* begin, const char if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::MethodDescriptorProto::_InternalParse; object = msg->add_method(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 18 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1)); break; } // optional .google.protobuf.ServiceOptions options = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::ServiceOptions::_InternalParse; object = msg->mutable_options(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -8057,8 +8081,6 @@ const char* ServiceDescriptorProto::_InternalParse(const char* begin, const char } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -8070,7 +8092,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool ServiceDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.ServiceDescriptorProto) for (;;) { @@ -8531,14 +8553,13 @@ const char* MethodDescriptorProto::_InternalParse(const char* begin, const char* while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional string name = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.MethodDescriptorProto.name"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_name(); @@ -8546,15 +8567,15 @@ const char* MethodDescriptorProto::_InternalParse(const char* begin, const char* object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional string input_type = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.MethodDescriptorProto.input_type"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_input_type(); @@ -8562,15 +8583,15 @@ const char* MethodDescriptorProto::_InternalParse(const char* begin, const char* object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional string output_type = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.MethodDescriptorProto.output_type"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_output_type(); @@ -8578,20 +8599,22 @@ const char* MethodDescriptorProto::_InternalParse(const char* begin, const char* object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional .google.protobuf.MethodOptions options = 4; case 4: { if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::MethodOptions::_InternalParse; object = msg->mutable_options(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; break; } @@ -8600,7 +8623,7 @@ const char* MethodDescriptorProto::_InternalParse(const char* begin, const char* if (static_cast<::google::protobuf::uint8>(tag) != 40) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_client_streaming(value); break; @@ -8610,15 +8633,16 @@ const char* MethodDescriptorProto::_InternalParse(const char* begin, const char* if (static_cast<::google::protobuf::uint8>(tag) != 48) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_server_streaming(value); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -8629,8 +8653,6 @@ const char* MethodDescriptorProto::_InternalParse(const char* begin, const char* } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -8642,7 +8664,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool MethodDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.MethodDescriptorProto) for (;;) { @@ -9336,14 +9358,13 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional string java_package = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.java_package"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_java_package(); @@ -9351,15 +9372,15 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional string java_outer_classname = 8; case 8: { if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.java_outer_classname"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_java_outer_classname(); @@ -9367,8 +9388,8 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED]; @@ -9376,7 +9397,7 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void if (static_cast<::google::protobuf::uint8>(tag) != 72) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); if (!::google::protobuf::FileOptions_OptimizeMode_IsValid(val)) { ::google::protobuf::internal::WriteVarint(9, val, msg->mutable_unknown_fields()); break; @@ -9390,7 +9411,7 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void if (static_cast<::google::protobuf::uint8>(tag) != 80) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_java_multiple_files(value); break; @@ -9399,7 +9420,7 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void case 11: { if (static_cast<::google::protobuf::uint8>(tag) != 90) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.go_package"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_go_package(); @@ -9407,8 +9428,8 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional bool cc_generic_services = 16 [default = false]; @@ -9416,7 +9437,7 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void if (static_cast<::google::protobuf::uint8>(tag) != 128) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_cc_generic_services(value); break; @@ -9426,7 +9447,7 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void if (static_cast<::google::protobuf::uint8>(tag) != 136) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_java_generic_services(value); break; @@ -9436,7 +9457,7 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void if (static_cast<::google::protobuf::uint8>(tag) != 144) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_py_generic_services(value); break; @@ -9446,7 +9467,7 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void if (static_cast<::google::protobuf::uint8>(tag) != 160) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_java_generate_equals_and_hash(value); break; @@ -9456,7 +9477,7 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void if (static_cast<::google::protobuf::uint8>(tag) != 184) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_deprecated(value); break; @@ -9466,7 +9487,7 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void if (static_cast<::google::protobuf::uint8>(tag) != 216) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_java_string_check_utf8(value); break; @@ -9476,7 +9497,7 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void if (static_cast<::google::protobuf::uint8>(tag) != 248) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_cc_enable_arenas(value); break; @@ -9485,7 +9506,7 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void case 36: { if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.objc_class_prefix"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_objc_class_prefix(); @@ -9493,15 +9514,15 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional string csharp_namespace = 37; case 37: { if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.csharp_namespace"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_csharp_namespace(); @@ -9509,15 +9530,15 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional string swift_prefix = 39; case 39: { if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.swift_prefix"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_swift_prefix(); @@ -9525,15 +9546,15 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional string php_class_prefix = 40; case 40: { if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.php_class_prefix"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_php_class_prefix(); @@ -9541,15 +9562,15 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional string php_namespace = 41; case 41: { if (static_cast<::google::protobuf::uint8>(tag) != 74) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.php_namespace"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_php_namespace(); @@ -9557,8 +9578,8 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional bool php_generic_services = 42 [default = false]; @@ -9566,7 +9587,7 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void if (static_cast<::google::protobuf::uint8>(tag) != 80) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_php_generic_services(value); break; @@ -9575,7 +9596,7 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void case 44: { if (static_cast<::google::protobuf::uint8>(tag) != 98) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.php_metadata_namespace"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_php_metadata_namespace(); @@ -9583,15 +9604,15 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional string ruby_package = 45; case 45: { if (static_cast<::google::protobuf::uint8>(tag) != 106) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.ruby_package"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_ruby_package(); @@ -9599,8 +9620,8 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; @@ -9608,21 +9629,24 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::UninterpretedOption::_InternalParse; object = msg->add_uninterpreted_option(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 65535) == 16058 && (ptr += 2)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 65535) == 16058 && (ptr += 2)); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } if ((8000u <= tag)) { @@ -9640,8 +9664,6 @@ const char* FileOptions::_InternalParse(const char* begin, const char* end, void } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -9653,7 +9675,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool FileOptions::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FileOptions) for (;;) { @@ -10804,15 +10826,14 @@ const char* MessageOptions::_InternalParse(const char* begin, const char* end, v while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional bool message_set_wire_format = 1 [default = false]; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_message_set_wire_format(value); break; @@ -10822,7 +10843,7 @@ const char* MessageOptions::_InternalParse(const char* begin, const char* end, v if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_no_standard_descriptor_accessor(value); break; @@ -10832,7 +10853,7 @@ const char* MessageOptions::_InternalParse(const char* begin, const char* end, v if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_deprecated(value); break; @@ -10842,7 +10863,7 @@ const char* MessageOptions::_InternalParse(const char* begin, const char* end, v if (static_cast<::google::protobuf::uint8>(tag) != 56) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_map_entry(value); break; @@ -10852,21 +10873,24 @@ const char* MessageOptions::_InternalParse(const char* begin, const char* end, v if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::UninterpretedOption::_InternalParse; object = msg->add_uninterpreted_option(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 65535) == 16058 && (ptr += 2)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 65535) == 16058 && (ptr += 2)); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } if ((8000u <= tag)) { @@ -10884,8 +10908,6 @@ const char* MessageOptions::_InternalParse(const char* begin, const char* end, v } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -10897,7 +10919,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool MessageOptions::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.MessageOptions) for (;;) { @@ -11369,15 +11391,14 @@ const char* FieldOptions::_InternalParse(const char* begin, const char* end, voi while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING]; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); if (!::google::protobuf::FieldOptions_CType_IsValid(val)) { ::google::protobuf::internal::WriteVarint(1, val, msg->mutable_unknown_fields()); break; @@ -11391,7 +11412,7 @@ const char* FieldOptions::_InternalParse(const char* begin, const char* end, voi if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_packed(value); break; @@ -11401,7 +11422,7 @@ const char* FieldOptions::_InternalParse(const char* begin, const char* end, voi if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_deprecated(value); break; @@ -11411,7 +11432,7 @@ const char* FieldOptions::_InternalParse(const char* begin, const char* end, voi if (static_cast<::google::protobuf::uint8>(tag) != 40) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_lazy(value); break; @@ -11421,7 +11442,7 @@ const char* FieldOptions::_InternalParse(const char* begin, const char* end, voi if (static_cast<::google::protobuf::uint8>(tag) != 48) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); if (!::google::protobuf::FieldOptions_JSType_IsValid(val)) { ::google::protobuf::internal::WriteVarint(6, val, msg->mutable_unknown_fields()); break; @@ -11435,7 +11456,7 @@ const char* FieldOptions::_InternalParse(const char* begin, const char* end, voi if (static_cast<::google::protobuf::uint8>(tag) != 80) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_weak(value); break; @@ -11445,21 +11466,24 @@ const char* FieldOptions::_InternalParse(const char* begin, const char* end, voi if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::UninterpretedOption::_InternalParse; object = msg->add_uninterpreted_option(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 65535) == 16058 && (ptr += 2)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 65535) == 16058 && (ptr += 2)); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } if ((8000u <= tag)) { @@ -11477,8 +11501,6 @@ const char* FieldOptions::_InternalParse(const char* begin, const char* end, voi } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -11490,7 +11512,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool FieldOptions::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FieldOptions) for (;;) { @@ -12008,29 +12030,31 @@ const char* OneofOptions::_InternalParse(const char* begin, const char* end, voi while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; case 999: { if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::UninterpretedOption::_InternalParse; object = msg->add_uninterpreted_option(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 65535) == 16058 && (ptr += 2)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 65535) == 16058 && (ptr += 2)); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } if ((8000u <= tag)) { @@ -12048,8 +12072,6 @@ const char* OneofOptions::_InternalParse(const char* begin, const char* end, voi } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -12061,7 +12083,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool OneofOptions::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.OneofOptions) for (;;) { @@ -12377,15 +12399,14 @@ const char* EnumOptions::_InternalParse(const char* begin, const char* end, void while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional bool allow_alias = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_allow_alias(value); break; @@ -12395,7 +12416,7 @@ const char* EnumOptions::_InternalParse(const char* begin, const char* end, void if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_deprecated(value); break; @@ -12405,21 +12426,24 @@ const char* EnumOptions::_InternalParse(const char* begin, const char* end, void if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::UninterpretedOption::_InternalParse; object = msg->add_uninterpreted_option(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 65535) == 16058 && (ptr += 2)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 65535) == 16058 && (ptr += 2)); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } if ((8000u <= tag)) { @@ -12437,8 +12461,6 @@ const char* EnumOptions::_InternalParse(const char* begin, const char* end, void } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -12450,7 +12472,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool EnumOptions::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumOptions) for (;;) { @@ -12829,15 +12851,14 @@ const char* EnumValueOptions::_InternalParse(const char* begin, const char* end, while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional bool deprecated = 1 [default = false]; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_deprecated(value); break; @@ -12847,21 +12868,24 @@ const char* EnumValueOptions::_InternalParse(const char* begin, const char* end, if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::UninterpretedOption::_InternalParse; object = msg->add_uninterpreted_option(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 65535) == 16058 && (ptr += 2)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 65535) == 16058 && (ptr += 2)); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } if ((8000u <= tag)) { @@ -12879,8 +12903,6 @@ const char* EnumValueOptions::_InternalParse(const char* begin, const char* end, } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -12892,7 +12914,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool EnumValueOptions::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumValueOptions) for (;;) { @@ -13233,15 +13255,14 @@ const char* ServiceOptions::_InternalParse(const char* begin, const char* end, v while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional bool deprecated = 33 [default = false]; case 33: { if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_deprecated(value); break; @@ -13251,21 +13272,24 @@ const char* ServiceOptions::_InternalParse(const char* begin, const char* end, v if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::UninterpretedOption::_InternalParse; object = msg->add_uninterpreted_option(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 65535) == 16058 && (ptr += 2)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 65535) == 16058 && (ptr += 2)); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } if ((8000u <= tag)) { @@ -13283,8 +13307,6 @@ const char* ServiceOptions::_InternalParse(const char* begin, const char* end, v } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -13296,7 +13318,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool ServiceOptions::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.ServiceOptions) for (;;) { @@ -13650,15 +13672,14 @@ const char* MethodOptions::_InternalParse(const char* begin, const char* end, vo while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // optional bool deprecated = 33 [default = false]; case 33: { if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_deprecated(value); break; @@ -13668,7 +13689,7 @@ const char* MethodOptions::_InternalParse(const char* begin, const char* end, vo if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); if (!::google::protobuf::MethodOptions_IdempotencyLevel_IsValid(val)) { ::google::protobuf::internal::WriteVarint(34, val, msg->mutable_unknown_fields()); break; @@ -13682,21 +13703,24 @@ const char* MethodOptions::_InternalParse(const char* begin, const char* end, vo if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::UninterpretedOption::_InternalParse; object = msg->add_uninterpreted_option(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 65535) == 16058 && (ptr += 2)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 65535) == 16058 && (ptr += 2)); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } if ((8000u <= tag)) { @@ -13714,8 +13738,6 @@ const char* MethodOptions::_InternalParse(const char* begin, const char* end, vo } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -13727,7 +13749,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool MethodOptions::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.MethodOptions) for (;;) { @@ -14123,14 +14145,13 @@ const char* UninterpretedOption_NamePart::_InternalParse(const char* begin, cons while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // required string name_part = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.UninterpretedOption.NamePart.name_part"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_name_part(); @@ -14138,8 +14159,8 @@ const char* UninterpretedOption_NamePart::_InternalParse(const char* begin, cons object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // required bool is_extension = 2; @@ -14147,15 +14168,16 @@ const char* UninterpretedOption_NamePart::_InternalParse(const char* begin, cons if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); bool value = val; msg->set_is_extension(value); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -14166,8 +14188,6 @@ const char* UninterpretedOption_NamePart::_InternalParse(const char* begin, cons } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -14179,7 +14199,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool UninterpretedOption_NamePart::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.UninterpretedOption.NamePart) for (;;) { @@ -14585,30 +14605,31 @@ const char* UninterpretedOption::_InternalParse(const char* begin, const char* e while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // repeated .google.protobuf.UninterpretedOption.NamePart name = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::UninterpretedOption_NamePart::_InternalParse; object = msg->add_name(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 18 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1)); break; } // optional string identifier_value = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.UninterpretedOption.identifier_value"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_identifier_value(); @@ -14616,8 +14637,8 @@ const char* UninterpretedOption::_InternalParse(const char* begin, const char* e object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional uint64 positive_int_value = 4; @@ -14625,7 +14646,7 @@ const char* UninterpretedOption::_InternalParse(const char* begin, const char* e if (static_cast<::google::protobuf::uint8>(tag) != 32) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::uint64 value = val; msg->set_positive_int_value(value); break; @@ -14635,7 +14656,7 @@ const char* UninterpretedOption::_InternalParse(const char* begin, const char* e if (static_cast<::google::protobuf::uint8>(tag) != 40) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int64 value = val; msg->set_negative_int_value(value); break; @@ -14653,22 +14674,21 @@ const char* UninterpretedOption::_InternalParse(const char* begin, const char* e case 7: { if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::internal::StringParser; ::std::string* str = msg->mutable_string_value(); str->clear(); object = str; if (size > end - ptr) goto len_delim_till_end; - auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + str->append(ptr, size); + ptr += size; break; } // optional string aggregate_value = 8; case 8: { if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.UninterpretedOption.aggregate_value"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_aggregate_value(); @@ -14676,14 +14696,15 @@ const char* UninterpretedOption::_InternalParse(const char* begin, const char* e object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -14694,8 +14715,6 @@ const char* UninterpretedOption::_InternalParse(const char* begin, const char* e } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -14707,7 +14726,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool UninterpretedOption::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.UninterpretedOption) for (;;) { @@ -15262,60 +15281,59 @@ const char* SourceCodeInfo_Location::_InternalParse(const char* begin, const cha while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // repeated int32 path = 1 [packed = true]; case 1: { if (static_cast<::google::protobuf::uint8>(tag) == 10) { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::internal::PackedInt32Parser; object = msg->mutable_path(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } else if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual; do { ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->add_path(value); if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 8 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 8 && (ptr += 1)); break; } // repeated int32 span = 2 [packed = true]; case 2: { if (static_cast<::google::protobuf::uint8>(tag) == 18) { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::internal::PackedInt32Parser; object = msg->mutable_span(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } else if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual; do { ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->add_span(value); if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 16 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 16 && (ptr += 1)); break; } // optional string leading_comments = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.SourceCodeInfo.Location.leading_comments"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_leading_comments(); @@ -15323,15 +15341,15 @@ const char* SourceCodeInfo_Location::_InternalParse(const char* begin, const cha object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional string trailing_comments = 4; case 4: { if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.SourceCodeInfo.Location.trailing_comments"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_trailing_comments(); @@ -15339,8 +15357,8 @@ const char* SourceCodeInfo_Location::_InternalParse(const char* begin, const cha object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // repeated string leading_detached_comments = 6; @@ -15348,7 +15366,7 @@ const char* SourceCodeInfo_Location::_InternalParse(const char* begin, const cha if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.SourceCodeInfo.Location.leading_detached_comments"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->add_leading_detached_comments(); @@ -15356,16 +15374,17 @@ const char* SourceCodeInfo_Location::_InternalParse(const char* begin, const cha object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 50 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 50 && (ptr += 1)); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -15376,8 +15395,6 @@ const char* SourceCodeInfo_Location::_InternalParse(const char* begin, const cha } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -15389,7 +15406,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool SourceCodeInfo_Location::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.SourceCodeInfo.Location) for (;;) { @@ -15886,29 +15903,31 @@ const char* SourceCodeInfo::_InternalParse(const char* begin, const char* end, v while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // repeated .google.protobuf.SourceCodeInfo.Location location = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::SourceCodeInfo_Location::_InternalParse; object = msg->add_location(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 10 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1)); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -15919,8 +15938,6 @@ const char* SourceCodeInfo::_InternalParse(const char* begin, const char* end, v } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -15932,7 +15949,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool SourceCodeInfo::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.SourceCodeInfo) for (;;) { @@ -16240,37 +16257,36 @@ const char* GeneratedCodeInfo_Annotation::_InternalParse(const char* begin, cons while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // repeated int32 path = 1 [packed = true]; case 1: { if (static_cast<::google::protobuf::uint8>(tag) == 10) { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::internal::PackedInt32Parser; object = msg->mutable_path(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } else if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual; do { ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->add_path(value); if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 8 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 8 && (ptr += 1)); break; } // optional string source_file = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.GeneratedCodeInfo.Annotation.source_file"); parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify; ::std::string* str = msg->mutable_source_file(); @@ -16278,8 +16294,8 @@ const char* GeneratedCodeInfo_Annotation::_InternalParse(const char* begin, cons object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } // optional int32 begin = 3; @@ -16287,7 +16303,7 @@ const char* GeneratedCodeInfo_Annotation::_InternalParse(const char* begin, cons if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->set_begin(value); break; @@ -16297,15 +16313,16 @@ const char* GeneratedCodeInfo_Annotation::_InternalParse(const char* begin, cons if (static_cast<::google::protobuf::uint8>(tag) != 32) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->set_end(value); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -16316,8 +16333,6 @@ const char* GeneratedCodeInfo_Annotation::_InternalParse(const char* begin, cons } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -16329,7 +16344,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.GeneratedCodeInfo.Annotation) for (;;) { @@ -16744,29 +16759,31 @@ const char* GeneratedCodeInfo::_InternalParse(const char* begin, const char* end while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::GeneratedCodeInfo_Annotation::_InternalParse; object = msg->add_annotation(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; + bool ok = ctx->ParseExactRange({parser_till_end, object}, + ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 10 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1)); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -16777,8 +16794,6 @@ const char* GeneratedCodeInfo::_InternalParse(const char* begin, const char* end } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -16790,7 +16805,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool GeneratedCodeInfo::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.GeneratedCodeInfo) for (;;) { @@ -16984,88 +16999,89 @@ void GeneratedCodeInfo::InternalSwap(GeneratedCodeInfo* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileDescriptorSet* Arena::CreateMaybeMessage< ::google::protobuf::FileDescriptorSet >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::FileDescriptorSet* Arena::CreateMaybeMessage< ::google::protobuf::FileDescriptorSet >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::FileDescriptorSet >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::FileDescriptorProto >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::FileDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::FileDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::FileDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto_ExtensionRange >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto_ExtensionRange >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::DescriptorProto_ExtensionRange >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto_ReservedRange >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto_ReservedRange >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::DescriptorProto_ReservedRange >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::DescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::DescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ExtensionRangeOptions* Arena::CreateMaybeMessage< ::google::protobuf::ExtensionRangeOptions >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::ExtensionRangeOptions* Arena::CreateMaybeMessage< ::google::protobuf::ExtensionRangeOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::ExtensionRangeOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::FieldDescriptorProto >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::FieldDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::FieldDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::FieldDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::OneofDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::OneofDescriptorProto >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::OneofDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::OneofDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::OneofDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMaybeMessage< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMaybeMessage< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::EnumDescriptorProto >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::EnumDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::EnumDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::EnumDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::EnumValueDescriptorProto >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::EnumValueDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::EnumValueDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ServiceDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::ServiceDescriptorProto >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::ServiceDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::ServiceDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::ServiceDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MethodDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::MethodDescriptorProto >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::MethodDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::MethodDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::MethodDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileOptions* Arena::CreateMaybeMessage< ::google::protobuf::FileOptions >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::FileOptions* Arena::CreateMaybeMessage< ::google::protobuf::FileOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::FileOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MessageOptions* Arena::CreateMaybeMessage< ::google::protobuf::MessageOptions >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::MessageOptions* Arena::CreateMaybeMessage< ::google::protobuf::MessageOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::MessageOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldOptions* Arena::CreateMaybeMessage< ::google::protobuf::FieldOptions >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::FieldOptions* Arena::CreateMaybeMessage< ::google::protobuf::FieldOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::FieldOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::OneofOptions* Arena::CreateMaybeMessage< ::google::protobuf::OneofOptions >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::OneofOptions* Arena::CreateMaybeMessage< ::google::protobuf::OneofOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::OneofOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumOptions* Arena::CreateMaybeMessage< ::google::protobuf::EnumOptions >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::EnumOptions* Arena::CreateMaybeMessage< ::google::protobuf::EnumOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::EnumOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValueOptions* Arena::CreateMaybeMessage< ::google::protobuf::EnumValueOptions >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::EnumValueOptions* Arena::CreateMaybeMessage< ::google::protobuf::EnumValueOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::EnumValueOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ServiceOptions* Arena::CreateMaybeMessage< ::google::protobuf::ServiceOptions >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::ServiceOptions* Arena::CreateMaybeMessage< ::google::protobuf::ServiceOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::ServiceOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MethodOptions* Arena::CreateMaybeMessage< ::google::protobuf::MethodOptions >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::MethodOptions* Arena::CreateMaybeMessage< ::google::protobuf::MethodOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::MethodOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMaybeMessage< ::google::protobuf::UninterpretedOption_NamePart >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMaybeMessage< ::google::protobuf::UninterpretedOption_NamePart >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::UninterpretedOption_NamePart >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UninterpretedOption* Arena::CreateMaybeMessage< ::google::protobuf::UninterpretedOption >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::UninterpretedOption* Arena::CreateMaybeMessage< ::google::protobuf::UninterpretedOption >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::UninterpretedOption >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMaybeMessage< ::google::protobuf::SourceCodeInfo_Location >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMaybeMessage< ::google::protobuf::SourceCodeInfo_Location >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::SourceCodeInfo_Location >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceCodeInfo* Arena::CreateMaybeMessage< ::google::protobuf::SourceCodeInfo >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::SourceCodeInfo* Arena::CreateMaybeMessage< ::google::protobuf::SourceCodeInfo >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::SourceCodeInfo >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMaybeMessage< ::google::protobuf::GeneratedCodeInfo_Annotation >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMaybeMessage< ::google::protobuf::GeneratedCodeInfo_Annotation >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::GeneratedCodeInfo_Annotation >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::GeneratedCodeInfo* Arena::CreateMaybeMessage< ::google::protobuf::GeneratedCodeInfo >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::GeneratedCodeInfo* Arena::CreateMaybeMessage< ::google::protobuf::GeneratedCodeInfo >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::GeneratedCodeInfo >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope) +#include diff --git a/src/google/protobuf/descriptor.pb.h b/src/google/protobuf/descriptor.pb.h index 3459a073c4..c4b8365251 100644 --- a/src/google/protobuf/descriptor.pb.h +++ b/src/google/protobuf/descriptor.pb.h @@ -7,18 +7,19 @@ #include #include -#include -#if GOOGLE_PROTOBUF_VERSION < 3006000 +#include +#if PROTOBUF_VERSION < 3006001 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3006001 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include @@ -33,131 +34,131 @@ #include // @@protoc_insertion_point(includes) #include -#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto LIBPROTOBUF_EXPORT +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto PROTOBUF_EXPORT // Internal implementation detail -- do not use these members. -struct LIBPROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fdescriptor_2eproto { +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fdescriptor_2eproto { static const ::google::protobuf::internal::ParseTableField entries[] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::AuxillaryParseTableField aux[] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::ParseTable schema[27] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::FieldMetadata field_metadata[]; static const ::google::protobuf::internal::SerializationTable serialization_table[]; static const ::google::protobuf::uint32 offsets[]; }; -void LIBPROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fdescriptor_2eproto(); +void PROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fdescriptor_2eproto(); namespace google { namespace protobuf { class DescriptorProto; class DescriptorProtoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern DescriptorProtoDefaultTypeInternal _DescriptorProto_default_instance_; +PROTOBUF_EXPORT extern DescriptorProtoDefaultTypeInternal _DescriptorProto_default_instance_; class DescriptorProto_ExtensionRange; class DescriptorProto_ExtensionRangeDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern DescriptorProto_ExtensionRangeDefaultTypeInternal _DescriptorProto_ExtensionRange_default_instance_; +PROTOBUF_EXPORT extern DescriptorProto_ExtensionRangeDefaultTypeInternal _DescriptorProto_ExtensionRange_default_instance_; class DescriptorProto_ReservedRange; class DescriptorProto_ReservedRangeDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern DescriptorProto_ReservedRangeDefaultTypeInternal _DescriptorProto_ReservedRange_default_instance_; +PROTOBUF_EXPORT extern DescriptorProto_ReservedRangeDefaultTypeInternal _DescriptorProto_ReservedRange_default_instance_; class EnumDescriptorProto; class EnumDescriptorProtoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern EnumDescriptorProtoDefaultTypeInternal _EnumDescriptorProto_default_instance_; +PROTOBUF_EXPORT extern EnumDescriptorProtoDefaultTypeInternal _EnumDescriptorProto_default_instance_; class EnumDescriptorProto_EnumReservedRange; class EnumDescriptorProto_EnumReservedRangeDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern EnumDescriptorProto_EnumReservedRangeDefaultTypeInternal _EnumDescriptorProto_EnumReservedRange_default_instance_; +PROTOBUF_EXPORT extern EnumDescriptorProto_EnumReservedRangeDefaultTypeInternal _EnumDescriptorProto_EnumReservedRange_default_instance_; class EnumOptions; class EnumOptionsDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern EnumOptionsDefaultTypeInternal _EnumOptions_default_instance_; +PROTOBUF_EXPORT extern EnumOptionsDefaultTypeInternal _EnumOptions_default_instance_; class EnumValueDescriptorProto; class EnumValueDescriptorProtoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern EnumValueDescriptorProtoDefaultTypeInternal _EnumValueDescriptorProto_default_instance_; +PROTOBUF_EXPORT extern EnumValueDescriptorProtoDefaultTypeInternal _EnumValueDescriptorProto_default_instance_; class EnumValueOptions; class EnumValueOptionsDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern EnumValueOptionsDefaultTypeInternal _EnumValueOptions_default_instance_; +PROTOBUF_EXPORT extern EnumValueOptionsDefaultTypeInternal _EnumValueOptions_default_instance_; class ExtensionRangeOptions; class ExtensionRangeOptionsDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern ExtensionRangeOptionsDefaultTypeInternal _ExtensionRangeOptions_default_instance_; +PROTOBUF_EXPORT extern ExtensionRangeOptionsDefaultTypeInternal _ExtensionRangeOptions_default_instance_; class FieldDescriptorProto; class FieldDescriptorProtoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern FieldDescriptorProtoDefaultTypeInternal _FieldDescriptorProto_default_instance_; +PROTOBUF_EXPORT extern FieldDescriptorProtoDefaultTypeInternal _FieldDescriptorProto_default_instance_; class FieldOptions; class FieldOptionsDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern FieldOptionsDefaultTypeInternal _FieldOptions_default_instance_; +PROTOBUF_EXPORT extern FieldOptionsDefaultTypeInternal _FieldOptions_default_instance_; class FileDescriptorProto; class FileDescriptorProtoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern FileDescriptorProtoDefaultTypeInternal _FileDescriptorProto_default_instance_; +PROTOBUF_EXPORT extern FileDescriptorProtoDefaultTypeInternal _FileDescriptorProto_default_instance_; class FileDescriptorSet; class FileDescriptorSetDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern FileDescriptorSetDefaultTypeInternal _FileDescriptorSet_default_instance_; +PROTOBUF_EXPORT extern FileDescriptorSetDefaultTypeInternal _FileDescriptorSet_default_instance_; class FileOptions; class FileOptionsDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern FileOptionsDefaultTypeInternal _FileOptions_default_instance_; +PROTOBUF_EXPORT extern FileOptionsDefaultTypeInternal _FileOptions_default_instance_; class GeneratedCodeInfo; class GeneratedCodeInfoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern GeneratedCodeInfoDefaultTypeInternal _GeneratedCodeInfo_default_instance_; +PROTOBUF_EXPORT extern GeneratedCodeInfoDefaultTypeInternal _GeneratedCodeInfo_default_instance_; class GeneratedCodeInfo_Annotation; class GeneratedCodeInfo_AnnotationDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern GeneratedCodeInfo_AnnotationDefaultTypeInternal _GeneratedCodeInfo_Annotation_default_instance_; +PROTOBUF_EXPORT extern GeneratedCodeInfo_AnnotationDefaultTypeInternal _GeneratedCodeInfo_Annotation_default_instance_; class MessageOptions; class MessageOptionsDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern MessageOptionsDefaultTypeInternal _MessageOptions_default_instance_; +PROTOBUF_EXPORT extern MessageOptionsDefaultTypeInternal _MessageOptions_default_instance_; class MethodDescriptorProto; class MethodDescriptorProtoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern MethodDescriptorProtoDefaultTypeInternal _MethodDescriptorProto_default_instance_; +PROTOBUF_EXPORT extern MethodDescriptorProtoDefaultTypeInternal _MethodDescriptorProto_default_instance_; class MethodOptions; class MethodOptionsDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern MethodOptionsDefaultTypeInternal _MethodOptions_default_instance_; +PROTOBUF_EXPORT extern MethodOptionsDefaultTypeInternal _MethodOptions_default_instance_; class OneofDescriptorProto; class OneofDescriptorProtoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern OneofDescriptorProtoDefaultTypeInternal _OneofDescriptorProto_default_instance_; +PROTOBUF_EXPORT extern OneofDescriptorProtoDefaultTypeInternal _OneofDescriptorProto_default_instance_; class OneofOptions; class OneofOptionsDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern OneofOptionsDefaultTypeInternal _OneofOptions_default_instance_; +PROTOBUF_EXPORT extern OneofOptionsDefaultTypeInternal _OneofOptions_default_instance_; class ServiceDescriptorProto; class ServiceDescriptorProtoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern ServiceDescriptorProtoDefaultTypeInternal _ServiceDescriptorProto_default_instance_; +PROTOBUF_EXPORT extern ServiceDescriptorProtoDefaultTypeInternal _ServiceDescriptorProto_default_instance_; class ServiceOptions; class ServiceOptionsDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern ServiceOptionsDefaultTypeInternal _ServiceOptions_default_instance_; +PROTOBUF_EXPORT extern ServiceOptionsDefaultTypeInternal _ServiceOptions_default_instance_; class SourceCodeInfo; class SourceCodeInfoDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern SourceCodeInfoDefaultTypeInternal _SourceCodeInfo_default_instance_; +PROTOBUF_EXPORT extern SourceCodeInfoDefaultTypeInternal _SourceCodeInfo_default_instance_; class SourceCodeInfo_Location; class SourceCodeInfo_LocationDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern SourceCodeInfo_LocationDefaultTypeInternal _SourceCodeInfo_Location_default_instance_; +PROTOBUF_EXPORT extern SourceCodeInfo_LocationDefaultTypeInternal _SourceCodeInfo_Location_default_instance_; class UninterpretedOption; class UninterpretedOptionDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern UninterpretedOptionDefaultTypeInternal _UninterpretedOption_default_instance_; +PROTOBUF_EXPORT extern UninterpretedOptionDefaultTypeInternal _UninterpretedOption_default_instance_; class UninterpretedOption_NamePart; class UninterpretedOption_NamePartDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern UninterpretedOption_NamePartDefaultTypeInternal _UninterpretedOption_NamePart_default_instance_; -template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto_ExtensionRange>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto_ReservedRange>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::EnumDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMaybeMessage<::google::protobuf::EnumDescriptorProto_EnumReservedRange>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumOptions* Arena::CreateMaybeMessage<::google::protobuf::EnumOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::EnumValueDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValueOptions* Arena::CreateMaybeMessage<::google::protobuf::EnumValueOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::ExtensionRangeOptions* Arena::CreateMaybeMessage<::google::protobuf::ExtensionRangeOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::FieldDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldOptions* Arena::CreateMaybeMessage<::google::protobuf::FieldOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::FileDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileDescriptorSet* Arena::CreateMaybeMessage<::google::protobuf::FileDescriptorSet>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileOptions* Arena::CreateMaybeMessage<::google::protobuf::FileOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo* Arena::CreateMaybeMessage<::google::protobuf::GeneratedCodeInfo>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMaybeMessage<::google::protobuf::GeneratedCodeInfo_Annotation>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::MessageOptions* Arena::CreateMaybeMessage<::google::protobuf::MessageOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::MethodDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::MethodDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::MethodOptions* Arena::CreateMaybeMessage<::google::protobuf::MethodOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::OneofDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::OneofDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::OneofOptions* Arena::CreateMaybeMessage<::google::protobuf::OneofOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::ServiceDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::ServiceDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::ServiceOptions* Arena::CreateMaybeMessage<::google::protobuf::ServiceOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo* Arena::CreateMaybeMessage<::google::protobuf::SourceCodeInfo>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMaybeMessage<::google::protobuf::SourceCodeInfo_Location>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::UninterpretedOption* Arena::CreateMaybeMessage<::google::protobuf::UninterpretedOption>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMaybeMessage<::google::protobuf::UninterpretedOption_NamePart>(Arena*); +PROTOBUF_EXPORT extern UninterpretedOption_NamePartDefaultTypeInternal _UninterpretedOption_NamePart_default_instance_; +template<> PROTOBUF_EXPORT ::google::protobuf::DescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto_ExtensionRange>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto_ReservedRange>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::EnumDescriptorProto>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMaybeMessage<::google::protobuf::EnumDescriptorProto_EnumReservedRange>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::EnumOptions* Arena::CreateMaybeMessage<::google::protobuf::EnumOptions>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::EnumValueDescriptorProto>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::EnumValueOptions* Arena::CreateMaybeMessage<::google::protobuf::EnumValueOptions>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::ExtensionRangeOptions* Arena::CreateMaybeMessage<::google::protobuf::ExtensionRangeOptions>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::FieldDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::FieldDescriptorProto>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::FieldOptions* Arena::CreateMaybeMessage<::google::protobuf::FieldOptions>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::FileDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::FileDescriptorProto>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::FileDescriptorSet* Arena::CreateMaybeMessage<::google::protobuf::FileDescriptorSet>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::FileOptions* Arena::CreateMaybeMessage<::google::protobuf::FileOptions>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo* Arena::CreateMaybeMessage<::google::protobuf::GeneratedCodeInfo>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMaybeMessage<::google::protobuf::GeneratedCodeInfo_Annotation>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::MessageOptions* Arena::CreateMaybeMessage<::google::protobuf::MessageOptions>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::MethodDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::MethodDescriptorProto>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::MethodOptions* Arena::CreateMaybeMessage<::google::protobuf::MethodOptions>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::OneofDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::OneofDescriptorProto>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::OneofOptions* Arena::CreateMaybeMessage<::google::protobuf::OneofOptions>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::ServiceDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::ServiceDescriptorProto>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::ServiceOptions* Arena::CreateMaybeMessage<::google::protobuf::ServiceOptions>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo* Arena::CreateMaybeMessage<::google::protobuf::SourceCodeInfo>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMaybeMessage<::google::protobuf::SourceCodeInfo_Location>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::UninterpretedOption* Arena::CreateMaybeMessage<::google::protobuf::UninterpretedOption>(Arena*); +template<> PROTOBUF_EXPORT ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMaybeMessage<::google::protobuf::UninterpretedOption_NamePart>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -183,12 +184,12 @@ enum FieldDescriptorProto_Type { FieldDescriptorProto_Type_TYPE_SINT32 = 17, FieldDescriptorProto_Type_TYPE_SINT64 = 18 }; -LIBPROTOBUF_EXPORT bool FieldDescriptorProto_Type_IsValid(int value); +PROTOBUF_EXPORT bool FieldDescriptorProto_Type_IsValid(int value); const FieldDescriptorProto_Type FieldDescriptorProto_Type_Type_MIN = FieldDescriptorProto_Type_TYPE_DOUBLE; const FieldDescriptorProto_Type FieldDescriptorProto_Type_Type_MAX = FieldDescriptorProto_Type_TYPE_SINT64; const int FieldDescriptorProto_Type_Type_ARRAYSIZE = FieldDescriptorProto_Type_Type_MAX + 1; -LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Type_descriptor(); +PROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Type_descriptor(); inline const ::std::string& FieldDescriptorProto_Type_Name(FieldDescriptorProto_Type value) { return ::google::protobuf::internal::NameOfEnum( FieldDescriptorProto_Type_descriptor(), value); @@ -203,12 +204,12 @@ enum FieldDescriptorProto_Label { FieldDescriptorProto_Label_LABEL_REQUIRED = 2, FieldDescriptorProto_Label_LABEL_REPEATED = 3 }; -LIBPROTOBUF_EXPORT bool FieldDescriptorProto_Label_IsValid(int value); +PROTOBUF_EXPORT bool FieldDescriptorProto_Label_IsValid(int value); const FieldDescriptorProto_Label FieldDescriptorProto_Label_Label_MIN = FieldDescriptorProto_Label_LABEL_OPTIONAL; const FieldDescriptorProto_Label FieldDescriptorProto_Label_Label_MAX = FieldDescriptorProto_Label_LABEL_REPEATED; const int FieldDescriptorProto_Label_Label_ARRAYSIZE = FieldDescriptorProto_Label_Label_MAX + 1; -LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Label_descriptor(); +PROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Label_descriptor(); inline const ::std::string& FieldDescriptorProto_Label_Name(FieldDescriptorProto_Label value) { return ::google::protobuf::internal::NameOfEnum( FieldDescriptorProto_Label_descriptor(), value); @@ -223,12 +224,12 @@ enum FileOptions_OptimizeMode { FileOptions_OptimizeMode_CODE_SIZE = 2, FileOptions_OptimizeMode_LITE_RUNTIME = 3 }; -LIBPROTOBUF_EXPORT bool FileOptions_OptimizeMode_IsValid(int value); +PROTOBUF_EXPORT bool FileOptions_OptimizeMode_IsValid(int value); const FileOptions_OptimizeMode FileOptions_OptimizeMode_OptimizeMode_MIN = FileOptions_OptimizeMode_SPEED; const FileOptions_OptimizeMode FileOptions_OptimizeMode_OptimizeMode_MAX = FileOptions_OptimizeMode_LITE_RUNTIME; const int FileOptions_OptimizeMode_OptimizeMode_ARRAYSIZE = FileOptions_OptimizeMode_OptimizeMode_MAX + 1; -LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FileOptions_OptimizeMode_descriptor(); +PROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FileOptions_OptimizeMode_descriptor(); inline const ::std::string& FileOptions_OptimizeMode_Name(FileOptions_OptimizeMode value) { return ::google::protobuf::internal::NameOfEnum( FileOptions_OptimizeMode_descriptor(), value); @@ -243,12 +244,12 @@ enum FieldOptions_CType { FieldOptions_CType_CORD = 1, FieldOptions_CType_STRING_PIECE = 2 }; -LIBPROTOBUF_EXPORT bool FieldOptions_CType_IsValid(int value); +PROTOBUF_EXPORT bool FieldOptions_CType_IsValid(int value); const FieldOptions_CType FieldOptions_CType_CType_MIN = FieldOptions_CType_STRING; const FieldOptions_CType FieldOptions_CType_CType_MAX = FieldOptions_CType_STRING_PIECE; const int FieldOptions_CType_CType_ARRAYSIZE = FieldOptions_CType_CType_MAX + 1; -LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldOptions_CType_descriptor(); +PROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldOptions_CType_descriptor(); inline const ::std::string& FieldOptions_CType_Name(FieldOptions_CType value) { return ::google::protobuf::internal::NameOfEnum( FieldOptions_CType_descriptor(), value); @@ -263,12 +264,12 @@ enum FieldOptions_JSType { FieldOptions_JSType_JS_STRING = 1, FieldOptions_JSType_JS_NUMBER = 2 }; -LIBPROTOBUF_EXPORT bool FieldOptions_JSType_IsValid(int value); +PROTOBUF_EXPORT bool FieldOptions_JSType_IsValid(int value); const FieldOptions_JSType FieldOptions_JSType_JSType_MIN = FieldOptions_JSType_JS_NORMAL; const FieldOptions_JSType FieldOptions_JSType_JSType_MAX = FieldOptions_JSType_JS_NUMBER; const int FieldOptions_JSType_JSType_ARRAYSIZE = FieldOptions_JSType_JSType_MAX + 1; -LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldOptions_JSType_descriptor(); +PROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldOptions_JSType_descriptor(); inline const ::std::string& FieldOptions_JSType_Name(FieldOptions_JSType value) { return ::google::protobuf::internal::NameOfEnum( FieldOptions_JSType_descriptor(), value); @@ -283,12 +284,12 @@ enum MethodOptions_IdempotencyLevel { MethodOptions_IdempotencyLevel_NO_SIDE_EFFECTS = 1, MethodOptions_IdempotencyLevel_IDEMPOTENT = 2 }; -LIBPROTOBUF_EXPORT bool MethodOptions_IdempotencyLevel_IsValid(int value); +PROTOBUF_EXPORT bool MethodOptions_IdempotencyLevel_IsValid(int value); const MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel_IdempotencyLevel_MIN = MethodOptions_IdempotencyLevel_IDEMPOTENCY_UNKNOWN; const MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel_IdempotencyLevel_MAX = MethodOptions_IdempotencyLevel_IDEMPOTENT; const int MethodOptions_IdempotencyLevel_IdempotencyLevel_ARRAYSIZE = MethodOptions_IdempotencyLevel_IdempotencyLevel_MAX + 1; -LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* MethodOptions_IdempotencyLevel_descriptor(); +PROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* MethodOptions_IdempotencyLevel_descriptor(); inline const ::std::string& MethodOptions_IdempotencyLevel_Name(MethodOptions_IdempotencyLevel value) { return ::google::protobuf::internal::NameOfEnum( MethodOptions_IdempotencyLevel_descriptor(), value); @@ -300,7 +301,7 @@ inline bool MethodOptions_IdempotencyLevel_Parse( } // =================================================================== -class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileDescriptorSet) */ { +class PROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileDescriptorSet) */ { public: FileDescriptorSet(); virtual ~FileDescriptorSet(); @@ -440,7 +441,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileDescriptorProto) */ { +class PROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileDescriptorProto) */ { public: FileDescriptorProto(); virtual ~FileDescriptorProto(); @@ -769,7 +770,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto.ExtensionRange) */ { +class PROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto.ExtensionRange) */ { public: DescriptorProto_ExtensionRange(); virtual ~DescriptorProto_ExtensionRange(); @@ -925,7 +926,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto.ReservedRange) */ { +class PROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto.ReservedRange) */ { public: DescriptorProto_ReservedRange(); virtual ~DescriptorProto_ReservedRange(); @@ -1068,7 +1069,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto) */ { +class PROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto) */ { public: DescriptorProto(); virtual ~DescriptorProto(); @@ -1350,7 +1351,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ExtensionRangeOptions) */ { +class PROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ExtensionRangeOptions) */ { public: ExtensionRangeOptions(); virtual ~ExtensionRangeOptions(); @@ -1493,7 +1494,7 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldDescriptorProto) */ { +class PROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldDescriptorProto) */ { public: FieldDescriptorProto(); virtual ~FieldDescriptorProto(); @@ -1876,7 +1877,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.OneofDescriptorProto) */ { +class PROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.OneofDescriptorProto) */ { public: OneofDescriptorProto(); virtual ~OneofDescriptorProto(); @@ -2041,7 +2042,7 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumDescriptorProto.EnumReservedRange) */ { +class PROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumDescriptorProto.EnumReservedRange) */ { public: EnumDescriptorProto_EnumReservedRange(); virtual ~EnumDescriptorProto_EnumReservedRange(); @@ -2184,7 +2185,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumDescriptorProto) */ { +class PROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumDescriptorProto) */ { public: EnumDescriptorProto(); virtual ~EnumDescriptorProto(); @@ -2400,7 +2401,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValueDescriptorProto) */ { +class PROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValueDescriptorProto) */ { public: EnumValueDescriptorProto(); virtual ~EnumValueDescriptorProto(); @@ -2573,7 +2574,7 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ServiceDescriptorProto) */ { +class PROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ServiceDescriptorProto) */ { public: ServiceDescriptorProto(); virtual ~ServiceDescriptorProto(); @@ -2751,7 +2752,7 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MethodDescriptorProto) */ { +class PROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MethodDescriptorProto) */ { public: MethodDescriptorProto(); virtual ~MethodDescriptorProto(); @@ -2982,7 +2983,7 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileOptions) */ { +class PROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileOptions) */ { public: FileOptions(); virtual ~FileOptions(); @@ -3383,11 +3384,11 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p void set_java_multiple_files(bool value); // optional bool java_generate_equals_and_hash = 20 [deprecated = true]; - GOOGLE_PROTOBUF_DEPRECATED bool has_java_generate_equals_and_hash() const; - GOOGLE_PROTOBUF_DEPRECATED void clear_java_generate_equals_and_hash(); - GOOGLE_PROTOBUF_DEPRECATED static const int kJavaGenerateEqualsAndHashFieldNumber = 20; - GOOGLE_PROTOBUF_DEPRECATED bool java_generate_equals_and_hash() const; - GOOGLE_PROTOBUF_DEPRECATED void set_java_generate_equals_and_hash(bool value); + PROTOBUF_DEPRECATED bool has_java_generate_equals_and_hash() const; + PROTOBUF_DEPRECATED void clear_java_generate_equals_and_hash(); + PROTOBUF_DEPRECATED static const int kJavaGenerateEqualsAndHashFieldNumber = 20; + PROTOBUF_DEPRECATED bool java_generate_equals_and_hash() const; + PROTOBUF_DEPRECATED void set_java_generate_equals_and_hash(bool value); // optional bool java_string_check_utf8 = 27 [default = false]; bool has_java_string_check_utf8() const; @@ -3483,7 +3484,7 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MessageOptions) */ { +class PROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MessageOptions) */ { public: MessageOptions(); virtual ~MessageOptions(); @@ -3658,7 +3659,7 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldOptions) */ { +class PROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldOptions) */ { public: FieldOptions(); virtual ~FieldOptions(); @@ -3905,7 +3906,7 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@ }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.OneofOptions) */ { +class PROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.OneofOptions) */ { public: OneofOptions(); virtual ~OneofOptions(); @@ -4048,7 +4049,7 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@ }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumOptions) */ { +class PROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumOptions) */ { public: EnumOptions(); virtual ~EnumOptions(); @@ -4207,7 +4208,7 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValueOptions) */ { +class PROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValueOptions) */ { public: EnumValueOptions(); virtual ~EnumValueOptions(); @@ -4358,7 +4359,7 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message / }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ServiceOptions) */ { +class PROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ServiceOptions) */ { public: ServiceOptions(); virtual ~ServiceOptions(); @@ -4509,7 +4510,7 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MethodOptions) */ { +class PROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MethodOptions) */ { public: MethodOptions(); virtual ~MethodOptions(); @@ -4696,7 +4697,7 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @ }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UninterpretedOption.NamePart) */ { +class PROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UninterpretedOption.NamePart) */ { public: UninterpretedOption_NamePart(); virtual ~UninterpretedOption_NamePart(); @@ -4859,7 +4860,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UninterpretedOption) */ { +class PROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UninterpretedOption) */ { public: UninterpretedOption(); virtual ~UninterpretedOption(); @@ -5100,7 +5101,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceCodeInfo.Location) */ { +class PROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceCodeInfo.Location) */ { public: SourceCodeInfo_Location(); virtual ~SourceCodeInfo_Location(); @@ -5328,7 +5329,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceCodeInfo) */ { +class PROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceCodeInfo) */ { public: SourceCodeInfo(); virtual ~SourceCodeInfo(); @@ -5470,7 +5471,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.GeneratedCodeInfo.Annotation) */ { +class PROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.GeneratedCodeInfo.Annotation) */ { public: GeneratedCodeInfo_Annotation(); virtual ~GeneratedCodeInfo_Annotation(); @@ -5652,7 +5653,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.GeneratedCodeInfo) */ { +class PROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.GeneratedCodeInfo) */ { public: GeneratedCodeInfo(); virtual ~GeneratedCodeInfo(); @@ -10535,7 +10536,7 @@ inline bool UninterpretedOption::has_positive_int_value() const { return (_has_bits_[0] & 0x00000008u) != 0; } inline void UninterpretedOption::clear_positive_int_value() { - positive_int_value_ = GOOGLE_PROTOBUF_ULONGLONG(0); + positive_int_value_ = PROTOBUF_ULONGLONG(0); _has_bits_[0] &= ~0x00000008u; } inline ::google::protobuf::uint64 UninterpretedOption::positive_int_value() const { @@ -10553,7 +10554,7 @@ inline bool UninterpretedOption::has_negative_int_value() const { return (_has_bits_[0] & 0x00000010u) != 0; } inline void UninterpretedOption::clear_negative_int_value() { - negative_int_value_ = GOOGLE_PROTOBUF_LONGLONG(0); + negative_int_value_ = PROTOBUF_LONGLONG(0); _has_bits_[0] &= ~0x00000010u; } inline ::google::protobuf::int64 UninterpretedOption::negative_int_value() const { diff --git a/src/google/protobuf/descriptor_database.h b/src/google/protobuf/descriptor_database.h index 0a87a14743..48892af10a 100644 --- a/src/google/protobuf/descriptor_database.h +++ b/src/google/protobuf/descriptor_database.h @@ -44,6 +44,12 @@ #include #include +#include + +#ifdef SWIG +#define PROTOBUF_EXPORT +#endif + namespace google { namespace protobuf { @@ -62,27 +68,27 @@ class MergedDescriptorDatabase; // calling DescriptorPool::BuildFile() for each one. Instead, a DescriptorPool // can be created which wraps a DescriptorDatabase and only builds particular // descriptors when they are needed. -class LIBPROTOBUF_EXPORT DescriptorDatabase { +class PROTOBUF_EXPORT DescriptorDatabase { public: inline DescriptorDatabase() {} virtual ~DescriptorDatabase(); // Find a file by file name. Fills in in *output and returns true if found. // Otherwise, returns false, leaving the contents of *output undefined. - virtual bool FindFileByName(const string& filename, + virtual bool FindFileByName(const std::string& filename, FileDescriptorProto* output) = 0; // Find the file that declares the given fully-qualified symbol name. // If found, fills in *output and returns true, otherwise returns false // and leaves *output undefined. - virtual bool FindFileContainingSymbol(const string& symbol_name, + virtual bool FindFileContainingSymbol(const std::string& symbol_name, FileDescriptorProto* output) = 0; // Find the file which defines an extension extending the given message type // with the given field number. If found, fills in *output and returns true, // otherwise returns false and leaves *output undefined. containing_type // must be a fully-qualified type name. - virtual bool FindFileContainingExtension(const string& containing_type, + virtual bool FindFileContainingExtension(const std::string& containing_type, int field_number, FileDescriptorProto* output) = 0; @@ -96,7 +102,7 @@ class LIBPROTOBUF_EXPORT DescriptorDatabase { // // This method has a default implementation that always returns // false. - virtual bool FindAllExtensionNumbers(const string& /* extendee_type */, + virtual bool FindAllExtensionNumbers(const std::string& /* extendee_type */, std::vector* /* output */) { return false; } @@ -110,7 +116,7 @@ class LIBPROTOBUF_EXPORT DescriptorDatabase { // // This method has a default implementation that always returns // false. - virtual bool FindAllFileNames(std::vector* output) { + virtual bool FindAllFileNames(std::vector* output) { return false; } @@ -139,7 +145,7 @@ class LIBPROTOBUF_EXPORT DescriptorDatabase { // FileDescriptor::CopyTo()) will always use fully-qualified names for all // types. You only need to worry if you are constructing FileDescriptorProtos // yourself, or are calling compiler::Parser directly. -class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase { +class PROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase { public: SimpleDescriptorDatabase(); ~SimpleDescriptorDatabase() override; @@ -154,17 +160,17 @@ class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase { bool AddAndOwn(const FileDescriptorProto* file); // implements DescriptorDatabase ----------------------------------- - bool FindFileByName(const string& filename, + bool FindFileByName(const std::string& filename, FileDescriptorProto* output) override; - bool FindFileContainingSymbol(const string& symbol_name, + bool FindFileContainingSymbol(const std::string& symbol_name, FileDescriptorProto* output) override; - bool FindFileContainingExtension(const string& containing_type, + bool FindFileContainingExtension(const std::string& containing_type, int field_number, FileDescriptorProto* output) override; - bool FindAllExtensionNumbers(const string& extendee_type, + bool FindAllExtensionNumbers(const std::string& extendee_type, std::vector* output) override; - bool FindAllFileNames(std::vector* output) override; + bool FindAllFileNames(std::vector* output) override; private: // So that it can use DescriptorIndex. @@ -179,23 +185,23 @@ class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase { // to the index. bool AddFile(const FileDescriptorProto& file, Value value); - bool AddSymbol(const string& name, Value value); + bool AddSymbol(const std::string& name, Value value); bool AddNestedExtensions(const DescriptorProto& message_type, Value value); bool AddExtension(const FieldDescriptorProto& field, Value value); - Value FindFile(const string& filename); - Value FindSymbol(const string& name); - Value FindExtension(const string& containing_type, int field_number); - bool FindAllExtensionNumbers(const string& containing_type, + Value FindFile(const std::string& filename); + Value FindSymbol(const std::string& name); + Value FindExtension(const std::string& containing_type, int field_number); + bool FindAllExtensionNumbers(const std::string& containing_type, std::vector* output); - void FindAllFileNames(std::vector* output); + void FindAllFileNames(std::vector* output); private: - std::map by_name_; - std::map by_symbol_; - std::map, Value> by_extension_; + std::map by_name_; + std::map by_symbol_; + std::map, Value> by_extension_; // Invariant: The by_symbol_ map does not contain any symbols which are // prefixes of other symbols in the map. For example, "foo.bar" is a @@ -250,17 +256,17 @@ class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase { // Find the last entry in the by_symbol_ map whose key is less than or // equal to the given name. - typename std::map::iterator FindLastLessOrEqual( - const string& name); + typename std::map::iterator FindLastLessOrEqual( + const std::string& name); // True if either the arguments are equal or super_symbol identifies a // parent symbol of sub_symbol (e.g. "foo.bar" is a parent of // "foo.bar.baz", but not a parent of "foo.barbaz"). - bool IsSubSymbol(const string& sub_symbol, const string& super_symbol); + bool IsSubSymbol(const std::string& sub_symbol, const std::string& super_symbol); // Returns true if and only if all characters in the name are alphanumerics, // underscores, or periods. - bool ValidateSymbolName(const string& name); + bool ValidateSymbolName(const std::string& name); }; @@ -280,7 +286,7 @@ class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase { // // The same caveats regarding FindFileContainingExtension() apply as with // SimpleDescriptorDatabase. -class LIBPROTOBUF_EXPORT EncodedDescriptorDatabase : public DescriptorDatabase { +class PROTOBUF_EXPORT EncodedDescriptorDatabase : public DescriptorDatabase { public: EncodedDescriptorDatabase(); ~EncodedDescriptorDatabase() override; @@ -298,18 +304,18 @@ class LIBPROTOBUF_EXPORT EncodedDescriptorDatabase : public DescriptorDatabase { bool AddCopy(const void* encoded_file_descriptor, int size); // Like FindFileContainingSymbol but returns only the name of the file. - bool FindNameOfFileContainingSymbol(const string& symbol_name, - string* output); + bool FindNameOfFileContainingSymbol(const std::string& symbol_name, + std::string* output); // implements DescriptorDatabase ----------------------------------- - bool FindFileByName(const string& filename, + bool FindFileByName(const std::string& filename, FileDescriptorProto* output) override; - bool FindFileContainingSymbol(const string& symbol_name, + bool FindFileContainingSymbol(const std::string& symbol_name, FileDescriptorProto* output) override; - bool FindFileContainingExtension(const string& containing_type, + bool FindFileContainingExtension(const std::string& containing_type, int field_number, FileDescriptorProto* output) override; - bool FindAllExtensionNumbers(const string& extendee_type, + bool FindAllExtensionNumbers(const std::string& extendee_type, std::vector* output) override; private: @@ -326,20 +332,20 @@ class LIBPROTOBUF_EXPORT EncodedDescriptorDatabase : public DescriptorDatabase { }; // A DescriptorDatabase that fetches files from a given pool. -class LIBPROTOBUF_EXPORT DescriptorPoolDatabase : public DescriptorDatabase { +class PROTOBUF_EXPORT DescriptorPoolDatabase : public DescriptorDatabase { public: explicit DescriptorPoolDatabase(const DescriptorPool& pool); ~DescriptorPoolDatabase() override; // implements DescriptorDatabase ----------------------------------- - bool FindFileByName(const string& filename, + bool FindFileByName(const std::string& filename, FileDescriptorProto* output) override; - bool FindFileContainingSymbol(const string& symbol_name, + bool FindFileContainingSymbol(const std::string& symbol_name, FileDescriptorProto* output) override; - bool FindFileContainingExtension(const string& containing_type, + bool FindFileContainingExtension(const std::string& containing_type, int field_number, FileDescriptorProto* output) override; - bool FindAllExtensionNumbers(const string& extendee_type, + bool FindAllExtensionNumbers(const std::string& extendee_type, std::vector* output) override; private: @@ -349,7 +355,7 @@ class LIBPROTOBUF_EXPORT DescriptorPoolDatabase : public DescriptorDatabase { // A DescriptorDatabase that wraps two or more others. It first searches the // first database and, if that fails, tries the second, and so on. -class LIBPROTOBUF_EXPORT MergedDescriptorDatabase : public DescriptorDatabase { +class PROTOBUF_EXPORT MergedDescriptorDatabase : public DescriptorDatabase { public: // Merge just two databases. The sources remain property of the caller. MergedDescriptorDatabase(DescriptorDatabase* source1, @@ -362,16 +368,16 @@ class LIBPROTOBUF_EXPORT MergedDescriptorDatabase : public DescriptorDatabase { ~MergedDescriptorDatabase() override; // implements DescriptorDatabase ----------------------------------- - bool FindFileByName(const string& filename, + bool FindFileByName(const std::string& filename, FileDescriptorProto* output) override; - bool FindFileContainingSymbol(const string& symbol_name, + bool FindFileContainingSymbol(const std::string& symbol_name, FileDescriptorProto* output) override; - bool FindFileContainingExtension(const string& containing_type, + bool FindFileContainingExtension(const std::string& containing_type, int field_number, FileDescriptorProto* output) override; // Merges the results of calling all databases. Returns true iff any // of the databases returned true. - bool FindAllExtensionNumbers(const string& extendee_type, + bool FindAllExtensionNumbers(const std::string& extendee_type, std::vector* output) override; @@ -383,4 +389,6 @@ class LIBPROTOBUF_EXPORT MergedDescriptorDatabase : public DescriptorDatabase { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_DESCRIPTOR_DATABASE_H__ diff --git a/src/google/protobuf/descriptor_unittest.cc b/src/google/protobuf/descriptor_unittest.cc index 0d16078e40..e48e440fcf 100644 --- a/src/google/protobuf/descriptor_unittest.cc +++ b/src/google/protobuf/descriptor_unittest.cc @@ -62,6 +62,8 @@ #include +#include + namespace google { namespace protobuf { @@ -2507,11 +2509,11 @@ TEST_F(MiscTest, DefaultValues) { ASSERT_TRUE(message->field(9)->has_default_value()); ASSERT_TRUE(message->field(10)->has_default_value()); - EXPECT_EQ(-1 , message->field(0)->default_value_int32 ()); - EXPECT_EQ(-GOOGLE_ULONGLONG(1000000000000), - message->field(1)->default_value_int64 ()); - EXPECT_EQ(42 , message->field(2)->default_value_uint32()); - EXPECT_EQ(GOOGLE_ULONGLONG(2000000000000), + EXPECT_EQ(-1, message->field(0)->default_value_int32()); + EXPECT_EQ(-PROTOBUF_ULONGLONG(1000000000000), + message->field(1)->default_value_int64()); + EXPECT_EQ(42, message->field(2)->default_value_uint32()); + EXPECT_EQ(PROTOBUF_ULONGLONG(2000000000000), message->field(3)->default_value_uint64()); EXPECT_EQ(4.5 , message->field(4)->default_value_float ()); EXPECT_EQ(10e100 , message->field(5)->default_value_double()); @@ -2926,11 +2928,11 @@ TEST(CustomOptions, OptionLocations) { file->FindServiceByName("TestServiceWithCustomOptions"); const MethodDescriptor* method = service->FindMethodByName("Foo"); - EXPECT_EQ(GOOGLE_LONGLONG(9876543210), + EXPECT_EQ(PROTOBUF_LONGLONG(9876543210), file->options().GetExtension(protobuf_unittest::file_opt1)); EXPECT_EQ(-56, message->options().GetExtension(protobuf_unittest::message_opt1)); - EXPECT_EQ(GOOGLE_LONGLONG(8765432109), + EXPECT_EQ(PROTOBUF_LONGLONG(8765432109), field->options().GetExtension(protobuf_unittest::field_opt1)); EXPECT_EQ(42, // Check that we get the default for an option we don't set. field->options().GetExtension(protobuf_unittest::field_opt2)); @@ -2941,7 +2943,7 @@ TEST(CustomOptions, OptionLocations) { EXPECT_EQ(123, enm->value(1)->options().GetExtension( protobuf_unittest::enum_value_opt1)); - EXPECT_EQ(GOOGLE_LONGLONG(-9876543210), + EXPECT_EQ(PROTOBUF_LONGLONG(-9876543210), service->options().GetExtension(protobuf_unittest::service_opt1)); EXPECT_EQ(protobuf_unittest::METHODOPT1_VAL2, method->options().GetExtension(protobuf_unittest::method_opt1)); diff --git a/src/google/protobuf/duration.pb.cc b/src/google/protobuf/duration.pb.cc index e9a82770c0..02602d2899 100644 --- a/src/google/protobuf/duration.pb.cc +++ b/src/google/protobuf/duration.pb.cc @@ -13,10 +13,6 @@ #include #include #include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif // @@protoc_insertion_point(includes) #include @@ -39,7 +35,7 @@ static void InitDefaultsDuration_google_2fprotobuf_2fduration_2eproto() { ::google::protobuf::Duration::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Duration_google_2fprotobuf_2fduration_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Duration_google_2fprotobuf_2fduration_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDuration_google_2fprotobuf_2fduration_2eproto}, {}}; void InitDefaults_google_2fprotobuf_2fduration_2eproto() { @@ -50,16 +46,16 @@ void InitDefaults_google_2fprotobuf_2fduration_2eproto() { constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fduration_2eproto = nullptr; constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fduration_2eproto = nullptr; -const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fduration_2eproto::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fduration_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Duration, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Duration, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Duration, seconds_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Duration, nanos_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Duration, seconds_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Duration, nanos_), }; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::google::protobuf::Duration)}, }; @@ -185,15 +181,14 @@ const char* Duration::_InternalParse(const char* begin, const char* end, void* o while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // int64 seconds = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int64 value = val; msg->set_seconds(value); break; @@ -203,15 +198,16 @@ const char* Duration::_InternalParse(const char* begin, const char* end, void* o if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual; ::google::protobuf::uint64 val; ptr = Varint::Parse64(ptr, &val); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ::google::protobuf::int32 value = val; msg->set_nanos(value); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -222,8 +218,6 @@ const char* Duration::_InternalParse(const char* begin, const char* end, void* o } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -235,7 +229,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Duration::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Duration) for (;;) { @@ -455,10 +449,11 @@ void Duration::InternalSwap(Duration* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Duration* Arena::CreateMaybeMessage< ::google::protobuf::Duration >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::Duration* Arena::CreateMaybeMessage< ::google::protobuf::Duration >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Duration >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope) +#include diff --git a/src/google/protobuf/duration.pb.h b/src/google/protobuf/duration.pb.h index 1d32e1bbbf..78d9466532 100644 --- a/src/google/protobuf/duration.pb.h +++ b/src/google/protobuf/duration.pb.h @@ -7,18 +7,19 @@ #include #include -#include -#if GOOGLE_PROTOBUF_VERSION < 3006000 +#include +#if PROTOBUF_VERSION < 3006001 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3006001 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include @@ -32,27 +33,27 @@ #include // @@protoc_insertion_point(includes) #include -#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fduration_2eproto LIBPROTOBUF_EXPORT +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fduration_2eproto PROTOBUF_EXPORT // Internal implementation detail -- do not use these members. -struct LIBPROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fduration_2eproto { +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fduration_2eproto { static const ::google::protobuf::internal::ParseTableField entries[] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::AuxillaryParseTableField aux[] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::ParseTable schema[1] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::FieldMetadata field_metadata[]; static const ::google::protobuf::internal::SerializationTable serialization_table[]; static const ::google::protobuf::uint32 offsets[]; }; -void LIBPROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fduration_2eproto(); +void PROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fduration_2eproto(); namespace google { namespace protobuf { class Duration; class DurationDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern DurationDefaultTypeInternal _Duration_default_instance_; -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Duration* Arena::CreateMaybeMessage<::google::protobuf::Duration>(Arena*); +PROTOBUF_EXPORT extern DurationDefaultTypeInternal _Duration_default_instance_; +template<> PROTOBUF_EXPORT ::google::protobuf::Duration* Arena::CreateMaybeMessage<::google::protobuf::Duration>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -60,7 +61,7 @@ namespace protobuf { // =================================================================== -class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Duration) */ { +class PROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Duration) */ { public: Duration(); virtual ~Duration(); @@ -204,7 +205,7 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot // int64 seconds = 1; inline void Duration::clear_seconds() { - seconds_ = GOOGLE_PROTOBUF_LONGLONG(0); + seconds_ = PROTOBUF_LONGLONG(0); } inline ::google::protobuf::int64 Duration::seconds() const { // @@protoc_insertion_point(field_get:google.protobuf.Duration.seconds) diff --git a/src/google/protobuf/dynamic_message.h b/src/google/protobuf/dynamic_message.h index c614ee5a22..1ea6f66f18 100644 --- a/src/google/protobuf/dynamic_message.h +++ b/src/google/protobuf/dynamic_message.h @@ -51,6 +51,8 @@ #error "You cannot SWIG proto headers" #endif +#include + namespace google { namespace protobuf { @@ -75,7 +77,7 @@ class DescriptorPool; // descriptor.h // encapsulates this "cache". All DynamicMessages of the same type created // from the same factory will share the same support data. Any Descriptors // used with a particular factory must outlive the factory. -class LIBPROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory { +class PROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory { public: // Construct a DynamicMessageFactory that will search for extensions in // the DescriptorPool in which the extendee is defined. @@ -151,7 +153,7 @@ class LIBPROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory { }; // Helper for computing a sorted list of map entries via reflection. -class LIBPROTOBUF_EXPORT DynamicMapSorter { +class PROTOBUF_EXPORT DynamicMapSorter { public: static std::vector Sort(const Message& message, int map_size, @@ -182,7 +184,7 @@ class LIBPROTOBUF_EXPORT DynamicMapSorter { } private: - class LIBPROTOBUF_EXPORT MapEntryMessageComparator { + class PROTOBUF_EXPORT MapEntryMessageComparator { public: explicit MapEntryMessageComparator(const Descriptor* descriptor) : field_(descriptor->field(0)) {} @@ -216,8 +218,8 @@ class LIBPROTOBUF_EXPORT DynamicMapSorter { return first < second; } case FieldDescriptor::CPPTYPE_STRING: { - string first = reflection->GetString(*a, field_); - string second = reflection->GetString(*b, field_); + std::string first = reflection->GetString(*a, field_); + std::string second = reflection->GetString(*b, field_); return first < second; } default: @@ -234,4 +236,6 @@ class LIBPROTOBUF_EXPORT DynamicMapSorter { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_DYNAMIC_MESSAGE_H__ diff --git a/src/google/protobuf/empty.pb.cc b/src/google/protobuf/empty.pb.cc index 5ca92661de..9d0f9ae09a 100644 --- a/src/google/protobuf/empty.pb.cc +++ b/src/google/protobuf/empty.pb.cc @@ -13,10 +13,6 @@ #include #include #include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif // @@protoc_insertion_point(includes) #include @@ -39,7 +35,7 @@ static void InitDefaultsEmpty_google_2fprotobuf_2fempty_2eproto() { ::google::protobuf::Empty::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Empty_google_2fprotobuf_2fempty_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Empty_google_2fprotobuf_2fempty_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsEmpty_google_2fprotobuf_2fempty_2eproto}, {}}; void InitDefaults_google_2fprotobuf_2fempty_2eproto() { @@ -50,14 +46,14 @@ void InitDefaults_google_2fprotobuf_2fempty_2eproto() { constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fempty_2eproto = nullptr; constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fempty_2eproto = nullptr; -const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fempty_2eproto::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fempty_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Empty, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::Empty, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ }; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::google::protobuf::Empty)}, }; @@ -171,13 +167,13 @@ const char* Empty::_InternalParse(const char* begin, const char* end, void* obje while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -188,8 +184,6 @@ const char* Empty::_InternalParse(const char* begin, const char* end, void* obje } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -201,7 +195,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Empty::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Empty) for (;;) { @@ -348,10 +342,11 @@ void Empty::InternalSwap(Empty* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Empty* Arena::CreateMaybeMessage< ::google::protobuf::Empty >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::Empty* Arena::CreateMaybeMessage< ::google::protobuf::Empty >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Empty >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope) +#include diff --git a/src/google/protobuf/empty.pb.h b/src/google/protobuf/empty.pb.h index 65f0b192f9..39b944b102 100644 --- a/src/google/protobuf/empty.pb.h +++ b/src/google/protobuf/empty.pb.h @@ -7,18 +7,19 @@ #include #include -#include -#if GOOGLE_PROTOBUF_VERSION < 3006000 +#include +#if PROTOBUF_VERSION < 3006001 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3006001 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include @@ -32,27 +33,27 @@ #include // @@protoc_insertion_point(includes) #include -#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fempty_2eproto LIBPROTOBUF_EXPORT +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fempty_2eproto PROTOBUF_EXPORT // Internal implementation detail -- do not use these members. -struct LIBPROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fempty_2eproto { +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fempty_2eproto { static const ::google::protobuf::internal::ParseTableField entries[] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::AuxillaryParseTableField aux[] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::ParseTable schema[1] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::FieldMetadata field_metadata[]; static const ::google::protobuf::internal::SerializationTable serialization_table[]; static const ::google::protobuf::uint32 offsets[]; }; -void LIBPROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fempty_2eproto(); +void PROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fempty_2eproto(); namespace google { namespace protobuf { class Empty; class EmptyDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern EmptyDefaultTypeInternal _Empty_default_instance_; -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Empty* Arena::CreateMaybeMessage<::google::protobuf::Empty>(Arena*); +PROTOBUF_EXPORT extern EmptyDefaultTypeInternal _Empty_default_instance_; +template<> PROTOBUF_EXPORT ::google::protobuf::Empty* Arena::CreateMaybeMessage<::google::protobuf::Empty>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -60,7 +61,7 @@ namespace protobuf { // =================================================================== -class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Empty) */ { +class PROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Empty) */ { public: Empty(); virtual ~Empty(); diff --git a/src/google/protobuf/extension_set.cc b/src/google/protobuf/extension_set.cc index cb40ab7188..6629ec0424 100644 --- a/src/google/protobuf/extension_set.cc +++ b/src/google/protobuf/extension_set.cc @@ -206,7 +206,7 @@ ExtensionSet::~ExtensionSet() { // Deletes all allocated extensions. if (arena_ == NULL) { ForEach([](int /* number */, Extension& ext) { ext.Free(); }); - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { delete map_.large; } else { DeleteFlatMap(map_.flat, flat_capacity_); @@ -912,8 +912,8 @@ size_t SizeOfUnion(ItX it_xs, ItX end_xs, ItY it_ys, ItY end_ys) { } // namespace void ExtensionSet::MergeFrom(const ExtensionSet& other) { - if (GOOGLE_PREDICT_TRUE(!is_large())) { - if (GOOGLE_PREDICT_TRUE(!other.is_large())) { + if (PROTOBUF_PREDICT_TRUE(!is_large())) { + if (PROTOBUF_PREDICT_TRUE(!other.is_large())) { GrowCapacity(SizeOfUnion(flat_begin(), flat_end(), other.flat_begin(), other.flat_end())); } else { @@ -1141,7 +1141,7 @@ void ExtensionSet::SwapExtension(ExtensionSet* other, bool ExtensionSet::IsInitialized() const { // Extensions are never required. However, we need to check that all // embedded messages are initialized. - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { for (const auto& kv : *map_.large) { if (!kv.second.IsInitialized()) return false; } @@ -1202,16 +1202,16 @@ bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input, #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER std::pair ExtensionSet::ParseField( - uint32 tag, ParseClosure parent, const char* begin, const char* end, + uint64 tag, ParseClosure parent, const char* begin, const char* end, const MessageLite* containing_type, internal::InternalMetadataWithArenaLite* metadata, internal::ParseContext* ctx) { GeneratedExtensionFinder finder(containing_type); - int number; + int number = tag >> 3; bool was_packed_on_wire; ExtensionInfo extension; - if (!FindExtensionInfoFromTag(tag, &finder, &number, &extension, - &was_packed_on_wire)) { + if (!FindExtensionInfoFromFieldNumber(tag & 7, number, &finder, &extension, + &was_packed_on_wire)) { return UnknownFieldParse(tag, parent, begin, end, metadata->mutable_unknown_fields(), ctx); } @@ -1265,7 +1265,7 @@ std::pair ExtensionSet::ParseField( case WireFormatLite::TYPE_##UPPERCASE: { \ uint64 value; \ ptr = Varint::Parse64(ptr, &value); \ - if (ptr == nullptr) goto error; \ + GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true)); \ if (extension.is_repeated) { \ Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \ extension.is_packed, value, extension.descriptor); \ @@ -1284,6 +1284,7 @@ std::pair ExtensionSet::ParseField( case WireFormatLite::TYPE_##UPPERCASE: { \ uint64 val; \ ptr = Varint::Parse64(ptr, &val); \ + GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true)); \ auto value = WireFormatLite::ZigZagDecode##SIZE(val); \ if (extension.is_repeated) { \ Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \ @@ -1323,7 +1324,7 @@ std::pair ExtensionSet::ParseField( case WireFormatLite::TYPE_ENUM: { uint64 val; ptr = Varint::Parse64(ptr, &val); - if (ptr == nullptr) goto error; + GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true)); int value = val; if (!extension.enum_validity_check.func( @@ -1359,9 +1360,10 @@ std::pair ExtensionSet::ParseField( *extension.message_prototype, extension.descriptor); child = {value->_ParseFunc(), value}; - if (!ctx->PrepareGroup(tag, &depth)) goto error; + bool ok = ctx->PrepareGroup(tag, &depth); + GOOGLE_PROTOBUF_ASSERT_RETURN(ok, std::make_pair(nullptr, true)); ptr = child(ptr, end, ctx); - if (!ptr) goto error; + GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true)); if (ctx->GroupContinues(depth)) goto group_continues; break; } @@ -1382,19 +1384,15 @@ std::pair ExtensionSet::ParseField( return std::make_pair(ptr, false); -error: - return std::make_pair(nullptr, true); - length_delim: uint32 size; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true)); if (size > end - ptr) goto len_delim_till_end; { auto newend = ptr + size; - if (!ctx->ParseExactRange(child, ptr, newend)) { - goto error; - } + bool ok = ctx->ParseExactRange(child, ptr, newend); + GOOGLE_PROTOBUF_ASSERT_RETURN(ok, std::make_pair(nullptr, true)); ptr = newend; } return std::make_pair(ptr, false); @@ -1641,7 +1639,7 @@ bool ExtensionSet::ParseMessageSet(io::CodedInputStream* input, void ExtensionSet::SerializeWithCachedSizes( int start_field_number, int end_field_number, io::CodedOutputStream* output) const { - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { const auto& end = map_.large->end(); for (auto it = map_.large->lower_bound(start_field_number); it != end && it->first < end_field_number; ++it) { @@ -2071,7 +2069,7 @@ bool ExtensionSet::Extension::IsInitialized() const { void ExtensionSet::LazyMessageExtension::UnusedKeyMethod() {} const ExtensionSet::Extension* ExtensionSet::FindOrNull(int key) const { - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { return FindOrNullInLargeMap(key); } const KeyValue* end = flat_end(); @@ -2094,7 +2092,7 @@ const ExtensionSet::Extension* ExtensionSet::FindOrNullInLargeMap( } ExtensionSet::Extension* ExtensionSet::FindOrNull(int key) { - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { return FindOrNullInLargeMap(key); } KeyValue* end = flat_end(); @@ -2116,7 +2114,7 @@ ExtensionSet::Extension* ExtensionSet::FindOrNullInLargeMap(int key) { } std::pair ExtensionSet::Insert(int key) { - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { auto maybe = map_.large->insert({key, Extension()}); return {&maybe.first->second, maybe.second}; } @@ -2138,7 +2136,7 @@ std::pair ExtensionSet::Insert(int key) { } void ExtensionSet::GrowCapacity(size_t minimum_new_capacity) { - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { return; // LargeMap does not have a "reserve" method. } if (flat_capacity_ >= minimum_new_capacity) { @@ -2174,7 +2172,7 @@ void ExtensionSet::GrowCapacity(size_t minimum_new_capacity) { constexpr uint16 ExtensionSet::kMaximumFlatCapacity; void ExtensionSet::Erase(int key) { - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { map_.large->erase(key); return; } @@ -2201,6 +2199,82 @@ RepeatedStringTypeTraits::GetDefaultRepeatedField() { return instance; } +void ExtensionSet::Extension::SerializeMessageSetItemWithCachedSizes( + int number, + io::CodedOutputStream* output) const { + if (type != WireFormatLite::TYPE_MESSAGE || is_repeated) { + // Not a valid MessageSet extension, but serialize it the normal way. + SerializeFieldWithCachedSizes(number, output); + return; + } + + if (is_cleared) return; + + // Start group. + output->WriteTag(WireFormatLite::kMessageSetItemStartTag); + + // Write type ID. + WireFormatLite::WriteUInt32(WireFormatLite::kMessageSetTypeIdNumber, + number, + output); + // Write message. + if (is_lazy) { + lazymessage_value->WriteMessage( + WireFormatLite::kMessageSetMessageNumber, output); + } else { + WireFormatLite::WriteMessageMaybeToArray( + WireFormatLite::kMessageSetMessageNumber, + *message_value, + output); + } + + // End group. + output->WriteTag(WireFormatLite::kMessageSetItemEndTag); +} + +size_t ExtensionSet::Extension::MessageSetItemByteSize(int number) const { + if (type != WireFormatLite::TYPE_MESSAGE || is_repeated) { + // Not a valid MessageSet extension, but compute the byte size for it the + // normal way. + return ByteSize(number); + } + + if (is_cleared) return 0; + + size_t our_size = WireFormatLite::kMessageSetItemTagsSize; + + // type_id + our_size += io::CodedOutputStream::VarintSize32(number); + + // message + size_t message_size = 0; + if (is_lazy) { + message_size = lazymessage_value->ByteSizeLong(); + } else { + message_size = message_value->ByteSizeLong(); + } + + our_size += io::CodedOutputStream::VarintSize32(message_size); + our_size += message_size; + + return our_size; +} + +void ExtensionSet::SerializeMessageSetWithCachedSizes( + io::CodedOutputStream* output) const { + ForEach([output](int number, const Extension& ext) { + ext.SerializeMessageSetItemWithCachedSizes(number, output); + }); +} + +size_t ExtensionSet::MessageSetByteSize() const { + size_t total_size = 0; + ForEach([&total_size](int number, const Extension& ext) { + total_size += ext.MessageSetItemByteSize(number); + }); + return total_size; +} + } // namespace internal } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/extension_set.h b/src/google/protobuf/extension_set.h index c22dfe07f7..b31c8c4fe6 100644 --- a/src/google/protobuf/extension_set.h +++ b/src/google/protobuf/extension_set.h @@ -47,7 +47,9 @@ #include #include +#include #include +#include #include @@ -132,7 +134,7 @@ struct ExtensionInfo { // Abstract interface for an object which looks up extension definitions. Used // when parsing. -class LIBPROTOBUF_EXPORT ExtensionFinder { +class PROTOBUF_EXPORT ExtensionFinder { public: virtual ~ExtensionFinder(); @@ -142,7 +144,7 @@ class LIBPROTOBUF_EXPORT ExtensionFinder { // Implementation of ExtensionFinder which finds extensions defined in .proto // files which have been compiled into the binary. -class LIBPROTOBUF_EXPORT GeneratedExtensionFinder : public ExtensionFinder { +class PROTOBUF_EXPORT GeneratedExtensionFinder : public ExtensionFinder { public: GeneratedExtensionFinder(const MessageLite* containing_type) : containing_type_(containing_type) {} @@ -172,7 +174,7 @@ class MessageSetFieldSkipper; // ExtensionSet. When parsing, if a tag number is encountered which is // inside one of the message type's extension ranges, the tag is passed // off to the ExtensionSet for parsing. Etc. -class LIBPROTOBUF_EXPORT ExtensionSet { +class PROTOBUF_EXPORT ExtensionSet { public: ExtensionSet(); explicit ExtensionSet(Arena* arena); @@ -249,7 +251,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet { double GetDouble(int number, double default_value) const; bool GetBool(int number, bool default_value) const; int GetEnum(int number, int default_value) const; - const string& GetString(int number, const string& default_value) const; + const std::string& GetString(int number, const std::string& default_value) const; const MessageLite& GetMessage(int number, const MessageLite& default_value) const; const MessageLite& GetMessage(int number, const Descriptor* message_type, @@ -267,8 +269,8 @@ class LIBPROTOBUF_EXPORT ExtensionSet { void SetDouble(int number, FieldType type, double value, desc); void SetBool(int number, FieldType type, bool value, desc); void SetEnum(int number, FieldType type, int value, desc); - void SetString(int number, FieldType type, const string& value, desc); - string* MutableString(int number, FieldType type, desc); + void SetString(int number, FieldType type, const std::string& value, desc); + std::string* MutableString(int number, FieldType type, desc); MessageLite* MutableMessage(int number, FieldType type, const MessageLite& prototype, desc); MessageLite* MutableMessage(const FieldDescriptor* decsriptor, @@ -319,7 +321,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet { double GetRepeatedDouble(int number, int index) const; bool GetRepeatedBool(int number, int index) const; int GetRepeatedEnum(int number, int index) const; - const string& GetRepeatedString(int number, int index) const; + const std::string& GetRepeatedString(int number, int index) const; const MessageLite& GetRepeatedMessage(int number, int index) const; void SetRepeatedInt32(int number, int index, int32 value); @@ -330,8 +332,8 @@ class LIBPROTOBUF_EXPORT ExtensionSet { void SetRepeatedDouble(int number, int index, double value); void SetRepeatedBool(int number, int index, bool value); void SetRepeatedEnum(int number, int index, int value); - void SetRepeatedString(int number, int index, const string& value); - string* MutableRepeatedString(int number, int index); + void SetRepeatedString(int number, int index, const std::string& value); + std::string* MutableRepeatedString(int number, int index); MessageLite* MutableRepeatedMessage(int number, int index); #define desc const FieldDescriptor* descriptor // avoid line wrapping @@ -343,8 +345,8 @@ class LIBPROTOBUF_EXPORT ExtensionSet { void AddDouble(int number, FieldType type, bool packed, double value, desc); void AddBool(int number, FieldType type, bool packed, bool value, desc); void AddEnum(int number, FieldType type, bool packed, int value, desc); - void AddString(int number, FieldType type, const string& value, desc); - string* AddString(int number, FieldType type, desc); + void AddString(int number, FieldType type, const std::string& value, desc); + std::string* AddString(int number, FieldType type, desc); MessageLite* AddMessage(int number, FieldType type, const MessageLite& prototype, desc); MessageLite* AddMessage(const FieldDescriptor* descriptor, @@ -396,13 +398,13 @@ class LIBPROTOBUF_EXPORT ExtensionSet { #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER // Lite parser std::pair ParseField( - uint32 tag, ParseClosure parent, const char* begin, const char* end, + uint64 tag, ParseClosure parent, const char* begin, const char* end, const MessageLite* containing_type, internal::InternalMetadataWithArenaLite* metadata, internal::ParseContext* ctx); // Full parser std::pair ParseField( - uint32 tag, ParseClosure parent, const char* begin, const char* end, + uint64 tag, ParseClosure parent, const char* begin, const char* end, const Message* containing_type, internal::InternalMetadataWithArena* metadata, internal::ParseContext* ctx); @@ -426,7 +428,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet { // FieldSkipper automatically). bool ParseMessageSet(io::CodedInputStream* input, const MessageLite* containing_type, - string* unknown_fields); + std::string* unknown_fields); bool ParseMessageSet(io::CodedInputStream* input, const Message* containing_type, UnknownFieldSet* unknown_fields); @@ -485,7 +487,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet { private: // Interface of a lazily parsed singular message extension. - class LIBPROTOBUF_EXPORT LazyMessageExtension { + class PROTOBUF_EXPORT LazyMessageExtension { public: LazyMessageExtension() {} virtual ~LazyMessageExtension() {} @@ -502,7 +504,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet { virtual bool IsInitialized() const = 0; - GOOGLE_PROTOBUF_DEPRECATED_MSG("Please use ByteSizeLong() instead") + PROTOBUF_DEPRECATED_MSG("Please use ByteSizeLong() instead") virtual int ByteSize() const { return internal::ToIntSize(ByteSizeLong()); } virtual size_t ByteSizeLong() const = 0; virtual size_t SpaceUsedLong() const = 0; @@ -539,7 +541,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet { double double_value; bool bool_value; int enum_value; - string* string_value; + std::string* string_value; MessageLite* message_value; LazyMessageExtension* lazymessage_value; @@ -551,7 +553,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet { RepeatedField* repeated_double_value; RepeatedField* repeated_bool_value; RepeatedField* repeated_enum_value; - RepeatedPtrField* repeated_string_value; + RepeatedPtrField* repeated_string_value; RepeatedPtrField* repeated_message_value; }; @@ -655,7 +657,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet { void Erase(int key); size_t Size() const { - return GOOGLE_PREDICT_FALSE(is_large()) ? map_.large->size() : flat_size_; + return PROTOBUF_PREDICT_FALSE(is_large()) ? map_.large->size() : flat_size_; } // Similar to std::for_each. @@ -671,7 +673,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet { // Applies a functor to the pairs in sorted order. template KeyValueFunctor ForEach(KeyValueFunctor func) { - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { return ForEach(map_.large->begin(), map_.large->end(), std::move(func)); } return ForEach(flat_begin(), flat_end(), std::move(func)); @@ -680,7 +682,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet { // Applies a functor to the pairs in sorted order. template KeyValueFunctor ForEach(KeyValueFunctor func) const { - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { return ForEach(map_.large->begin(), map_.large->end(), std::move(func)); } return ForEach(flat_begin(), flat_end(), std::move(func)); @@ -690,10 +692,10 @@ class LIBPROTOBUF_EXPORT ExtensionSet { void InternalExtensionMergeFrom(int number, const Extension& other_extension); #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER - bool FindExtension(uint32 tag, const Message* containing_type, + bool FindExtension(int wire_type, uint32 field, + const Message* containing_type, const internal::ParseContext* ctx, - ExtensionInfo* extension, int* number, - bool* was_packed_on_wire); + ExtensionInfo* extension, bool* was_packed_on_wire); #endif // Returns true and fills field_number and extension if extension is found. @@ -796,18 +798,54 @@ class LIBPROTOBUF_EXPORT ExtensionSet { GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionSet); }; +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +template +const char* ParseMessageSet(const char* begin, const char* end, Msg* msg, + ExtensionSet* ext, Metadata* metadata, + internal::ParseContext* ctx) { + auto ptr = begin; + int depth; + (void)depth; + while (ptr < end) { + uint32 tag; + ptr = Varint::Parse32Inline(ptr, &tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + if (tag == WireFormatLite::kMessageSetItemStartTag) { + bool ok = ctx->PrepareGroup(tag, &depth); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); + ctx->extra_parse_data().payload.clear(); + ptr = Msg::InternalParseMessageSetItem(ptr, end, msg, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + if (ctx->GroupContinues(depth)) goto group_continues; + } else { + auto res = + ext->ParseField(tag, {Msg::_InternalParse, msg}, ptr, end, + Msg::internal_default_instance(), metadata, ctx); + ptr = res.first; + if (res.second) break; + } + } + return ptr; +group_continues: + GOOGLE_DCHECK(ptr >= end); + ctx->StoreGroup({Msg::_InternalParse, msg}, + {Msg::InternalParseMessageSetItem, msg}, depth); + return ptr; +} +#endif + // These are just for convenience... inline void ExtensionSet::SetString(int number, FieldType type, - const string& value, + const std::string& value, const FieldDescriptor* descriptor) { MutableString(number, type, descriptor)->assign(value); } inline void ExtensionSet::SetRepeatedString(int number, int index, - const string& value) { + const std::string& value) { MutableRepeatedString(number, index)->assign(value); } inline void ExtensionSet::AddString(int number, FieldType type, - const string& value, + const std::string& value, const FieldDescriptor* descriptor) { AddString(number, type, descriptor)->assign(value); } @@ -922,7 +960,7 @@ class RepeatedPrimitiveTypeTraits { } }; -class LIBPROTOBUF_EXPORT RepeatedPrimitiveDefaults { +class PROTOBUF_EXPORT RepeatedPrimitiveDefaults { private: template friend class RepeatedPrimitiveTypeTraits; @@ -999,21 +1037,21 @@ PROTOBUF_DEFINE_PRIMITIVE_TYPE(bool, Bool) // StringTypeTraits // Strings support both Set() and Mutable(). -class LIBPROTOBUF_EXPORT StringTypeTraits { +class PROTOBUF_EXPORT StringTypeTraits { public: - typedef const string& ConstType; - typedef string* MutableType; + typedef const std::string& ConstType; + typedef std::string* MutableType; typedef StringTypeTraits Singular; - static inline const string& Get(int number, const ExtensionSet& set, + static inline const std::string& Get(int number, const ExtensionSet& set, ConstType default_value) { return set.GetString(number, default_value); } - static inline void Set(int number, FieldType field_type, const string& value, + static inline void Set(int number, FieldType field_type, const std::string& value, ExtensionSet* set) { set->SetString(number, field_type, value, NULL); } - static inline string* Mutable(int number, FieldType field_type, + static inline std::string* Mutable(int number, FieldType field_type, ExtensionSet* set) { return set->MutableString(number, field_type, NULL); } @@ -1024,44 +1062,44 @@ class LIBPROTOBUF_EXPORT StringTypeTraits { } }; -class LIBPROTOBUF_EXPORT RepeatedStringTypeTraits { +class PROTOBUF_EXPORT RepeatedStringTypeTraits { public: - typedef const string& ConstType; - typedef string* MutableType; + typedef const std::string& ConstType; + typedef std::string* MutableType; typedef RepeatedStringTypeTraits Repeated; - typedef RepeatedPtrField RepeatedFieldType; + typedef RepeatedPtrField RepeatedFieldType; - static inline const string& Get(int number, const ExtensionSet& set, + static inline const std::string& Get(int number, const ExtensionSet& set, int index) { return set.GetRepeatedString(number, index); } - static inline void Set(int number, int index, const string& value, + static inline void Set(int number, int index, const std::string& value, ExtensionSet* set) { set->SetRepeatedString(number, index, value); } - static inline string* Mutable(int number, int index, ExtensionSet* set) { + static inline std::string* Mutable(int number, int index, ExtensionSet* set) { return set->MutableRepeatedString(number, index); } static inline void Add(int number, FieldType field_type, bool /*is_packed*/, - const string& value, ExtensionSet* set) { + const std::string& value, ExtensionSet* set) { set->AddString(number, field_type, value, NULL); } - static inline string* Add(int number, FieldType field_type, + static inline std::string* Add(int number, FieldType field_type, ExtensionSet* set) { return set->AddString(number, field_type, NULL); } - static inline const RepeatedPtrField& GetRepeated( + static inline const RepeatedPtrField& GetRepeated( int number, const ExtensionSet& set) { - return *reinterpret_cast*>( + return *reinterpret_cast*>( set.GetRawRepeatedField(number, GetDefaultRepeatedField())); } - static inline RepeatedPtrField* MutableRepeated(int number, + static inline RepeatedPtrField* MutableRepeated(int number, FieldType field_type, bool is_packed, ExtensionSet* set) { - return reinterpret_cast*>( + return reinterpret_cast*>( set->MutableRawRepeatedField(number, field_type, is_packed, NULL)); } @@ -1325,101 +1363,101 @@ class ExtensionIdentifier { // // For similar reason, we use "_field_type" and "_is_packed" as parameter names // below, so that "field_type" and "is_packed" can be used as field names. -#define GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(CLASSNAME) \ +#define GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(CLASSNAME) \ /* Has, Size, Clear */ \ template \ inline bool HasExtension( \ - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \ return _extensions_.Has(id.number()); \ } \ \ template \ inline void ClearExtension( \ - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \ _extensions_.ClearExtension(id.number()); \ } \ \ template \ inline int ExtensionSize( \ - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \ return _extensions_.ExtensionSize(id.number()); \ } \ \ /* Singular accessors */ \ template \ inline typename _proto_TypeTraits::Singular::ConstType GetExtension( \ - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \ return _proto_TypeTraits::Get(id.number(), _extensions_, \ id.default_value()); \ } \ \ template \ inline typename _proto_TypeTraits::Singular::MutableType MutableExtension( \ - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \ return _proto_TypeTraits::Mutable(id.number(), _field_type, \ &_extensions_); \ } \ \ template \ inline void SetExtension( \ - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ typename _proto_TypeTraits::Singular::ConstType value) { \ _proto_TypeTraits::Set(id.number(), _field_type, value, &_extensions_); \ } \ \ template \ inline void SetAllocatedExtension( \ - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ typename _proto_TypeTraits::Singular::MutableType value) { \ _proto_TypeTraits::SetAllocated(id.number(), _field_type, value, \ &_extensions_); \ } \ template \ inline void UnsafeArenaSetAllocatedExtension( \ - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ typename _proto_TypeTraits::Singular::MutableType value) { \ _proto_TypeTraits::UnsafeArenaSetAllocated(id.number(), _field_type, \ value, &_extensions_); \ } \ template \ inline typename _proto_TypeTraits::Singular::MutableType ReleaseExtension( \ - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \ return _proto_TypeTraits::Release(id.number(), _field_type, \ &_extensions_); \ } \ template \ inline typename _proto_TypeTraits::Singular::MutableType \ UnsafeArenaReleaseExtension( \ - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \ return _proto_TypeTraits::UnsafeArenaRelease(id.number(), _field_type, \ &_extensions_); \ @@ -1427,49 +1465,49 @@ class ExtensionIdentifier { \ /* Repeated accessors */ \ template \ inline typename _proto_TypeTraits::Repeated::ConstType GetExtension( \ - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ int index) const { \ return _proto_TypeTraits::Get(id.number(), _extensions_, index); \ } \ \ template \ inline typename _proto_TypeTraits::Repeated::MutableType MutableExtension( \ - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ int index) { \ return _proto_TypeTraits::Mutable(id.number(), index, &_extensions_); \ } \ \ template \ inline void SetExtension( \ - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ int index, typename _proto_TypeTraits::Repeated::ConstType value) { \ _proto_TypeTraits::Set(id.number(), index, value, &_extensions_); \ } \ \ template \ inline typename _proto_TypeTraits::Repeated::MutableType AddExtension( \ - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \ return _proto_TypeTraits::Add(id.number(), _field_type, &_extensions_); \ } \ \ template \ inline void AddExtension( \ - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \ typename _proto_TypeTraits::Repeated::ConstType value) { \ _proto_TypeTraits::Add(id.number(), _field_type, _is_packed, value, \ @@ -1477,21 +1515,21 @@ class ExtensionIdentifier { } \ \ template \ inline const typename _proto_TypeTraits::Repeated::RepeatedFieldType& \ GetRepeatedExtension( \ - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \ return _proto_TypeTraits::GetRepeated(id.number(), _extensions_); \ } \ \ template \ inline typename _proto_TypeTraits::Repeated::RepeatedFieldType* \ MutableRepeatedExtension( \ - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \ return _proto_TypeTraits::MutableRepeated(id.number(), _field_type, \ _is_packed, &_extensions_); \ diff --git a/src/google/protobuf/extension_set_heavy.cc b/src/google/protobuf/extension_set_heavy.cc index 7c93c61d16..20d36ab783 100644 --- a/src/google/protobuf/extension_set_heavy.cc +++ b/src/google/protobuf/extension_set_heavy.cc @@ -45,6 +45,7 @@ #include #include #include +#include #include @@ -315,22 +316,23 @@ bool DescriptorPoolExtensionFinder::Find(int number, ExtensionInfo* output) { } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER -bool ExtensionSet::FindExtension(uint32 tag, const Message* containing_type, +bool ExtensionSet::FindExtension(int wire_type, uint32 field, + const Message* containing_type, const internal::ParseContext* ctx, - ExtensionInfo* extension, int* number, + ExtensionInfo* extension, bool* was_packed_on_wire) { if (ctx->extra_parse_data().pool == nullptr) { GeneratedExtensionFinder finder(containing_type); - if (!FindExtensionInfoFromTag(tag, &finder, number, extension, - was_packed_on_wire)) { + if (!FindExtensionInfoFromFieldNumber(wire_type, field, &finder, extension, + was_packed_on_wire)) { return false; } } else { DescriptorPoolExtensionFinder finder(ctx->extra_parse_data().pool, ctx->extra_parse_data().factory, containing_type->GetDescriptor()); - if (!FindExtensionInfoFromTag(tag, &finder, number, extension, - was_packed_on_wire)) { + if (!FindExtensionInfoFromFieldNumber(wire_type, field, &finder, extension, + was_packed_on_wire)) { return false; } } @@ -338,14 +340,14 @@ bool ExtensionSet::FindExtension(uint32 tag, const Message* containing_type, } std::pair ExtensionSet::ParseField( - uint32 tag, ParseClosure parent, const char* begin, const char* end, + uint64 tag, ParseClosure parent, const char* begin, const char* end, const Message* containing_type, internal::InternalMetadataWithArena* metadata, internal::ParseContext* ctx) { - int number; + int number = tag >> 3; bool was_packed_on_wire; ExtensionInfo extension; - if (!FindExtension(tag, containing_type, ctx, &extension, &number, + if (!FindExtension(tag & 7, number, containing_type, ctx, &extension, &was_packed_on_wire)) { return UnknownFieldParse(tag, parent, begin, end, metadata->mutable_unknown_fields(), ctx); @@ -400,7 +402,7 @@ std::pair ExtensionSet::ParseField( case WireFormatLite::TYPE_##UPPERCASE: { \ uint64 value; \ ptr = Varint::Parse64(ptr, &value); \ - if (ptr == nullptr) goto error; \ + GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true)); \ if (extension.is_repeated) { \ Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \ extension.is_packed, value, extension.descriptor); \ @@ -419,6 +421,7 @@ std::pair ExtensionSet::ParseField( case WireFormatLite::TYPE_##UPPERCASE: { \ uint64 val; \ ptr = Varint::Parse64(ptr, &val); \ + GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true)); \ auto value = WireFormatLite::ZigZagDecode##SIZE(val); \ if (extension.is_repeated) { \ Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \ @@ -458,7 +461,7 @@ std::pair ExtensionSet::ParseField( case WireFormatLite::TYPE_ENUM: { uint64 val; ptr = Varint::Parse64(ptr, &val); - if (ptr == nullptr) goto error; + GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true)); int value = val; if (!extension.enum_validity_check.func( @@ -494,9 +497,10 @@ std::pair ExtensionSet::ParseField( *extension.message_prototype, extension.descriptor); child = {value->_ParseFunc(), value}; - if (!ctx->PrepareGroup(tag, &depth)) goto error; + bool ok = ctx->PrepareGroup(tag, &depth); + GOOGLE_PROTOBUF_ASSERT_RETURN(ok, std::make_pair(nullptr, true)); ptr = child(ptr, end, ctx); - if (!ptr) goto error; + GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true)); if (ctx->GroupContinues(depth)) goto group_continues; break; } @@ -517,19 +521,15 @@ std::pair ExtensionSet::ParseField( return std::make_pair(ptr, false); -error: - return std::make_pair(nullptr, true); - length_delim: uint32 size; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true)); if (size > end - ptr) goto len_delim_till_end; { auto newend = ptr + size; - if (!ctx->ParseExactRange(child, ptr, newend)) { - goto error; - } + bool ok = ctx->ParseExactRange(child, ptr, newend); + GOOGLE_PROTOBUF_ASSERT_RETURN(ok, std::make_pair(nullptr, true)); ptr = newend; } return std::make_pair(ptr, false); @@ -570,64 +570,60 @@ const char* ExtensionSet::ParseMessageSetItem( if (tag == WireFormatLite::kMessageSetTypeIdTag) { uint32 type_id; ptr = Varint::Parse32(ptr, &type_id); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); if (ctx->extra_parse_data().payload.empty()) { tag = *ptr++; - if (tag == WireFormatLite::kMessageSetMessageTag) { - auto res = ParseField(type_id * 8 + 2, parent, ptr, end, - containing_type, metadata, ctx); - ptr = res.first; - if (res.second) break; - } else { - goto error; - } + GOOGLE_PROTOBUF_PARSER_ASSERT(tag == + WireFormatLite::kMessageSetMessageTag); + auto res = ParseField(static_cast(type_id) * 8 + 2, parent, ptr, + end, containing_type, metadata, ctx); + ptr = res.first; + if (res.second) break; } else { ExtensionInfo extension; GeneratedExtensionFinder finder(containing_type); - int number; bool was_packed_on_wire; - if (!FindExtension(type_id * 8 + 2, containing_type, ctx, &extension, - &number, &was_packed_on_wire)) { + if (!FindExtension(2, type_id, containing_type, ctx, &extension, + &was_packed_on_wire)) { metadata->mutable_unknown_fields()->AddLengthDelimited( type_id, ctx->extra_parse_data().payload); continue; } MessageLite* value = extension.is_repeated - ? AddMessage(number, WireFormatLite::TYPE_MESSAGE, + ? AddMessage(type_id, WireFormatLite::TYPE_MESSAGE, *extension.message_prototype, extension.descriptor) - : MutableMessage(number, WireFormatLite::TYPE_MESSAGE, + : MutableMessage(type_id, WireFormatLite::TYPE_MESSAGE, *extension.message_prototype, extension.descriptor); ParseClosure parser = {value->_ParseFunc(), value}; StringPiece chunk(ctx->extra_parse_data().payload.data()); - if (!ctx->ParseExactRange(parser, chunk.begin(), chunk.end())) { - return nullptr; - } + bool ok = ctx->ParseExactRange(parser, chunk.begin(), chunk.end()); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); } } else if (tag == WireFormatLite::kMessageSetItemEndTag) { - if (!ctx->ValidEndGroup(tag)) goto error; + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); break; } else if (tag == WireFormatLite::kMessageSetMessageTag) { uint32 size; ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ParseClosure child = {internal::StringParser, &ctx->extra_parse_data().payload}; if (size > end - ptr) { return ctx->StoreAndTailCall(ptr, end, parent, child, size); } else { auto newend = ptr + size; - if (!ctx->ParseExactRange(child, ptr, newend)) { - goto error; - } + bool ok = ctx->ParseExactRange(child, ptr, newend); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); ptr = newend; } } else { ptr--; ptr = Varint::Parse32(ptr, &tag); - if (ptr == nullptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); auto res = ParseField(tag, parent, ptr, end, containing_type, metadata, ctx); ptr = res.first; @@ -635,8 +631,6 @@ const char* ExtensionSet::ParseMessageSetItem( } } return ptr; -error: - return nullptr; } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER @@ -744,7 +738,7 @@ uint8* ExtensionSet::SerializeMessageSetWithCachedSizesToArray( uint8* ExtensionSet::InternalSerializeWithCachedSizesToArray( int start_field_number, int end_field_number, bool deterministic, uint8* target) const { - if (GOOGLE_PREDICT_FALSE(is_large())) { + if (PROTOBUF_PREDICT_FALSE(is_large())) { const auto& end = map_.large->end(); for (auto it = map_.large->lower_bound(start_field_number); it != end && it->first < end_field_number; ++it) { @@ -983,82 +977,6 @@ bool ExtensionSet::ParseMessageSetItem(io::CodedInputStream* input, MSFull{this, extension_finder, field_skipper}); } -void ExtensionSet::Extension::SerializeMessageSetItemWithCachedSizes( - int number, - io::CodedOutputStream* output) const { - if (type != WireFormatLite::TYPE_MESSAGE || is_repeated) { - // Not a valid MessageSet extension, but serialize it the normal way. - SerializeFieldWithCachedSizes(number, output); - return; - } - - if (is_cleared) return; - - // Start group. - output->WriteTag(WireFormatLite::kMessageSetItemStartTag); - - // Write type ID. - WireFormatLite::WriteUInt32(WireFormatLite::kMessageSetTypeIdNumber, - number, - output); - // Write message. - if (is_lazy) { - lazymessage_value->WriteMessage( - WireFormatLite::kMessageSetMessageNumber, output); - } else { - WireFormatLite::WriteMessageMaybeToArray( - WireFormatLite::kMessageSetMessageNumber, - *message_value, - output); - } - - // End group. - output->WriteTag(WireFormatLite::kMessageSetItemEndTag); -} - -size_t ExtensionSet::Extension::MessageSetItemByteSize(int number) const { - if (type != WireFormatLite::TYPE_MESSAGE || is_repeated) { - // Not a valid MessageSet extension, but compute the byte size for it the - // normal way. - return ByteSize(number); - } - - if (is_cleared) return 0; - - size_t our_size = WireFormatLite::kMessageSetItemTagsSize; - - // type_id - our_size += io::CodedOutputStream::VarintSize32(number); - - // message - size_t message_size = 0; - if (is_lazy) { - message_size = lazymessage_value->ByteSizeLong(); - } else { - message_size = message_value->ByteSizeLong(); - } - - our_size += io::CodedOutputStream::VarintSize32(message_size); - our_size += message_size; - - return our_size; -} - -void ExtensionSet::SerializeMessageSetWithCachedSizes( - io::CodedOutputStream* output) const { - ForEach([output](int number, const Extension& ext) { - ext.SerializeMessageSetItemWithCachedSizes(number, output); - }); -} - -size_t ExtensionSet::MessageSetByteSize() const { - size_t total_size = 0; - ForEach([&total_size](int number, const Extension& ext) { - total_size += ext.MessageSetItemByteSize(number); - }); - return total_size; -} - } // namespace internal } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/extension_set_unittest.cc b/src/google/protobuf/extension_set_unittest.cc index f3346c8827..af398546d3 100644 --- a/src/google/protobuf/extension_set_unittest.cc +++ b/src/google/protobuf/extension_set_unittest.cc @@ -1051,10 +1051,14 @@ TEST(ExtensionSetTest, RepeatedFields) { enum_const_iter; RepeatedField::const_iterator enum_const_end; - for (enum_const_iter = message.GetRepeatedExtension( - unittest::repeated_nested_enum_extension).begin(), - enum_const_end = message.GetRepeatedExtension( - unittest::repeated_nested_enum_extension).end(); + for (enum_const_iter = + message + .GetRepeatedExtension(unittest::repeated_nested_enum_extension) + .begin(), + enum_const_end = + message + .GetRepeatedExtension(unittest::repeated_nested_enum_extension) + .end(); enum_const_iter != enum_const_end; ++enum_const_iter) { ASSERT_EQ(*enum_const_iter, unittest::TestAllTypes::NestedEnum_MAX); } @@ -1271,7 +1275,7 @@ TEST(ExtensionSetTest, DynamicExtensions) { const Message& sub_message = message.GetReflection()->GetMessage(message, message_extension); const unittest::ForeignMessage* typed_sub_message = -#if GOOGLE_PROTOBUF_RTTI +#if PROTOBUF_RTTI dynamic_cast(&sub_message); #else static_cast(&sub_message); diff --git a/src/google/protobuf/field_mask.pb.cc b/src/google/protobuf/field_mask.pb.cc index 9791b97430..8b25299621 100644 --- a/src/google/protobuf/field_mask.pb.cc +++ b/src/google/protobuf/field_mask.pb.cc @@ -13,10 +13,6 @@ #include #include #include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif // @@protoc_insertion_point(includes) #include @@ -39,7 +35,7 @@ static void InitDefaultsFieldMask_google_2fprotobuf_2ffield_5fmask_2eproto() { ::google::protobuf::FieldMask::InitAsDefaultInstance(); } -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_FieldMask_google_2fprotobuf_2ffield_5fmask_2eproto = +PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_FieldMask_google_2fprotobuf_2ffield_5fmask_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsFieldMask_google_2fprotobuf_2ffield_5fmask_2eproto}, {}}; void InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto() { @@ -50,15 +46,15 @@ void InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto() { constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto = nullptr; constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto = nullptr; -const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldMask, _internal_metadata_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldMask, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldMask, paths_), + PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldMask, paths_), }; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { +static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::google::protobuf::FieldMask)}, }; @@ -179,15 +175,14 @@ const char* FieldMask::_InternalParse(const char* begin, const char* end, void* while (ptr < end) { ::google::protobuf::uint32 tag; ptr = Varint::Parse32Inline(ptr, &tag); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { - case 0: goto error; // repeated string paths = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; do { ptr = Varint::Parse32Inline(ptr, &size); - if (!ptr) goto error; + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.protobuf.FieldMask.paths"); parser_till_end = ::google::protobuf::internal::StringParserUTF8; ::std::string* str = msg->add_paths(); @@ -195,16 +190,17 @@ const char* FieldMask::_InternalParse(const char* begin, const char* end, void* object = str; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; - if (!ctx->ParseExactRange({parser_till_end, object}, ptr, newend)) goto error; - ptr = newend; + if (size) ptr = parser_till_end(ptr, newend, object, ctx); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); if (ptr >= end) break; - } while((*reinterpret_cast(ptr) & 255) == 10 && (ptr += 1)); + } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1)); break; } default: { handle_unusual: (void)&&handle_unusual; - if ((tag & 7) == 4) { - if (!ctx->ValidEndGroup(tag)) goto error; + if ((tag & 7) == 4 || tag == 0) { + bool ok = ctx->ValidEndGroup(tag); + GOOGLE_PROTOBUF_PARSER_ASSERT(ok); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, @@ -215,8 +211,6 @@ const char* FieldMask::_InternalParse(const char* begin, const char* end, void* } // switch } // while return ptr; -error: - return nullptr; len_delim_till_end: (void)&&len_delim_till_end; return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); @@ -228,7 +222,7 @@ group_continues: (void)&&group_continues; #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool FieldMask::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure +#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FieldMask) for (;;) { @@ -426,10 +420,11 @@ void FieldMask::InternalSwap(FieldMask* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldMask* Arena::CreateMaybeMessage< ::google::protobuf::FieldMask >(Arena* arena) { +template<> PROTOBUF_NOINLINE ::google::protobuf::FieldMask* Arena::CreateMaybeMessage< ::google::protobuf::FieldMask >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::FieldMask >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope) +#include diff --git a/src/google/protobuf/field_mask.pb.h b/src/google/protobuf/field_mask.pb.h index 2055e964af..5b8561df10 100644 --- a/src/google/protobuf/field_mask.pb.h +++ b/src/google/protobuf/field_mask.pb.h @@ -7,18 +7,19 @@ #include #include -#include -#if GOOGLE_PROTOBUF_VERSION < 3006000 +#include +#if PROTOBUF_VERSION < 3006001 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3006001 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include @@ -32,27 +33,27 @@ #include // @@protoc_insertion_point(includes) #include -#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ffield_5fmask_2eproto LIBPROTOBUF_EXPORT +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ffield_5fmask_2eproto PROTOBUF_EXPORT // Internal implementation detail -- do not use these members. -struct LIBPROTOBUF_EXPORT TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto { +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto { static const ::google::protobuf::internal::ParseTableField entries[] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::AuxillaryParseTableField aux[] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::ParseTable schema[1] - GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold); + PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::FieldMetadata field_metadata[]; static const ::google::protobuf::internal::SerializationTable serialization_table[]; static const ::google::protobuf::uint32 offsets[]; }; -void LIBPROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2ffield_5fmask_2eproto(); +void PROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2ffield_5fmask_2eproto(); namespace google { namespace protobuf { class FieldMask; class FieldMaskDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern FieldMaskDefaultTypeInternal _FieldMask_default_instance_; -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldMask* Arena::CreateMaybeMessage<::google::protobuf::FieldMask>(Arena*); +PROTOBUF_EXPORT extern FieldMaskDefaultTypeInternal _FieldMask_default_instance_; +template<> PROTOBUF_EXPORT ::google::protobuf::FieldMask* Arena::CreateMaybeMessage<::google::protobuf::FieldMask>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -60,7 +61,7 @@ namespace protobuf { // =================================================================== -class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldMask) */ { +class PROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldMask) */ { public: FieldMask(); virtual ~FieldMask(); diff --git a/src/google/protobuf/generated_enum_reflection.h b/src/google/protobuf/generated_enum_reflection.h index 27aac3f3c4..774528ee5c 100644 --- a/src/google/protobuf/generated_enum_reflection.h +++ b/src/google/protobuf/generated_enum_reflection.h @@ -48,6 +48,8 @@ #error "You cannot SWIG proto headers" #endif +#include + namespace google { namespace protobuf { class EnumDescriptor; @@ -68,13 +70,12 @@ namespace internal { // Helper for EnumType_Parse functions: try to parse the string 'name' as an // enum name of the given type, returning true and filling in value on success, // or returning false and leaving value unchanged on failure. -LIBPROTOBUF_EXPORT bool ParseNamedEnum(const EnumDescriptor* descriptor, - const string& name, - int* value); +PROTOBUF_EXPORT bool ParseNamedEnum(const EnumDescriptor* descriptor, + const std::string& name, int* value); template bool ParseNamedEnum(const EnumDescriptor* descriptor, - const string& name, + const std::string& name, EnumType* value) { int tmp; if (!ParseNamedEnum(descriptor, name, &tmp)) return false; @@ -85,10 +86,13 @@ bool ParseNamedEnum(const EnumDescriptor* descriptor, // Just a wrapper around printing the name of a value. The main point of this // function is not to be inlined, so that you can do this without including // descriptor.h. -LIBPROTOBUF_EXPORT const string& NameOfEnum(const EnumDescriptor* descriptor, int value); +PROTOBUF_EXPORT const std::string& NameOfEnum(const EnumDescriptor* descriptor, + int value); } // namespace internal } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_GENERATED_ENUM_REFLECTION_H__ diff --git a/src/google/protobuf/generated_message_reflection.cc b/src/google/protobuf/generated_message_reflection.cc index e24f03063b..f926da274e 100644 --- a/src/google/protobuf/generated_message_reflection.cc +++ b/src/google/protobuf/generated_message_reflection.cc @@ -1201,8 +1201,9 @@ void GeneratedMessageReflection::SetString( MutableField(message, field)->UnsafeSetDefault( default_ptr); } - MutableField(message, field)->Set(default_ptr, - value, GetArena(message)); + MutableField(message, field) + ->Mutable(default_ptr, GetArena(message)) + ->assign(value); break; } } @@ -1705,7 +1706,7 @@ void* GeneratedMessageReflection::MutableRawRepeatedField( if (field->cpp_type() != cpptype) ReportReflectionUsageTypeError(descriptor_, field, "MutableRawRepeatedField", cpptype); - if (ctype >= 0) + if (ctype >= 0 && !field->is_extension()) GOOGLE_CHECK_EQ(field->options().ctype(), ctype) << "subtype mismatch"; if (desc != NULL) GOOGLE_CHECK_EQ(field->message_type(), desc) << "wrong submessage type"; diff --git a/src/google/protobuf/generated_message_reflection.h b/src/google/protobuf/generated_message_reflection.h index 177312cf7a..0ffb3ff270 100644 --- a/src/google/protobuf/generated_message_reflection.h +++ b/src/google/protobuf/generated_message_reflection.h @@ -361,11 +361,11 @@ class GeneratedMessageReflection final : public Reflection { const FieldDescriptor* field) const override; bool GetBool(const Message& message, const FieldDescriptor* field) const override; - string GetString(const Message& message, + std::string GetString(const Message& message, const FieldDescriptor* field) const override; - const string& GetStringReference(const Message& message, + const std::string& GetStringReference(const Message& message, const FieldDescriptor* field, - string* scratch) const override; + std::string* scratch) const override; const EnumValueDescriptor* GetEnum( const Message& message, const FieldDescriptor* field) const override; int GetEnumValue(const Message& message, @@ -409,7 +409,7 @@ class GeneratedMessageReflection final : public Reflection { void SetBool(Message* message, const FieldDescriptor* field, bool value) const override; void SetString(Message* message, const FieldDescriptor* field, - const string& value) const override; + const std::string& value) const override; void SetEnum(Message* message, const FieldDescriptor* field, const EnumValueDescriptor* value) const override; void SetEnumValue(Message* message, const FieldDescriptor* field, @@ -435,12 +435,12 @@ class GeneratedMessageReflection final : public Reflection { int index) const override; bool GetRepeatedBool(const Message& message, const FieldDescriptor* field, int index) const override; - string GetRepeatedString(const Message& message, const FieldDescriptor* field, + std::string GetRepeatedString(const Message& message, const FieldDescriptor* field, int index) const override; - const string& GetRepeatedStringReference(const Message& message, + const std::string& GetRepeatedStringReference(const Message& message, const FieldDescriptor* field, int index, - string* scratch) const override; + std::string* scratch) const override; const EnumValueDescriptor* GetRepeatedEnum(const Message& message, const FieldDescriptor* field, int index) const override; @@ -466,7 +466,7 @@ class GeneratedMessageReflection final : public Reflection { void SetRepeatedBool(Message* message, const FieldDescriptor* field, int index, bool value) const override; void SetRepeatedString(Message* message, const FieldDescriptor* field, - int index, const string& value) const override; + int index, const std::string& value) const override; void SetRepeatedEnum(Message* message, const FieldDescriptor* field, int index, const EnumValueDescriptor* value) const override; @@ -492,7 +492,7 @@ class GeneratedMessageReflection final : public Reflection { void AddBool(Message* message, const FieldDescriptor* field, bool value) const override; void AddString(Message* message, const FieldDescriptor* field, - const string& value) const override; + const std::string& value) const override; void AddEnum(Message* message, const FieldDescriptor* field, const EnumValueDescriptor* value) const override; void AddEnumValue(Message* message, const FieldDescriptor* field, @@ -503,7 +503,7 @@ class GeneratedMessageReflection final : public Reflection { Message* new_entry) const override; const FieldDescriptor* FindKnownExtensionByName( - const string& name) const override; + const std::string& name) const override; const FieldDescriptor* FindKnownExtensionByNumber(int number) const override; bool SupportsUnknownEnumValues() const override; @@ -681,7 +681,7 @@ class GeneratedMessageReflection final : public Reflection { typedef void (*InitFunc)(); -struct LIBPROTOBUF_EXPORT AssignDescriptorsTable { +struct PROTOBUF_EXPORT AssignDescriptorsTable { once_flag once; InitFunc add_descriptors; const char* filename; @@ -695,9 +695,9 @@ struct LIBPROTOBUF_EXPORT AssignDescriptorsTable { const ServiceDescriptor** file_level_service_descriptors; }; -void LIBPROTOBUF_EXPORT AssignDescriptors(AssignDescriptorsTable* table); +void PROTOBUF_EXPORT AssignDescriptors(AssignDescriptorsTable* table); -struct LIBPROTOBUF_EXPORT DescriptorTable { +struct PROTOBUF_EXPORT DescriptorTable { bool is_initialized; InitFunc init_defaults; const char* descriptor; @@ -706,14 +706,13 @@ struct LIBPROTOBUF_EXPORT DescriptorTable { int size; // of serialized descriptor }; -void LIBPROTOBUF_EXPORT AddDescriptors(DescriptorTable* table, - const InitFunc* deps, - int num_deps); +void PROTOBUF_EXPORT AddDescriptors(DescriptorTable* table, + const InitFunc* deps, int num_deps); // These cannot be in lite so we put them in the reflection. -LIBPROTOBUF_EXPORT void UnknownFieldSetSerializer(const uint8* base, uint32 offset, uint32 tag, - uint32 has_offset, - io::CodedOutputStream* output); +PROTOBUF_EXPORT void UnknownFieldSetSerializer(const uint8* base, uint32 offset, + uint32 tag, uint32 has_offset, + io::CodedOutputStream* output); } // namespace internal } // namespace protobuf diff --git a/src/google/protobuf/generated_message_table_driven_lite.h b/src/google/protobuf/generated_message_table_driven_lite.h index 4b461f1b3c..17e256a7c2 100644 --- a/src/google/protobuf/generated_message_table_driven_lite.h +++ b/src/google/protobuf/generated_message_table_driven_lite.h @@ -44,6 +44,8 @@ #include +#include + namespace google { namespace protobuf { namespace internal { @@ -83,7 +85,7 @@ inline const Type* Raw(const MessageLite* msg, int64 offset) { template inline Arena* GetArena(MessageLite* msg, int64 arena_offset) { - if (GOOGLE_PREDICT_FALSE(arena_offset == -1)) { + if (PROTOBUF_PREDICT_FALSE(arena_offset == -1)) { return NULL; } @@ -109,9 +111,9 @@ inline Type* AddField(MessageLite* msg, int64 offset) { } template <> -inline string* AddField(MessageLite* msg, int64 offset) { - RepeatedPtrField* repeated = - Raw>(msg, offset); +inline std::string* AddField(MessageLite* msg, int64 offset) { + RepeatedPtrField* repeated = + Raw>(msg, offset); return repeated->Add(); } @@ -205,11 +207,11 @@ inline void ResetOneofField(const ParseTable& table, int field_number, switch (field_type) { case ProcessingType_STRING: Raw(msg, offset) - ->UnsafeSetDefault(static_cast(default_ptr)); + ->UnsafeSetDefault(static_cast(default_ptr)); break; case ProcessingType_INLINED: new (Raw(msg, offset)) - InlinedStringField(*static_cast(default_ptr)); + InlinedStringField(*static_cast(default_ptr)); break; case ProcessingType_MESSAGE: MessageLite** submessage = Raw(msg, offset); @@ -250,7 +252,7 @@ static inline bool HandleString(io::CodedInputStream* input, MessageLite* msg, GOOGLE_DCHECK(s != nullptr); ::std::string* value = s->MutableNoArena(NULL); - if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) { + if (PROTOBUF_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) { return false; } @@ -261,25 +263,25 @@ static inline bool HandleString(io::CodedInputStream* input, MessageLite* msg, break; } case StringType_STRING: { - string* value; + std::string* value; switch (cardinality) { case Cardinality_SINGULAR: // TODO(ckennelly): Is this optimal? value = MutableField(msg, has_bits, has_bit_index, offset) - ->Mutable(static_cast(default_ptr), arena); + ->Mutable(static_cast(default_ptr), arena); break; case Cardinality_REPEATED: - value = AddField(msg, offset); + value = AddField(msg, offset); break; case Cardinality_ONEOF: value = Raw(msg, offset) - ->Mutable(static_cast(default_ptr), arena); + ->Mutable(static_cast(default_ptr), arena); break; } GOOGLE_DCHECK(value != nullptr); - if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) { + if (PROTOBUF_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) { return false; } @@ -308,7 +310,7 @@ inline bool HandleEnum(const ParseTable& table, io::CodedInputStream* input, uint32 presence_index, int64 offset, uint32 tag, int field_number) { int value; - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( (!WireFormatLite::ReadPrimitive( input, &value)))) { return false; @@ -394,7 +396,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, continue; } - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( !UnknownFieldHandler::Skip(msg, table, input, tag))) { return false; } @@ -422,7 +424,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, #define HANDLE_TYPE(TYPE, CPPTYPE) \ case (WireFormatLite::TYPE_##TYPE): { \ CPPTYPE value; \ - if (GOOGLE_PREDICT_FALSE( \ + if (PROTOBUF_PREDICT_FALSE( \ (!WireFormatLite::ReadPrimitive< \ CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, &value)))) { \ return false; \ @@ -432,8 +434,8 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, } \ case (WireFormatLite::TYPE_##TYPE) | kRepeatedMask: { \ RepeatedField* values = Raw>(msg, offset); \ - if (GOOGLE_PREDICT_FALSE((!WireFormatLite::ReadRepeatedPrimitive< \ - CPPTYPE, WireFormatLite::TYPE_##TYPE>( \ + if (PROTOBUF_PREDICT_FALSE((!WireFormatLite::ReadRepeatedPrimitive< \ + CPPTYPE, WireFormatLite::TYPE_##TYPE>( \ data->tag_size, tag, input, values)))) { \ return false; \ } \ @@ -442,7 +444,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, case (WireFormatLite::TYPE_##TYPE) | kOneofMask: { \ uint32* oneof_case = Raw(msg, table.oneof_case_offset); \ CPPTYPE value; \ - if (GOOGLE_PREDICT_FALSE( \ + if (PROTOBUF_PREDICT_FALSE( \ (!WireFormatLite::ReadPrimitive< \ CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, &value)))) { \ return false; \ @@ -480,7 +482,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, GetArena(msg, table.arena_offset); const void* default_ptr = table.aux[field_number].strings.default_ptr; - if (GOOGLE_PREDICT_FALSE(( + if (PROTOBUF_PREDICT_FALSE(( !HandleString( input, msg, arena, has_bits, presence_index, offset, default_ptr, NULL)))) { @@ -497,8 +499,8 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, GetArena(msg, table.arena_offset); const void* default_ptr = table.aux[field_number].strings.default_ptr; - if (GOOGLE_PREDICT_FALSE((!HandleString( + if (PROTOBUF_PREDICT_FALSE((!HandleString( input, msg, arena, has_bits, presence_index, offset, default_ptr, NULL)))) { return false; @@ -519,7 +521,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, table, field_number, arena, msg, oneof_case + presence_index, offset, default_ptr); - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( (!HandleString( input, msg, arena, has_bits, presence_index, offset, default_ptr, NULL)))) { @@ -539,7 +541,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, const void* default_ptr = table.aux[field_number].strings.default_ptr; - if (GOOGLE_PREDICT_FALSE(( + if (PROTOBUF_PREDICT_FALSE(( !HandleString( input, msg, arena, has_bits, presence_index, offset, default_ptr, NULL)))) { @@ -554,7 +556,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, const void* default_ptr = table.aux[field_number].strings.default_ptr; const char* field_name = table.aux[field_number].strings.field_name; - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( (!HandleString( input, msg, arena, has_bits, presence_index, offset, default_ptr, field_name)))) { @@ -569,7 +571,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, const void* default_ptr = table.aux[field_number].strings.default_ptr; const char* field_name = table.aux[field_number].strings.field_name; - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( (!HandleString( input, msg, arena, has_bits, presence_index, offset, default_ptr, field_name)))) { @@ -588,7 +590,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, table, field_number, arena, msg, oneof_case + presence_index, offset, default_ptr); - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( (!HandleString( input, msg, arena, has_bits, presence_index, offset, default_ptr, field_name)))) { @@ -598,7 +600,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, } #endif case WireFormatLite::TYPE_ENUM: { - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( (!HandleEnum( table, input, msg, has_bits, presence_index, offset, tag, @@ -608,7 +610,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, break; } case WireFormatLite::TYPE_ENUM | kRepeatedMask: { - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( (!HandleEnum( table, input, msg, has_bits, presence_index, offset, tag, @@ -619,7 +621,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, } case WireFormatLite::TYPE_ENUM | kOneofMask: { uint32* oneof_case = Raw(msg, table.oneof_case_offset); - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( (!HandleEnum(table, input, msg, oneof_case, presence_index, offset, tag, @@ -642,7 +644,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, *submsg_holder = submsg; } - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( !WireFormatLite::ReadGroup(field_number, input, submsg))) { return false; } @@ -658,7 +660,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, MessageLite* submsg = MergePartialFromCodedStreamHelper::Add(field, prototype); - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( !WireFormatLite::ReadGroup(field_number, input, submsg))) { return false; } @@ -682,7 +684,8 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, *submsg_holder = submsg; } - if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadMessage(input, submsg))) { + if (PROTOBUF_PREDICT_FALSE( + !WireFormatLite::ReadMessage(input, submsg))) { return false; } @@ -701,7 +704,8 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, MessageLite* submsg = MergePartialFromCodedStreamHelper::Add(field, prototype); - if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadMessage(input, submsg))) { + if (PROTOBUF_PREDICT_FALSE( + !WireFormatLite::ReadMessage(input, submsg))) { return false; } @@ -717,7 +721,8 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, offset, NULL); MessageLite* submsg = *submsg_holder; - if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadMessage(input, submsg))) { + if (PROTOBUF_PREDICT_FALSE( + !WireFormatLite::ReadMessage(input, submsg))) { return false; } @@ -730,7 +735,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, const void* default_ptr = table.aux[field_number].strings.default_ptr; const char* field_name = table.aux[field_number].strings.field_name; - if (GOOGLE_PREDICT_FALSE(( + if (PROTOBUF_PREDICT_FALSE(( !HandleString( input, msg, arena, has_bits, presence_index, offset, default_ptr, field_name)))) { @@ -740,7 +745,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, } #endif // GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED case TYPE_MAP: { - if (GOOGLE_PREDICT_FALSE(!(*table.aux[field_number].maps.parse_map)( + if (PROTOBUF_PREDICT_FALSE(!(*table.aux[field_number].maps.parse_map)( input, Raw(msg, offset)))) { return false; } @@ -771,7 +776,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, #define HANDLE_PACKED_TYPE(TYPE, CPPTYPE, CPPTYPE_METHOD) \ case WireFormatLite::TYPE_##TYPE: { \ RepeatedField* values = Raw>(msg, offset); \ - if (GOOGLE_PREDICT_FALSE( \ + if (PROTOBUF_PREDICT_FALSE( \ (!WireFormatLite::ReadPackedPrimitive< \ CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, values)))) { \ return false; \ @@ -802,7 +807,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, // are valid, we implement our own parser rather than call // WireFormat::ReadPackedEnumPreserveUnknowns. uint32 length; - if (GOOGLE_PREDICT_FALSE(!input->ReadVarint32(&length))) { + if (PROTOBUF_PREDICT_FALSE(!input->ReadVarint32(&length))) { return false; } @@ -813,7 +818,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, io::CodedInputStream::Limit limit = input->PushLimit(length); while (input->BytesUntilLimit() > 0) { int value; - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( (!WireFormatLite::ReadPrimitive< int, WireFormatLite::TYPE_ENUM>(input, &value)))) { return false; @@ -852,7 +857,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, } // process unknown field. - if (GOOGLE_PREDICT_FALSE( + if (PROTOBUF_PREDICT_FALSE( !UnknownFieldHandler::Skip(msg, table, input, tag))) { return false; } @@ -864,4 +869,6 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_GENERATED_MESSAGE_TABLE_DRIVEN_LITE_H__ diff --git a/src/google/protobuf/generated_message_util.h b/src/google/protobuf/generated_message_util.h index 23d1009e1c..b9bbb26b6e 100644 --- a/src/google/protobuf/generated_message_util.h +++ b/src/google/protobuf/generated_message_util.h @@ -75,38 +75,10 @@ namespace io { class CodedInputStream; } namespace internal { -// Returns the offset of the given field within the given aggregate type. -// This is equivalent to the ANSI C offsetof() macro. However, according -// to the C++ standard, offsetof() only works on POD types, and GCC -// enforces this requirement with a warning. In practice, this rule is -// unnecessarily strict; there is probably no compiler or platform on -// which the offsets of the direct fields of a class are non-constant. -// Fields inherited from superclasses *can* have non-constant offsets, -// but that's not what this macro will be used for. -#if defined(__clang__) -// For Clang we use __builtin_offsetof() and suppress the warning, -// to avoid Control Flow Integrity and UBSan vptr sanitizers from -// crashing while trying to validate the invalid reinterpet_casts. -#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TYPE, FIELD) \ - _Pragma("clang diagnostic push") \ - _Pragma("clang diagnostic ignored \"-Winvalid-offsetof\"") \ - __builtin_offsetof(TYPE, FIELD) \ - _Pragma("clang diagnostic pop") -#else -// Note that we calculate relative to the pointer value 16 here since if we -// just use zero, GCC complains about dereferencing a NULL pointer. We -// choose 16 rather than some other number just in case the compiler would -// be confused by an unaligned pointer. -#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TYPE, FIELD) \ - static_cast< ::google::protobuf::uint32>(reinterpret_cast( \ - &reinterpret_cast(16)->FIELD) - \ - reinterpret_cast(16)) -#endif - -LIBPROTOBUF_EXPORT void InitProtobufDefaults(); +PROTOBUF_EXPORT void InitProtobufDefaults(); // This used by proto1 -LIBPROTOBUF_EXPORT inline const ::std::string& GetEmptyString() { +PROTOBUF_EXPORT inline const ::std::string& GetEmptyString() { InitProtobufDefaults(); return GetEmptyStringAlreadyInited(); } @@ -139,7 +111,7 @@ bool AllAreInitializedWeak(const RepeatedPtrField& t) { return true; } -struct LIBPROTOBUF_EXPORT FieldMetadata { +struct PROTOBUF_EXPORT FieldMetadata { uint32 offset; // offset of this field in the struct uint32 tag; // field * 8 + wire_type // byte offset * 8 + bit_offset; @@ -188,19 +160,23 @@ typedef void (*SpecialSerializer)(const uint8* base, uint32 offset, uint32 tag, uint32 has_offset, io::CodedOutputStream* output); -LIBPROTOBUF_EXPORT void ExtensionSerializer(const uint8* base, uint32 offset, uint32 tag, - uint32 has_offset, io::CodedOutputStream* output); -LIBPROTOBUF_EXPORT void UnknownFieldSerializerLite(const uint8* base, uint32 offset, uint32 tag, - uint32 has_offset, - io::CodedOutputStream* output); +PROTOBUF_EXPORT void ExtensionSerializer(const uint8* base, uint32 offset, + uint32 tag, uint32 has_offset, + io::CodedOutputStream* output); +PROTOBUF_EXPORT void UnknownFieldSerializerLite(const uint8* base, + uint32 offset, uint32 tag, + uint32 has_offset, + io::CodedOutputStream* output); struct SerializationTable { int num_fields; const FieldMetadata* field_table; }; -LIBPROTOBUF_EXPORT void SerializeInternal(const uint8* base, const FieldMetadata* table, - int32 num_fields, io::CodedOutputStream* output); +PROTOBUF_EXPORT void SerializeInternal(const uint8* base, + const FieldMetadata* table, + int32 num_fields, + io::CodedOutputStream* output); inline void TableSerialize(const MessageLite& msg, const SerializationTable* table, @@ -290,10 +266,10 @@ void MapFieldSerializer(const uint8* base, uint32 offset, uint32 tag, } } -LIBPROTOBUF_EXPORT MessageLite* DuplicateIfNonNullInternal(MessageLite* message); -LIBPROTOBUF_EXPORT MessageLite* GetOwnedMessageInternal(Arena* message_arena, - MessageLite* submessage, - Arena* submessage_arena); +PROTOBUF_EXPORT MessageLite* DuplicateIfNonNullInternal(MessageLite* message); +PROTOBUF_EXPORT MessageLite* GetOwnedMessageInternal(Arena* message_arena, + MessageLite* submessage, + Arena* submessage_arena); template T* DuplicateIfNonNull(T* message) { @@ -315,7 +291,7 @@ T* GetOwnedMessage(Arena* message_arena, T* submessage, // Hide atomic from the public header and allow easy change to regular int // on platforms where the atomic might have a perf impact. -class LIBPROTOBUF_EXPORT CachedSize { +class PROTOBUF_EXPORT CachedSize { public: int Get() const { return size_.load(std::memory_order_relaxed); } void Set(int size) { size_.store(size, std::memory_order_relaxed); } @@ -325,7 +301,7 @@ class LIBPROTOBUF_EXPORT CachedSize { // SCCInfo represents information of a strongly connected component of // mutual dependent messages. -struct LIBPROTOBUF_EXPORT SCCInfoBase { +struct PROTOBUF_EXPORT SCCInfoBase { // We use 0 for the Initialized state, because test eax,eax, jnz is smaller // and is subject to macro fusion. enum { @@ -359,15 +335,16 @@ struct SCCInfo { SCCInfoBase* deps[N ? N : 1]; }; -LIBPROTOBUF_EXPORT void InitSCCImpl(SCCInfoBase* scc); +PROTOBUF_EXPORT void InitSCCImpl(SCCInfoBase* scc); inline void InitSCC(SCCInfoBase* scc) { auto status = scc->visit_status.load(std::memory_order_acquire); - if (GOOGLE_PREDICT_FALSE(status != SCCInfoBase::kInitialized)) InitSCCImpl(scc); + if (PROTOBUF_PREDICT_FALSE(status != SCCInfoBase::kInitialized)) + InitSCCImpl(scc); } -LIBPROTOBUF_EXPORT void DestroyMessage(const void* message); -LIBPROTOBUF_EXPORT void DestroyString(const void* s); +PROTOBUF_EXPORT void DestroyMessage(const void* message); +PROTOBUF_EXPORT void DestroyString(const void* s); // Destroy (not delete) the message inline void OnShutdownDestroyMessage(const void* ptr) { OnShutdownRun(DestroyMessage, ptr); diff --git a/src/google/protobuf/has_bits.h b/src/google/protobuf/has_bits.h index edf4e82992..d15b3f8d91 100644 --- a/src/google/protobuf/has_bits.h +++ b/src/google/protobuf/has_bits.h @@ -47,18 +47,17 @@ namespace internal { template class HasBits { public: - HasBits() GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { Clear(); } + HasBits() PROTOBUF_ALWAYS_INLINE { Clear(); } - void Clear() GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + void Clear() PROTOBUF_ALWAYS_INLINE { memset(has_bits_, 0, sizeof(has_bits_)); } - ::google::protobuf::uint32& operator[](int index) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + ::google::protobuf::uint32& operator[](int index) PROTOBUF_ALWAYS_INLINE { return has_bits_[index]; } - const ::google::protobuf::uint32& operator[](int index) const - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + const ::google::protobuf::uint32& operator[](int index) const PROTOBUF_ALWAYS_INLINE { return has_bits_[index]; } diff --git a/src/google/protobuf/implicit_weak_message.cc b/src/google/protobuf/implicit_weak_message.cc index 7e47cdcc32..582d7084df 100644 --- a/src/google/protobuf/implicit_weak_message.cc +++ b/src/google/protobuf/implicit_weak_message.cc @@ -31,11 +31,13 @@ #include #include +#include +#include + +#include #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER #include #endif -#include -#include namespace google { namespace protobuf { diff --git a/src/google/protobuf/implicit_weak_message.h b/src/google/protobuf/implicit_weak_message.h index 2983628934..5d3b479a45 100644 --- a/src/google/protobuf/implicit_weak_message.h +++ b/src/google/protobuf/implicit_weak_message.h @@ -36,6 +36,8 @@ #include #include +#include + #ifdef SWIG #error "You cannot SWIG proto headers" #endif @@ -50,52 +52,52 @@ namespace internal { // An implementation of MessageLite that treats all data as unknown. This type // acts as a placeholder for an implicit weak field in the case where the true // message type does not get linked into the binary. -class LIBPROTOBUF_EXPORT ImplicitWeakMessage : public MessageLite { +class PROTOBUF_EXPORT ImplicitWeakMessage : public MessageLite { public: ImplicitWeakMessage() : arena_(NULL) {} explicit ImplicitWeakMessage(Arena* arena) : arena_(arena) {} static const ImplicitWeakMessage* default_instance(); - string GetTypeName() const { return ""; } + std::string GetTypeName() const override { return ""; } - MessageLite* New() const { return new ImplicitWeakMessage; } - MessageLite* New(Arena* arena) const { + MessageLite* New() const override { return new ImplicitWeakMessage; } + MessageLite* New(Arena* arena) const override { return Arena::CreateMessage(arena); } - Arena* GetArena() const { return arena_; } + Arena* GetArena() const override { return arena_; } - void Clear() { data_.clear(); } + void Clear() override { data_.clear(); } - bool IsInitialized() const { return true; } + bool IsInitialized() const override { return true; } - void CheckTypeAndMergeFrom(const MessageLite& other) { + void CheckTypeAndMergeFrom(const MessageLite& other) override { data_.append(static_cast(other).data_); } - bool MergePartialFromCodedStream(io::CodedInputStream* input); + bool MergePartialFromCodedStream(io::CodedInputStream* input) override; #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER - ParseFunc _ParseFunc() const { return _InternalParse; } + ParseFunc _ParseFunc() const override { return _InternalParse; } static const char* _InternalParse(const char* begin, const char* end, void* object, ParseContext* ctx); #endif - size_t ByteSizeLong() const { return data_.size(); } + size_t ByteSizeLong() const override { return data_.size(); } - void SerializeWithCachedSizes(io::CodedOutputStream* output) const { + void SerializeWithCachedSizes(io::CodedOutputStream* output) const override { output->WriteString(data_); } - int GetCachedSize() const { return static_cast(data_.size()); } + int GetCachedSize() const override { return static_cast(data_.size()); } typedef void InternalArenaConstructable_; private: Arena* const arena_; - string data_; + std::string data_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImplicitWeakMessage); }; @@ -141,4 +143,6 @@ class ImplicitWeakTypeHandler { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_IMPLICIT_WEAK_MESSAGE_H__ diff --git a/src/google/protobuf/inlined_string_field.h b/src/google/protobuf/inlined_string_field.h index 1509193f97..c5077b4bfb 100644 --- a/src/google/protobuf/inlined_string_field.h +++ b/src/google/protobuf/inlined_string_field.h @@ -58,53 +58,49 @@ namespace internal { // default_value parameters are taken for consistency with ArenaStringPtr, but // are not used for most methods. With inlining, these should be removed from // the generated binary. -class LIBPROTOBUF_EXPORT InlinedStringField { +class PROTOBUF_EXPORT InlinedStringField { public: - InlinedStringField() GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + InlinedStringField() PROTOBUF_ALWAYS_INLINE; explicit InlinedStringField(const ::std::string& default_value); void AssignWithDefault(const ::std::string* default_value, - const InlinedStringField& from) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + const InlinedStringField& from) PROTOBUF_ALWAYS_INLINE; void ClearToEmpty(const ::std::string* default_value, - Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + Arena* arena) PROTOBUF_ALWAYS_INLINE { ClearToEmptyNoArena(default_value); } - void ClearNonDefaultToEmpty() GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + void ClearNonDefaultToEmpty() PROTOBUF_ALWAYS_INLINE { ClearNonDefaultToEmptyNoArena(); } void ClearToEmptyNoArena(const ::std::string* default_value) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + PROTOBUF_ALWAYS_INLINE { ClearNonDefaultToEmptyNoArena(); } - void ClearNonDefaultToEmptyNoArena() GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + void ClearNonDefaultToEmptyNoArena() PROTOBUF_ALWAYS_INLINE; void ClearToDefault(const ::std::string* default_value, - Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + Arena* arena) PROTOBUF_ALWAYS_INLINE { ClearToDefaultNoArena(default_value); } void ClearToDefaultNoArena(const ::std::string* default_value) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + PROTOBUF_ALWAYS_INLINE; void Destroy(const ::std::string* default_value, - Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + Arena* arena) PROTOBUF_ALWAYS_INLINE { DestroyNoArena(default_value); } - void DestroyNoArena(const ::std::string* default_value) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + void DestroyNoArena(const ::std::string* default_value) PROTOBUF_ALWAYS_INLINE; - const ::std::string& Get() const GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { - return GetNoArena(); - } - const ::std::string& GetNoArena() const GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + const ::std::string& Get() const PROTOBUF_ALWAYS_INLINE { return GetNoArena(); } + const ::std::string& GetNoArena() const PROTOBUF_ALWAYS_INLINE; ::std::string* Mutable(const ::std::string* default_value, - Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + Arena* arena) PROTOBUF_ALWAYS_INLINE { return MutableNoArena(default_value); } ::std::string* MutableNoArena(const ::std::string* default_value) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + PROTOBUF_ALWAYS_INLINE; ::std::string* Release(const ::std::string* default_value, Arena* arena) { return ReleaseNoArena(default_value); @@ -118,30 +114,30 @@ class LIBPROTOBUF_EXPORT InlinedStringField { ::std::string* ReleaseNonDefaultNoArena(const ::std::string* default_value); void Set(const ::std::string* default_value, StringPiece value, - Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + Arena* arena) PROTOBUF_ALWAYS_INLINE { SetNoArena(default_value, value); } void SetLite(const ::std::string* default_value, StringPiece value, - Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + Arena* arena) PROTOBUF_ALWAYS_INLINE { SetNoArena(default_value, value); } - void SetNoArena(const ::std::string* default_value, StringPiece value) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + void SetNoArena(const ::std::string* default_value, + StringPiece value) PROTOBUF_ALWAYS_INLINE; void Set(const ::std::string* default_value, const ::std::string& value, - Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + Arena* arena) PROTOBUF_ALWAYS_INLINE { SetNoArena(default_value, value); } void SetLite(const ::std::string* default_value, const ::std::string& value, - Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + Arena* arena) PROTOBUF_ALWAYS_INLINE { SetNoArena(default_value, value); } - void SetNoArena(const ::std::string* default_value, const ::std::string& value) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + void SetNoArena(const ::std::string* default_value, + const ::std::string& value) PROTOBUF_ALWAYS_INLINE; #if LANG_CXX11 void SetNoArena(const ::std::string* default_value, - ::std::string&& value) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + ::std::string&& value) PROTOBUF_ALWAYS_INLINE; #endif void SetAllocated(const ::std::string* default_value, ::std::string* value, @@ -150,7 +146,7 @@ class LIBPROTOBUF_EXPORT InlinedStringField { } void SetAllocatedNoArena(const ::std::string* default_value, ::std::string* value); - void Swap(InlinedStringField* from) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + void Swap(InlinedStringField* from) PROTOBUF_ALWAYS_INLINE; ::std::string* UnsafeMutablePointer(); void UnsafeSetDefault(const ::std::string* default_value); ::std::string* UnsafeArenaRelease(const ::std::string* default_value, Arena* arena); diff --git a/src/google/protobuf/io/coded_stream.cc b/src/google/protobuf/io/coded_stream.cc index 311668ce03..547c5c6459 100644 --- a/src/google/protobuf/io/coded_stream.cc +++ b/src/google/protobuf/io/coded_stream.cc @@ -123,7 +123,7 @@ CodedInputStream::Limit CodedInputStream::PushLimit(int byte_limit) { // security: byte_limit is possibly evil, so check for negative values // and overflow. Also check that the new requested limit is before the // previous limit; otherwise we continue to enforce the previous limit. - if (GOOGLE_PREDICT_TRUE(byte_limit >= 0 && + if (PROTOBUF_PREDICT_TRUE(byte_limit >= 0 && byte_limit <= INT_MAX - current_position && byte_limit < current_limit_ - current_position)) { current_limit_ = current_position + byte_limit; @@ -314,11 +314,25 @@ bool CodedInputStream::ReadLittleEndian64Fallback(uint64* value) { namespace { +// Decodes varint64 with known size, N, and returns next pointer. Knowing N at +// compile time, compiler can generate optimal code. For example, instead of +// subtracting 0x80 at each iteration, it subtracts properly shifted mask once. +template +const uint8* DecodeVarint64KnownSize(const uint8* buffer, uint64* value) { + GOOGLE_DCHECK_GT(N, 0); + uint64 result = static_cast(buffer[N - 1]) << (7 * (N - 1)); + for (int i = 0, offset = 0; i < N - 1; i++, offset += 7) { + result += static_cast(buffer[i] - 0x80) << offset; + } + *value = result; + return buffer + N; +} + // Read a varint from the given buffer, write it to *value, and return a pair. // The first part of the pair is true iff the read was successful. The second // part is buffer + (number of bytes read). This function is always inlined, // so returning a pair is costless. -GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE +PROTOBUF_ALWAYS_INLINE ::std::pair ReadVarint32FromArray( uint32 first_byte, const uint8* buffer, uint32* value); @@ -356,47 +370,39 @@ inline ::std::pair ReadVarint32FromArray( return std::make_pair(true, ptr); } -GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE::std::pair -ReadVarint64FromArray(const uint8* buffer, uint64* value); +PROTOBUF_ALWAYS_INLINE::std::pair ReadVarint64FromArray( + const uint8* buffer, uint64* value); inline ::std::pair ReadVarint64FromArray( const uint8* buffer, uint64* value) { - const uint8* ptr = buffer; - uint32 b; - - // Splitting into 32-bit pieces gives better performance on 32-bit - // processors. - uint32 part0 = 0, part1 = 0, part2 = 0; - - b = *(ptr++); part0 = b ; if (!(b & 0x80)) goto done; - part0 -= 0x80; - b = *(ptr++); part0 += b << 7; if (!(b & 0x80)) goto done; - part0 -= 0x80 << 7; - b = *(ptr++); part0 += b << 14; if (!(b & 0x80)) goto done; - part0 -= 0x80 << 14; - b = *(ptr++); part0 += b << 21; if (!(b & 0x80)) goto done; - part0 -= 0x80 << 21; - b = *(ptr++); part1 = b ; if (!(b & 0x80)) goto done; - part1 -= 0x80; - b = *(ptr++); part1 += b << 7; if (!(b & 0x80)) goto done; - part1 -= 0x80 << 7; - b = *(ptr++); part1 += b << 14; if (!(b & 0x80)) goto done; - part1 -= 0x80 << 14; - b = *(ptr++); part1 += b << 21; if (!(b & 0x80)) goto done; - part1 -= 0x80 << 21; - b = *(ptr++); part2 = b ; if (!(b & 0x80)) goto done; - part2 -= 0x80; - b = *(ptr++); part2 += b << 7; if (!(b & 0x80)) goto done; - // "part2 -= 0x80 << 7" is irrelevant because (0x80 << 7) << 56 is 0. - - // We have overrun the maximum size of a varint (10 bytes). Assume - // the data is corrupt. - return std::make_pair(false, ptr); + // Assumes varint64 is at least 2 bytes. + GOOGLE_DCHECK_GE(buffer[0], 128); + + const uint8* next; + if (buffer[1] < 128) { + next = DecodeVarint64KnownSize<2>(buffer, value); + } else if (buffer[2] < 128) { + next = DecodeVarint64KnownSize<3>(buffer, value); + } else if (buffer[3] < 128) { + next = DecodeVarint64KnownSize<4>(buffer, value); + } else if (buffer[4] < 128) { + next = DecodeVarint64KnownSize<5>(buffer, value); + } else if (buffer[5] < 128) { + next = DecodeVarint64KnownSize<6>(buffer, value); + } else if (buffer[6] < 128) { + next = DecodeVarint64KnownSize<7>(buffer, value); + } else if (buffer[7] < 128) { + next = DecodeVarint64KnownSize<8>(buffer, value); + } else if (buffer[8] < 128) { + next = DecodeVarint64KnownSize<9>(buffer, value); + } else if (buffer[9] < 128) { + next = DecodeVarint64KnownSize<10>(buffer, value); + } else { + // We have overrun the maximum size of a varint (10 bytes). Assume + // the data is corrupt. + return std::make_pair(false, buffer + 11); + } - done: - *value = (static_cast(part0)) | - (static_cast(part1) << 28) | - (static_cast(part2) << 56); - return std::make_pair(true, ptr); + return std::make_pair(true, next); } } // namespace diff --git a/src/google/protobuf/io/coded_stream.h b/src/google/protobuf/io/coded_stream.h index 71a4f5fb25..63631d1f5c 100644 --- a/src/google/protobuf/io/coded_stream.h +++ b/src/google/protobuf/io/coded_stream.h @@ -161,6 +161,13 @@ class CodedOutputStream; class ZeroCopyInputStream; // zero_copy_stream.h class ZeroCopyOutputStream; // zero_copy_stream.h +template +T UnalignedLoad(const void* p) { + T res; + memcpy(&res, p, sizeof(T)); + return res; +} + // Class which reads and decodes binary data which is composed of varint- // encoded integers and fixed-width pieces. Wraps a ZeroCopyInputStream. // Most users will not need to deal with CodedInputStream. @@ -168,7 +175,7 @@ class ZeroCopyOutputStream; // zero_copy_stream.h // Most methods of CodedInputStream that return a bool return false if an // underlying I/O error occurs or if the data is malformed. Once such a // failure occurs, the CodedInputStream is broken and is no longer useful. -class LIBPROTOBUF_EXPORT CodedInputStream { +class PROTOBUF_EXPORT CodedInputStream { public: // Create a CodedInputStream that reads from the given ZeroCopyInputStream. explicit CodedInputStream(ZeroCopyInputStream* input); @@ -204,7 +211,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // Like GetDirectBufferPointer, but this method is inlined, and does not // attempt to Refresh() if the buffer is currently empty. - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE + PROTOBUF_ALWAYS_INLINE void GetDirectBufferPointerInline(const void** data, int* size); // Read raw bytes, copying them into the given buffer. @@ -212,15 +219,15 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // Like the above, with inlined optimizations. This should only be used // by the protobuf implementation. - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE + PROTOBUF_ALWAYS_INLINE bool InternalReadRawInline(void* buffer, int size); // Like ReadRaw, but reads into a string. - bool ReadString(string* buffer, int size); + bool ReadString(std::string* buffer, int size); // Like the above, with inlined optimizations. This should only be used // by the protobuf implementation. - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - bool InternalReadStringInline(string* buffer, int size); + PROTOBUF_ALWAYS_INLINE + bool InternalReadStringInline(std::string* buffer, int size); // Read a 32-bit little-endian integer. @@ -263,11 +270,11 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // Always inline because this is only called in one place per parse loop // but it is called for every iteration of said loop, so it should be fast. // GCC doesn't want to inline this by default. - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE uint32 ReadTag() { + PROTOBUF_ALWAYS_INLINE uint32 ReadTag() { return last_tag_ = ReadTagNoLastTag(); } - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE uint32 ReadTagNoLastTag(); + PROTOBUF_ALWAYS_INLINE uint32 ReadTagNoLastTag(); // This usually a faster alternative to ReadTag() when cutoff is a manifest // constant. It does particularly well for cutoff >= 127. The first part @@ -277,14 +284,14 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // above cutoff or is 0. (There's intentional wiggle room when tag is 0, // because that can arise in several ways, and for best performance we want // to avoid an extra "is tag == 0?" check here.) - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE + PROTOBUF_ALWAYS_INLINE std::pair ReadTagWithCutoff(uint32 cutoff) { std::pair result = ReadTagWithCutoffNoLastTag(cutoff); last_tag_ = result.first; return result; } - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE + PROTOBUF_ALWAYS_INLINE std::pair ReadTagWithCutoffNoLastTag(uint32 cutoff); // Usually returns true if calling ReadVarint32() now would produce the given @@ -294,7 +301,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // parameter. // Always inline because this collapses to a small number of instructions // when given a constant parameter, but GCC doesn't want to inline by default. - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool ExpectTag(uint32 expected); + PROTOBUF_ALWAYS_INLINE bool ExpectTag(uint32 expected); // Like above, except this reads from the specified buffer. The caller is // responsible for ensuring that the buffer is large enough to read a varint @@ -303,7 +310,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // // Returns a pointer beyond the expected tag if it was found, or NULL if it // was not. - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE + PROTOBUF_ALWAYS_INLINE static const uint8* ExpectTagFromArray(const uint8* buffer, uint32 expected); // Usually returns true if no more bytes can be read. Always returns false @@ -390,7 +397,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // This is unrelated to PushLimit()/PopLimit(). void SetTotalBytesLimit(int total_bytes_limit); - GOOGLE_PROTOBUF_DEPRECATED_MSG( + PROTOBUF_DEPRECATED_MSG( "Please use the single parameter version of SetTotalBytesLimit(). The " "second parameter is ignored.") void SetTotalBytesLimit(int total_bytes_limit, int) { @@ -409,6 +416,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // Sets the maximum recursion depth. The default is 100. void SetRecursionLimit(int limit); + int RecursionBudget() { return recursion_budget_; } // Increments the current recursion depth. Returns true if the depth is @@ -627,7 +635,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // stream. uint32 ReadTagFallback(uint32 first_byte_or_zero); uint32 ReadTagSlow(); - bool ReadStringFallback(string* buffer, int size); + bool ReadStringFallback(std::string* buffer, int size); // Return the size of the buffer. int BufferSize() const; @@ -683,7 +691,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream { // } // // delete coded_output; -class LIBPROTOBUF_EXPORT CodedOutputStream { +class PROTOBUF_EXPORT CodedOutputStream { public: // Create an CodedOutputStream that writes to the given ZeroCopyOutputStream. explicit CodedOutputStream(ZeroCopyOutputStream* output); @@ -737,11 +745,11 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { static uint8* WriteRawToArray(const void* buffer, int size, uint8* target); // Equivalent to WriteRaw(str.data(), str.size()). - void WriteString(const string& str); + void WriteString(const std::string& str); // Like WriteString() but writing directly to the target array. - static uint8* WriteStringToArray(const string& str, uint8* target); + static uint8* WriteStringToArray(const std::string& str, uint8* target); // Write the varint-encoded size of str followed by str. - static uint8* WriteStringWithSizeToArray(const string& str, uint8* target); + static uint8* WriteStringWithSizeToArray(const std::string& str, uint8* target); // Instructs the CodedOutputStream to allow the underlying @@ -788,7 +796,7 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { // but GCC by default doesn't want to inline this. void WriteTag(uint32 value); // Like WriteTag() but writing directly to the target array. - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE + PROTOBUF_ALWAYS_INLINE static uint8* WriteTagToArray(uint32 value, uint8* target); // Returns the number of bytes needed to encode the given value as a varint. @@ -908,7 +916,7 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { inline bool CodedInputStream::ReadVarint32(uint32* value) { uint32 v = 0; - if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_)) { + if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_)) { v = *buffer_; if (v < 0x80) { *value = v; @@ -922,7 +930,7 @@ inline bool CodedInputStream::ReadVarint32(uint32* value) { } inline bool CodedInputStream::ReadVarint64(uint64* value) { - if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_) && *buffer_ < 0x80) { + if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_) && *buffer_ < 0x80) { *value = *buffer_; Advance(1); return true; @@ -933,7 +941,7 @@ inline bool CodedInputStream::ReadVarint64(uint64* value) { } inline bool CodedInputStream::ReadVarintSizeAsInt(int* value) { - if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_)) { + if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_)) { int v = *buffer_; if (v < 0x80) { *value = v; @@ -984,7 +992,7 @@ inline const uint8* CodedInputStream::ReadLittleEndian64FromArray( inline bool CodedInputStream::ReadLittleEndian32(uint32* value) { #if defined(PROTOBUF_LITTLE_ENDIAN) - if (GOOGLE_PREDICT_TRUE(BufferSize() >= static_cast(sizeof(*value)))) { + if (PROTOBUF_PREDICT_TRUE(BufferSize() >= static_cast(sizeof(*value)))) { buffer_ = ReadLittleEndian32FromArray(buffer_, value); return true; } else { @@ -997,7 +1005,7 @@ inline bool CodedInputStream::ReadLittleEndian32(uint32* value) { inline bool CodedInputStream::ReadLittleEndian64(uint64* value) { #if defined(PROTOBUF_LITTLE_ENDIAN) - if (GOOGLE_PREDICT_TRUE(BufferSize() >= static_cast(sizeof(*value)))) { + if (PROTOBUF_PREDICT_TRUE(BufferSize() >= static_cast(sizeof(*value)))) { buffer_ = ReadLittleEndian64FromArray(buffer_, value); return true; } else { @@ -1010,7 +1018,7 @@ inline bool CodedInputStream::ReadLittleEndian64(uint64* value) { inline uint32 CodedInputStream::ReadTagNoLastTag() { uint32 v = 0; - if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_)) { + if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_)) { v = *buffer_; if (v < 0x80) { Advance(1); @@ -1027,7 +1035,7 @@ inline std::pair CodedInputStream::ReadTagWithCutoffNoLastTag( // constant, and things like "cutoff >= kMax1ByteVarint" to be evaluated at // compile time. uint32 first_byte_or_zero = 0; - if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_)) { + if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_)) { // Hot case: buffer_ non_empty, buffer_[0] in [1, 128). // TODO(gpike): Is it worth rearranging this? E.g., if the number of fields // is large enough then is it better to check for the two-byte case first? @@ -1041,8 +1049,8 @@ inline std::pair CodedInputStream::ReadTagWithCutoffNoLastTag( // Other hot case: cutoff >= 0x80, buffer_ has at least two bytes available, // and tag is two bytes. The latter is tested by bitwise-and-not of the // first byte and the second byte. - if (cutoff >= 0x80 && GOOGLE_PREDICT_TRUE(buffer_ + 1 < buffer_end_) && - GOOGLE_PREDICT_TRUE((buffer_[0] & ~buffer_[1]) >= 0x80)) { + if (cutoff >= 0x80 && PROTOBUF_PREDICT_TRUE(buffer_ + 1 < buffer_end_) && + PROTOBUF_PREDICT_TRUE((buffer_[0] & ~buffer_[1]) >= 0x80)) { const uint32 kMax2ByteVarint = (0x7f << 7) + 0x7f; uint32 tag = (1u << 7) * buffer_[1] + (buffer_[0] - 0x80); Advance(2); @@ -1071,14 +1079,14 @@ inline bool CodedInputStream::ConsumedEntireMessage() { inline bool CodedInputStream::ExpectTag(uint32 expected) { if (expected < (1 << 7)) { - if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_) && buffer_[0] == expected) { + if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_) && buffer_[0] == expected) { Advance(1); return true; } else { return false; } } else if (expected < (1 << 14)) { - if (GOOGLE_PREDICT_TRUE(BufferSize() >= 2) && + if (PROTOBUF_PREDICT_TRUE(BufferSize() >= 2) && buffer_[0] == static_cast(expected | 0x80) && buffer_[1] == static_cast(expected >> 7)) { Advance(2); @@ -1269,7 +1277,7 @@ inline size_t CodedOutputStream::VarintSize32SignExtended(int32 value) { } } -inline void CodedOutputStream::WriteString(const string& str) { +inline void CodedOutputStream::WriteString(const std::string& str) { WriteRaw(str.data(), static_cast(str.size())); } @@ -1283,7 +1291,7 @@ inline void CodedOutputStream::WriteRawMaybeAliased( } inline uint8* CodedOutputStream::WriteStringToArray( - const string& str, uint8* target) { + const std::string& str, uint8* target) { return WriteRawToArray(str.data(), static_cast(str.size()), target); } diff --git a/src/google/protobuf/io/coded_stream_inl.h b/src/google/protobuf/io/coded_stream_inl.h index d95b06e04e..df66282a3e 100644 --- a/src/google/protobuf/io/coded_stream_inl.h +++ b/src/google/protobuf/io/coded_stream_inl.h @@ -47,7 +47,7 @@ namespace google { namespace protobuf { namespace io { -inline bool CodedInputStream::InternalReadStringInline(string* buffer, +inline bool CodedInputStream::InternalReadStringInline(std::string* buffer, int size) { if (size < 0) return false; // security: size is often user-supplied diff --git a/src/google/protobuf/io/coded_stream_unittest.cc b/src/google/protobuf/io/coded_stream_unittest.cc index bcda8c81fd..52cc7c33b2 100644 --- a/src/google/protobuf/io/coded_stream_unittest.cc +++ b/src/google/protobuf/io/coded_stream_unittest.cc @@ -49,10 +49,12 @@ #include #include +#include + // This declares an unsigned long long integer literal in a portable way. // (The original macro is way too big and ruins my formatting.) #undef ULL -#define ULL(x) GOOGLE_ULONGLONG(x) +#define ULL(x) PROTOBUF_ULONGLONG(x) namespace google { diff --git a/src/google/protobuf/io/gzip_stream.h b/src/google/protobuf/io/gzip_stream.h index ba1475c7bc..b8eadfab81 100644 --- a/src/google/protobuf/io/gzip_stream.h +++ b/src/google/protobuf/io/gzip_stream.h @@ -48,12 +48,14 @@ #include #include +#include + namespace google { namespace protobuf { namespace io { // A ZeroCopyInputStream that reads compressed data through zlib -class LIBPROTOBUF_EXPORT GzipInputStream : public ZeroCopyInputStream { +class PROTOBUF_EXPORT GzipInputStream : public ZeroCopyInputStream { public: // Format key for constructor enum Format { @@ -107,8 +109,7 @@ class LIBPROTOBUF_EXPORT GzipInputStream : public ZeroCopyInputStream { GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(GzipInputStream); }; - -class LIBPROTOBUF_EXPORT GzipOutputStream : public ZeroCopyOutputStream { +class PROTOBUF_EXPORT GzipOutputStream : public ZeroCopyOutputStream { public: // Format key for constructor enum Format { @@ -119,7 +120,7 @@ class LIBPROTOBUF_EXPORT GzipOutputStream : public ZeroCopyOutputStream { ZLIB = 2, }; - struct LIBPROTOBUF_EXPORT Options { + struct PROTOBUF_EXPORT Options { // Defaults to GZIP. Format format; @@ -207,4 +208,6 @@ class LIBPROTOBUF_EXPORT GzipOutputStream : public ZeroCopyOutputStream { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_IO_GZIP_STREAM_H__ diff --git a/src/google/protobuf/io/printer.h b/src/google/protobuf/io/printer.h index 236aed43d1..ce693e54d6 100644 --- a/src/google/protobuf/io/printer.h +++ b/src/google/protobuf/io/printer.h @@ -42,6 +42,8 @@ #include #include +#include + namespace google { namespace protobuf { namespace io { @@ -49,15 +51,15 @@ namespace io { class ZeroCopyOutputStream; // zero_copy_stream.h // Records annotations about a Printer's output. -class LIBPROTOBUF_EXPORT AnnotationCollector { +class PROTOBUF_EXPORT AnnotationCollector { public: // Annotation is a ofset range and a payload pair. - typedef std::pair, string> Annotation; + typedef std::pair, std::string> Annotation; // Records that the bytes in file_path beginning with begin_offset and ending // before end_offset are associated with the SourceCodeInfo-style path. virtual void AddAnnotation(size_t begin_offset, size_t end_offset, - const string& file_path, + const std::string& file_path, const std::vector& path) = 0; // TODO(gerbens) I don't see why we need virtuals here. Just a vector of @@ -80,7 +82,7 @@ class AnnotationProtoCollector : public AnnotationCollector { // Override for AnnotationCollector::AddAnnotation. virtual void AddAnnotation(size_t begin_offset, size_t end_offset, - const string& file_path, + const std::string& file_path, const std::vector& path) { typename AnnotationProto::Annotation* annotation = annotation_proto_->add_annotation(); @@ -176,7 +178,7 @@ class AnnotationProtoCollector : public AnnotationCollector { // This code associates the span covering "call(bar,bar)" in the output with the // call_ descriptor. -class LIBPROTOBUF_EXPORT Printer { +class PROTOBUF_EXPORT Printer { public: // Create a printer that writes text to the given output stream. Use the // given character as the delimiter for variables. @@ -217,7 +219,7 @@ class LIBPROTOBUF_EXPORT Printer { // Link a subsitution variable emitted by the last call to Print to the file // with path file_name. - void Annotate(const char* varname, const string& file_name) { + void Annotate(const char* varname, const std::string& file_name) { Annotate(varname, varname, file_name); } @@ -226,7 +228,7 @@ class LIBPROTOBUF_EXPORT Printer { // at begin_varname's value and ends after the last character of the value // substituted for end_varname. void Annotate(const char* begin_varname, const char* end_varname, - const string& file_name) { + const std::string& file_name) { if (annotation_collector_ == NULL) { // Annotations aren't turned on for this Printer. return; @@ -240,12 +242,12 @@ class LIBPROTOBUF_EXPORT Printer { // substituted are identified by their names surrounded by delimiter // characters (as given to the constructor). The variable bindings are // defined by the given map. - void Print(const std::map& variables, const char* text); + void Print(const std::map& variables, const char* text); // Like the first Print(), except the substitutions are given as parameters. template void Print(const char* text, const Args&... args) { - std::map vars; + std::map vars; PrintInternal(&vars, text, args...); } @@ -260,7 +262,7 @@ class LIBPROTOBUF_EXPORT Printer { // Write a string to the output buffer. // This method does not look for newlines to add indentation. - void PrintRaw(const string& data); + void PrintRaw(const std::string& data); // Write a zero-delimited string to output buffer. // This method does not look for newlines to add indentation. @@ -275,8 +277,8 @@ class LIBPROTOBUF_EXPORT Printer { // formatting text using named variables (eq. "$foo$) from a lookup map (vars) // and variables directly supplied by arguments (eq "$1$" meaning first // argument which is the zero index element of args). - void FormatInternal(const std::vector& args, - const std::map& vars, const char* format); + void FormatInternal(const std::vector& args, + const std::map& vars, const char* format); // True if any write to the underlying stream failed. (We don't just // crash in this case because this is an I/O failure, not a programming @@ -291,16 +293,16 @@ class LIBPROTOBUF_EXPORT Printer { // substituted for end_varname. Note that begin_varname and end_varname // may refer to the same variable. void Annotate(const char* begin_varname, const char* end_varname, - const string& file_path, const std::vector& path); + const std::string& file_path, const std::vector& path); // Base case - void PrintInternal(std::map* vars, const char* text) { + void PrintInternal(std::map* vars, const char* text) { Print(*vars, text); } template - void PrintInternal(std::map* vars, const char* text, - const char* key, const string& value, + void PrintInternal(std::map* vars, const char* text, + const char* key, const std::string& value, const Args&... args) { (*vars)[key] = value; PrintInternal(vars, text, args...); @@ -323,7 +325,7 @@ class LIBPROTOBUF_EXPORT Printer { inline void IndentIfAtStart(); const char* WriteVariable( - const std::vector& args, const std::map& vars, + const std::vector& args, const std::map& vars, const char* format, int* arg_index, std::vector* annotations); @@ -337,7 +339,7 @@ class LIBPROTOBUF_EXPORT Printer { // used to calculate annotation ranges in the substitutions_ map below. size_t offset_; - string indent_; + std::string indent_; bool at_start_of_line_; bool failed_; @@ -348,12 +350,12 @@ class LIBPROTOBUF_EXPORT Printer { // start offset is the beginning of the substitution; the end offset is the // last byte of the substitution plus one (such that (end - start) is the // length of the substituted string). - std::map > substitutions_; + std::map > substitutions_; // Keeps track of the keys in substitutions_ that need to be updated when // indents are inserted. These are keys that refer to the beginning of the // current line. - std::vector line_start_variables_; + std::vector line_start_variables_; // Returns true and sets range to the substitution range in the output for // varname if varname was used once in the last call to Print. If varname @@ -373,4 +375,6 @@ class LIBPROTOBUF_EXPORT Printer { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_IO_PRINTER_H__ diff --git a/src/google/protobuf/io/tokenizer.h b/src/google/protobuf/io/tokenizer.h index 59b6772933..f6c3d273fe 100644 --- a/src/google/protobuf/io/tokenizer.h +++ b/src/google/protobuf/io/tokenizer.h @@ -42,6 +42,8 @@ #include #include +#include + namespace google { namespace protobuf { namespace io { @@ -61,7 +63,7 @@ typedef int ColumnNumber; // Abstract interface for an object which collects the errors that occur // during parsing. A typical implementation might simply print the errors // to stdout. -class LIBPROTOBUF_EXPORT ErrorCollector { +class PROTOBUF_EXPORT ErrorCollector { public: inline ErrorCollector() {} virtual ~ErrorCollector(); @@ -70,13 +72,13 @@ class LIBPROTOBUF_EXPORT ErrorCollector { // column numbers. The numbers are zero-based, so you may want to add // 1 to each before printing them. virtual void AddError(int line, ColumnNumber column, - const string& message) = 0; + const std::string& message) = 0; // Indicates that there was a warning in the input at the given line and // column numbers. The numbers are zero-based, so you may want to add // 1 to each before printing them. virtual void AddWarning(int line, ColumnNumber column, - const string& message) { } + const std::string& message) { } private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ErrorCollector); @@ -88,7 +90,7 @@ class LIBPROTOBUF_EXPORT ErrorCollector { // precise descriptions. Whitespace and comments are skipped. By default, // C- and C++-style comments are recognized, but other styles can be used by // calling set_comment_style(). -class LIBPROTOBUF_EXPORT Tokenizer { +class PROTOBUF_EXPORT Tokenizer { public: // Construct a Tokenizer that reads and tokenizes text from the given // input stream and writes errors to the given error_collector. @@ -124,7 +126,7 @@ class LIBPROTOBUF_EXPORT Tokenizer { // Structure representing a token read from the token stream. struct Token { TokenType type; - string text; // The exact text of the token as it appeared in + std::string text; // The exact text of the token as it appeared in // the input. e.g. tokens of TYPE_STRING will still // be escaped and in quotes. @@ -190,31 +192,31 @@ class LIBPROTOBUF_EXPORT Tokenizer { // /* Block comment attached to // * grault. */ // optional int32 grault = 6; - bool NextWithComments(string* prev_trailing_comments, - std::vector* detached_comments, - string* next_leading_comments); + bool NextWithComments(std::string* prev_trailing_comments, + std::vector* detached_comments, + std::string* next_leading_comments); // Parse helpers --------------------------------------------------- // Parses a TYPE_FLOAT token. This never fails, so long as the text actually // comes from a TYPE_FLOAT token parsed by Tokenizer. If it doesn't, the // result is undefined (possibly an assert failure). - static double ParseFloat(const string& text); + static double ParseFloat(const std::string& text); // Parses a TYPE_STRING token. This never fails, so long as the text actually // comes from a TYPE_STRING token parsed by Tokenizer. If it doesn't, the // result is undefined (possibly an assert failure). - static void ParseString(const string& text, string* output); + static void ParseString(const std::string& text, std::string* output); // Identical to ParseString, but appends to output. - static void ParseStringAppend(const string& text, string* output); + static void ParseStringAppend(const std::string& text, std::string* output); // Parses a TYPE_INTEGER token. Returns false if the result would be // greater than max_value. Otherwise, returns true and sets *output to the // result. If the text is not from a Token of type TYPE_INTEGER originally // parsed by a Tokenizer, the result is undefined (possibly an assert // failure). - static bool ParseInteger(const string& text, uint64 max_value, + static bool ParseInteger(const std::string& text, uint64 max_value, uint64* output); // Options --------------------------------------------------------- @@ -250,7 +252,7 @@ class LIBPROTOBUF_EXPORT Tokenizer { } // External helper: validate an identifier. - static bool IsIdentifier(const string& text); + static bool IsIdentifier(const std::string& text); // ----------------------------------------------------------------- private: @@ -276,7 +278,7 @@ class LIBPROTOBUF_EXPORT Tokenizer { // Call RecordTo(&str) to start recording and StopRecording() to stop. // E.g. StartToken() calls RecordTo(¤t_.text). record_start_ is the // position within the current buffer where recording started. - string* record_target_; + std::string* record_target_; int record_start_; // Options. @@ -299,7 +301,7 @@ class LIBPROTOBUF_EXPORT Tokenizer { // Read a new buffer from the input. void Refresh(); - inline void RecordTo(string* target); + inline void RecordTo(std::string* target); inline void StopRecording(); // Called when the current character is the first character of a new @@ -311,7 +313,7 @@ class LIBPROTOBUF_EXPORT Tokenizer { inline void EndToken(); // Convenience method to add an error at the current line and column. - void AddError(const string& message) { + void AddError(const std::string& message) { error_collector_->AddError(line_, column_, message); } @@ -334,9 +336,9 @@ class LIBPROTOBUF_EXPORT Tokenizer { TokenType ConsumeNumber(bool started_with_zero, bool started_with_dot); // Consume the rest of a line. - void ConsumeLineComment(string* content); + void ConsumeLineComment(std::string* content); // Consume until "*/". - void ConsumeBlockComment(string* content); + void ConsumeBlockComment(std::string* content); enum NextCommentStatus { // Started a line comment. @@ -399,7 +401,7 @@ inline const Tokenizer::Token& Tokenizer::previous() { return previous_; } -inline void Tokenizer::ParseString(const string& text, string* output) { +inline void Tokenizer::ParseString(const std::string& text, std::string* output) { output->clear(); ParseStringAppend(text, output); } @@ -408,4 +410,6 @@ inline void Tokenizer::ParseString(const string& text, string* output) { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_IO_TOKENIZER_H__ diff --git a/src/google/protobuf/io/zero_copy_stream.h b/src/google/protobuf/io/zero_copy_stream.h index f532d75967..de2374b513 100644 --- a/src/google/protobuf/io/zero_copy_stream.h +++ b/src/google/protobuf/io/zero_copy_stream.h @@ -110,6 +110,8 @@ #include #include +#include + namespace google { namespace protobuf { @@ -121,7 +123,7 @@ class ZeroCopyOutputStream; // Abstract interface similar to an input stream but designed to minimize // copying. -class LIBPROTOBUF_EXPORT ZeroCopyInputStream { +class PROTOBUF_EXPORT ZeroCopyInputStream { public: ZeroCopyInputStream() {} virtual ~ZeroCopyInputStream() {} @@ -178,7 +180,7 @@ class LIBPROTOBUF_EXPORT ZeroCopyInputStream { // Abstract interface similar to an output stream but designed to minimize // copying. -class LIBPROTOBUF_EXPORT ZeroCopyOutputStream { +class PROTOBUF_EXPORT ZeroCopyOutputStream { public: ZeroCopyOutputStream() {} virtual ~ZeroCopyOutputStream() {} @@ -245,4 +247,6 @@ class LIBPROTOBUF_EXPORT ZeroCopyOutputStream { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_H__ diff --git a/src/google/protobuf/io/zero_copy_stream_impl.h b/src/google/protobuf/io/zero_copy_stream_impl.h index 206fd0d459..46062a855e 100644 --- a/src/google/protobuf/io/zero_copy_stream_impl.h +++ b/src/google/protobuf/io/zero_copy_stream_impl.h @@ -47,6 +47,8 @@ #include +#include + namespace google { namespace protobuf { namespace io { @@ -60,7 +62,7 @@ namespace io { // The latter will introduce an extra layer of buffering, harming performance. // Also, it's conceivable that FileInputStream could someday be enhanced // to use zero-copy file descriptors on OSs which support them. -class LIBPROTOBUF_EXPORT FileInputStream : public ZeroCopyInputStream { +class PROTOBUF_EXPORT FileInputStream : public ZeroCopyInputStream { public: // Creates a stream that reads from the given Unix file descriptor. // If a block_size is given, it specifies the number of bytes that @@ -93,7 +95,7 @@ class LIBPROTOBUF_EXPORT FileInputStream : public ZeroCopyInputStream { int64 ByteCount() const override; private: - class LIBPROTOBUF_EXPORT CopyingFileInputStream : public CopyingInputStream { + class PROTOBUF_EXPORT CopyingFileInputStream : public CopyingInputStream { public: CopyingFileInputStream(int file_descriptor); ~CopyingFileInputStream() override; @@ -137,7 +139,7 @@ class LIBPROTOBUF_EXPORT FileInputStream : public ZeroCopyInputStream { // harming performance. Also, it's conceivable that FileOutputStream could // someday be enhanced to use zero-copy file descriptors on OSs which // support them. -class LIBPROTOBUF_EXPORT FileOutputStream : public ZeroCopyOutputStream { +class PROTOBUF_EXPORT FileOutputStream : public ZeroCopyOutputStream { public: // Creates a stream that writes to the given Unix file descriptor. // If a block_size is given, it specifies the size of the buffers @@ -175,7 +177,7 @@ class LIBPROTOBUF_EXPORT FileOutputStream : public ZeroCopyOutputStream { int64 ByteCount() const override; private: - class LIBPROTOBUF_EXPORT CopyingFileOutputStream : public CopyingOutputStream { + class PROTOBUF_EXPORT CopyingFileOutputStream : public CopyingOutputStream { public: CopyingFileOutputStream(int file_descriptor); ~CopyingFileOutputStream() override; @@ -211,7 +213,7 @@ class LIBPROTOBUF_EXPORT FileOutputStream : public ZeroCopyOutputStream { // // Note that for reading files (or anything represented by a file descriptor), // FileInputStream is more efficient. -class LIBPROTOBUF_EXPORT IstreamInputStream : public ZeroCopyInputStream { +class PROTOBUF_EXPORT IstreamInputStream : public ZeroCopyInputStream { public: // Creates a stream that reads from the given C++ istream. // If a block_size is given, it specifies the number of bytes that @@ -226,7 +228,7 @@ class LIBPROTOBUF_EXPORT IstreamInputStream : public ZeroCopyInputStream { int64 ByteCount() const override; private: - class LIBPROTOBUF_EXPORT CopyingIstreamInputStream : public CopyingInputStream { + class PROTOBUF_EXPORT CopyingIstreamInputStream : public CopyingInputStream { public: CopyingIstreamInputStream(std::istream* input); ~CopyingIstreamInputStream() override; @@ -254,7 +256,7 @@ class LIBPROTOBUF_EXPORT IstreamInputStream : public ZeroCopyInputStream { // // Note that for writing files (or anything represented by a file descriptor), // FileOutputStream is more efficient. -class LIBPROTOBUF_EXPORT OstreamOutputStream : public ZeroCopyOutputStream { +class PROTOBUF_EXPORT OstreamOutputStream : public ZeroCopyOutputStream { public: // Creates a stream that writes to the given C++ ostream. // If a block_size is given, it specifies the size of the buffers @@ -269,7 +271,8 @@ class LIBPROTOBUF_EXPORT OstreamOutputStream : public ZeroCopyOutputStream { int64 ByteCount() const override; private: - class LIBPROTOBUF_EXPORT CopyingOstreamOutputStream : public CopyingOutputStream { + class PROTOBUF_EXPORT CopyingOstreamOutputStream + : public CopyingOutputStream { public: CopyingOstreamOutputStream(std::ostream* output); ~CopyingOstreamOutputStream() override; @@ -299,7 +302,7 @@ class LIBPROTOBUF_EXPORT OstreamOutputStream : public ZeroCopyOutputStream { // ConcatenatingInputStream may do odd things. It is suggested that you do // not use ConcatenatingInputStream on streams that might produce read errors // other than end-of-stream. -class LIBPROTOBUF_EXPORT ConcatenatingInputStream : public ZeroCopyInputStream { +class PROTOBUF_EXPORT ConcatenatingInputStream : public ZeroCopyInputStream { public: // All streams passed in as well as the array itself must remain valid // until the ConcatenatingInputStream is destroyed. @@ -327,7 +330,7 @@ class LIBPROTOBUF_EXPORT ConcatenatingInputStream : public ZeroCopyInputStream { // A ZeroCopyInputStream which wraps some other stream and limits it to // a particular byte count. -class LIBPROTOBUF_EXPORT LimitingInputStream : public ZeroCopyInputStream { +class PROTOBUF_EXPORT LimitingInputStream : public ZeroCopyInputStream { public: LimitingInputStream(ZeroCopyInputStream* input, int64 limit); ~LimitingInputStream() override; @@ -353,4 +356,6 @@ class LIBPROTOBUF_EXPORT LimitingInputStream : public ZeroCopyInputStream { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_H__ diff --git a/src/google/protobuf/io/zero_copy_stream_impl_lite.h b/src/google/protobuf/io/zero_copy_stream_impl_lite.h index da4ef4556f..07d188499e 100644 --- a/src/google/protobuf/io/zero_copy_stream_impl_lite.h +++ b/src/google/protobuf/io/zero_copy_stream_impl_lite.h @@ -53,6 +53,8 @@ #include +#include + namespace google { namespace protobuf { namespace io { @@ -60,7 +62,7 @@ namespace io { // =================================================================== // A ZeroCopyInputStream backed by an in-memory array of bytes. -class LIBPROTOBUF_EXPORT ArrayInputStream : public ZeroCopyInputStream { +class PROTOBUF_EXPORT ArrayInputStream : public ZeroCopyInputStream { public: // Create an InputStream that returns the bytes pointed to by "data". // "data" remains the property of the caller but must remain valid until @@ -94,7 +96,7 @@ class LIBPROTOBUF_EXPORT ArrayInputStream : public ZeroCopyInputStream { // =================================================================== // A ZeroCopyOutputStream backed by an in-memory array of bytes. -class LIBPROTOBUF_EXPORT ArrayOutputStream : public ZeroCopyOutputStream { +class PROTOBUF_EXPORT ArrayOutputStream : public ZeroCopyOutputStream { public: // Create an OutputStream that writes to the bytes pointed to by "data". // "data" remains the property of the caller but must remain valid until @@ -126,7 +128,7 @@ class LIBPROTOBUF_EXPORT ArrayOutputStream : public ZeroCopyOutputStream { // =================================================================== // A ZeroCopyOutputStream which appends bytes to a string. -class LIBPROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream { +class PROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream { public: // Create a StringOutputStream which appends bytes to the given string. // The string remains property of the caller, but it is mutated in arbitrary @@ -137,7 +139,7 @@ class LIBPROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream { // Hint: If you call target->reserve(n) before creating the stream, // the first call to Next() will return at least n bytes of buffer // space. - explicit StringOutputStream(string* target); + explicit StringOutputStream(std::string* target); ~StringOutputStream() override = default; // implements ZeroCopyOutputStream --------------------------------- @@ -146,12 +148,12 @@ class LIBPROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream { int64 ByteCount() const override; protected: - void SetString(string* target); + void SetString(std::string* target); private: static const int kMinimumSize = 16; - string* target_; + std::string* target_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringOutputStream); }; @@ -173,7 +175,7 @@ class LIBPROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream { // CopyingInputStream implementations should avoid buffering if possible. // CopyingInputStreamAdaptor does its own buffering and will read data // in large blocks. -class LIBPROTOBUF_EXPORT CopyingInputStream { +class PROTOBUF_EXPORT CopyingInputStream { public: virtual ~CopyingInputStream() {} @@ -199,7 +201,7 @@ class LIBPROTOBUF_EXPORT CopyingInputStream { // If you want to read from file descriptors or C++ istreams, this is // already implemented for you: use FileInputStream or IstreamInputStream // respectively. -class LIBPROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream { +class PROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream { public: // Creates a stream that reads from the given CopyingInputStream. // If a block_size is given, it specifies the number of bytes that @@ -267,7 +269,7 @@ class LIBPROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream // CopyingOutputStream implementations should avoid buffering if possible. // CopyingOutputStreamAdaptor does its own buffering and will write data // in large blocks. -class LIBPROTOBUF_EXPORT CopyingOutputStream { +class PROTOBUF_EXPORT CopyingOutputStream { public: virtual ~CopyingOutputStream() {} @@ -283,7 +285,7 @@ class LIBPROTOBUF_EXPORT CopyingOutputStream { // If you want to write to file descriptors or C++ ostreams, this is // already implemented for you: use FileOutputStream or OstreamOutputStream // respectively. -class LIBPROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStream { +class PROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStream { public: // Creates a stream that writes to the given Unix file descriptor. // If a block_size is given, it specifies the size of the buffers @@ -356,7 +358,7 @@ class LIBPROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStrea // Return a pointer to mutable characters underlying the given string. The // return value is valid until the next time the string is resized. We // trust the caller to treat the return value as an array of length s->size(). -inline char* mutable_string_data(string* s) { +inline char* mutable_string_data(std::string* s) { #ifdef LANG_CXX11 // This should be simpler & faster than string_as_array() because the latter // is guaranteed to return NULL when *s is empty, so it has to check for that. @@ -370,7 +372,7 @@ inline char* mutable_string_data(string* s) { // ({ char* p = mutable_string_data(s); make_pair(p, p != NULL); }) // Sometimes it's faster: in some scenarios p cannot be NULL, and then the // code can avoid that check. -inline std::pair as_string_data(string* s) { +inline std::pair as_string_data(std::string* s) { char *p = mutable_string_data(s); #ifdef LANG_CXX11 return std::make_pair(p, true); @@ -383,4 +385,6 @@ inline std::pair as_string_data(string* s) { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__ diff --git a/src/google/protobuf/lite_unittest.cc b/src/google/protobuf/lite_unittest.cc index ee44f51b19..e893316b37 100644 --- a/src/google/protobuf/lite_unittest.cc +++ b/src/google/protobuf/lite_unittest.cc @@ -46,9 +46,10 @@ #include #include +// When string == std::string inside Google, we can remove this typedef. #include -using std::string; +typedef std::string ProtoString; namespace google { namespace protobuf { @@ -75,7 +76,7 @@ void SetAllTypesInEmptyMessageUnknownFields( protobuf_unittest::TestAllTypesLite message; TestUtilLite::ExpectClear(message); TestUtilLite::SetAllFields(&message); - string data = message.SerializeAsString(); + ProtoString data = message.SerializeAsString(); empty_message->ParseFromString(data); } @@ -87,12 +88,12 @@ void SetSomeTypesInEmptyMessageUnknownFields( message.set_optional_int64(102); message.set_optional_uint32(103); message.set_optional_uint64(104); - string data = message.SerializeAsString(); + ProtoString data = message.SerializeAsString(); empty_message->ParseFromString(data); } TEST(Lite, AllLite1) { - string data; + ProtoString data; { protobuf_unittest::TestAllTypesLite message, message2, message3; @@ -112,13 +113,13 @@ TEST(Lite, AllLite1) { } TEST(Lite, AllLite2) { - string data; + ProtoString data; { protobuf_unittest::TestAllExtensionsLite message, message2, message3; TestUtilLite::ExpectExtensionsClear(message); TestUtilLite::SetAllExtensions(&message); message2.CopyFrom(message); - string extensions_data = message.SerializeAsString(); + ProtoString extensions_data = message.SerializeAsString(); message3.ParseFromString(extensions_data); TestUtilLite::ExpectAllExtensionsSet(message); TestUtilLite::ExpectAllExtensionsSet(message2); @@ -131,7 +132,7 @@ TEST(Lite, AllLite2) { } TEST(Lite, AllLite3) { - string data, packed_data; + ProtoString data, packed_data; { protobuf_unittest::TestPackedTypesLite message, message2, message3; @@ -154,7 +155,7 @@ TEST(Lite, AllLite3) { TestUtilLite::ExpectPackedExtensionsClear(message); TestUtilLite::SetPackedExtensions(&message); message2.CopyFrom(message); - string packed_extensions_data = message.SerializeAsString(); + ProtoString packed_extensions_data = message.SerializeAsString(); EXPECT_EQ(packed_extensions_data, packed_data); message3.ParseFromString(packed_extensions_data); TestUtilLite::ExpectPackedExtensionsSet(message); @@ -168,7 +169,7 @@ TEST(Lite, AllLite3) { } TEST(Lite, AllLite5) { - string data; + ProtoString data; { // Test that if an optional or required message/group field appears multiple @@ -202,7 +203,7 @@ TEST(Lite, AllLite5) { #undef ASSIGN_REPEATED_GROUP - string buffer; + ProtoString buffer; generator.SerializeToString(&buffer); unittest::TestParsingMergeLite parsing_merge; parsing_merge.ParseFromString(buffer); @@ -225,7 +226,7 @@ TEST(Lite, AllLite5) { } TEST(Lite, AllLite6) { - string data; + ProtoString data; // Test unknown fields support for lite messages. { @@ -246,7 +247,7 @@ TEST(Lite, AllLite6) { } TEST(Lite, AllLite7) { - string data; + ProtoString data; { protobuf_unittest::TestAllExtensionsLite message, message2; @@ -266,7 +267,7 @@ TEST(Lite, AllLite7) { } TEST(Lite, AllLite8) { - string data; + ProtoString data; { protobuf_unittest::TestPackedTypesLite message, message2; @@ -286,7 +287,7 @@ TEST(Lite, AllLite8) { } TEST(Lite, AllLite9) { - string data; + ProtoString data; { protobuf_unittest::TestPackedExtensionsLite message, message2; @@ -306,7 +307,7 @@ TEST(Lite, AllLite9) { } TEST(Lite, AllLite10) { - string data; + ProtoString data; { // Test Unknown fields swap @@ -314,7 +315,7 @@ TEST(Lite, AllLite10) { SetAllTypesInEmptyMessageUnknownFields(&empty_message); SetSomeTypesInEmptyMessageUnknownFields(&empty_message2); data = empty_message.SerializeAsString(); - string data2 = empty_message2.SerializeAsString(); + ProtoString data2 = empty_message2.SerializeAsString(); empty_message.Swap(&empty_message2); EXPECT_EQ(data, empty_message2.SerializeAsString()); EXPECT_EQ(data2, empty_message.SerializeAsString()); @@ -322,7 +323,7 @@ TEST(Lite, AllLite10) { } TEST(Lite, AllLite11) { - string data; + ProtoString data; { // Test unknown fields swap with self @@ -335,7 +336,7 @@ TEST(Lite, AllLite11) { } TEST(Lite, AllLite12) { - string data; + ProtoString data; { // Test MergeFrom with unknown fields @@ -365,12 +366,12 @@ TEST(Lite, AllLite12) { } TEST(Lite, AllLite13) { - string data; + ProtoString data; { // Test unknown enum value protobuf_unittest::TestAllTypesLite message; - string buffer; + ProtoString buffer; { io::StringOutputStream output_stream(&buffer); io::CodedOutputStream coded_output(&output_stream); @@ -390,7 +391,7 @@ TEST(Lite, AllLite13) { } TEST(Lite, AllLite14) { - string data; + ProtoString data; { // Test Clear with unknown fields @@ -404,7 +405,7 @@ TEST(Lite, AllLite14) { // Tests for map lite ============================================= TEST(Lite, AllLite15) { - string data; + ProtoString data; { // Accessors @@ -419,7 +420,7 @@ TEST(Lite, AllLite15) { } TEST(Lite, AllLite16) { - string data; + ProtoString data; { // SetMapFieldsInitialized @@ -431,7 +432,7 @@ TEST(Lite, AllLite16) { } TEST(Lite, AllLite17) { - string data; + ProtoString data; { // Clear @@ -444,7 +445,7 @@ TEST(Lite, AllLite17) { } TEST(Lite, AllLite18) { - string data; + ProtoString data; { // ClearMessageMap @@ -457,7 +458,7 @@ TEST(Lite, AllLite18) { } TEST(Lite, AllLite19) { - string data; + ProtoString data; { // CopyFrom @@ -474,7 +475,7 @@ TEST(Lite, AllLite19) { } TEST(Lite, AllLite20) { - string data; + ProtoString data; { // CopyFromMessageMap @@ -492,7 +493,7 @@ TEST(Lite, AllLite20) { } TEST(Lite, AllLite21) { - string data; + ProtoString data; { // SwapWithEmpty @@ -509,7 +510,7 @@ TEST(Lite, AllLite21) { } TEST(Lite, AllLite22) { - string data; + ProtoString data; { // SwapWithSelf @@ -524,7 +525,7 @@ TEST(Lite, AllLite22) { } TEST(Lite, AllLite23) { - string data; + ProtoString data; { // SwapWithOther @@ -541,7 +542,7 @@ TEST(Lite, AllLite23) { } TEST(Lite, AllLite24) { - string data; + ProtoString data; { // CopyConstructor @@ -554,7 +555,7 @@ TEST(Lite, AllLite24) { } TEST(Lite, AllLite25) { - string data; + ProtoString data; { // CopyAssignmentOperator @@ -572,7 +573,7 @@ TEST(Lite, AllLite25) { } TEST(Lite, AllLite26) { - string data; + ProtoString data; { // NonEmptyMergeFrom @@ -594,7 +595,7 @@ TEST(Lite, AllLite26) { } TEST(Lite, AllLite27) { - string data; + ProtoString data; { // MergeFromMessageMap @@ -612,12 +613,12 @@ TEST(Lite, AllLite27) { } TEST(Lite, AllLite28) { - string data; + ProtoString data; { // Test the generated SerializeWithCachedSizesToArray() protobuf_unittest::TestMapLite message1, message2; - string data; + ProtoString data; MapLiteTestUtil::SetMapFields(&message1); int size = message1.ByteSize(); data.resize(size); @@ -630,14 +631,14 @@ TEST(Lite, AllLite28) { } TEST(Lite, AllLite29) { - string data; + ProtoString data; { // Test the generated SerializeWithCachedSizes() protobuf_unittest::TestMapLite message1, message2; MapLiteTestUtil::SetMapFields(&message1); int size = message1.ByteSize(); - string data; + ProtoString data; data.resize(size); { // Allow the output stream to buffer only one byte at a time. @@ -654,7 +655,7 @@ TEST(Lite, AllLite29) { TEST(Lite, AllLite32) { - string data; + ProtoString data; { // Proto2UnknownEnum @@ -663,14 +664,14 @@ TEST(Lite, AllLite32) { protobuf_unittest::E_PROTO2_MAP_ENUM_FOO_LITE; (*from.mutable_unknown_map_field())[0] = protobuf_unittest::E_PROTO2_MAP_ENUM_EXTRA_LITE; - string data; + ProtoString data; from.SerializeToString(&data); protobuf_unittest::TestEnumMapLite to; EXPECT_TRUE(to.ParseFromString(data)); EXPECT_EQ(0, to.unknown_map_field().size()); EXPECT_FALSE(to.mutable_unknown_fields()->empty()); - EXPECT_EQ(1, to.known_map_field().size()); + ASSERT_EQ(1, to.known_map_field().size()); EXPECT_EQ(protobuf_unittest::PROTO2_MAP_ENUM_FOO_LITE, to.known_map_field().at(0)); @@ -678,141 +679,147 @@ TEST(Lite, AllLite32) { from.Clear(); to.SerializeToString(&data); EXPECT_TRUE(from.ParseFromString(data)); - EXPECT_EQ(1, from.known_map_field().size()); + ASSERT_EQ(1, from.known_map_field().size()); EXPECT_EQ(protobuf_unittest::E_PROTO2_MAP_ENUM_FOO_LITE, from.known_map_field().at(0)); - EXPECT_EQ(1, from.unknown_map_field().size()); + ASSERT_EQ(1, from.unknown_map_field().size()); EXPECT_EQ(protobuf_unittest::E_PROTO2_MAP_ENUM_EXTRA_LITE, from.unknown_map_field().at(0)); } } TEST(Lite, AllLite33) { - string data; + ProtoString data; { // StandardWireFormat protobuf_unittest::TestMapLite message; - string data = "\x0A\x04\x08\x01\x10\x01"; + ProtoString data = "\x0A\x04\x08\x01\x10\x01"; EXPECT_TRUE(message.ParseFromString(data)); - EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_EQ(1, message.map_int32_int32().size()); EXPECT_EQ(1, message.map_int32_int32().at(1)); } } TEST(Lite, AllLite34) { - string data; + ProtoString data; { // UnorderedWireFormat protobuf_unittest::TestMapLite message; // put value before key in wire format - string data = "\x0A\x04\x10\x01\x08\x02"; + ProtoString data = "\x0A\x04\x10\x01\x08\x02"; EXPECT_TRUE(message.ParseFromString(data)); - EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_EQ(1, message.map_int32_int32().size()); + ASSERT_NE(message.map_int32_int32().find(2), + message.map_int32_int32().end()); EXPECT_EQ(1, message.map_int32_int32().at(2)); } } TEST(Lite, AllLite35) { - string data; + ProtoString data; { // DuplicatedKeyWireFormat protobuf_unittest::TestMapLite message; // Two key fields in wire format - string data = "\x0A\x06\x08\x01\x08\x02\x10\x01"; + ProtoString data = "\x0A\x06\x08\x01\x08\x02\x10\x01"; EXPECT_TRUE(message.ParseFromString(data)); - EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_EQ(1, message.map_int32_int32().size()); EXPECT_EQ(1, message.map_int32_int32().at(2)); } } TEST(Lite, AllLite36) { - string data; + ProtoString data; { // DuplicatedValueWireFormat protobuf_unittest::TestMapLite message; // Two value fields in wire format - string data = "\x0A\x06\x08\x01\x10\x01\x10\x02"; + ProtoString data = "\x0A\x06\x08\x01\x10\x01\x10\x02"; EXPECT_TRUE(message.ParseFromString(data)); - EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_EQ(1, message.map_int32_int32().size()); EXPECT_EQ(2, message.map_int32_int32().at(1)); } } TEST(Lite, AllLite37) { - string data; + ProtoString data; { // MissedKeyWireFormat protobuf_unittest::TestMapLite message; // No key field in wire format - string data = "\x0A\x02\x10\x01"; + ProtoString data = "\x0A\x02\x10\x01"; EXPECT_TRUE(message.ParseFromString(data)); - EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_EQ(1, message.map_int32_int32().size()); + ASSERT_NE(message.map_int32_int32().find(0), + message.map_int32_int32().end()); EXPECT_EQ(1, message.map_int32_int32().at(0)); } } TEST(Lite, AllLite38) { - string data; + ProtoString data; { // MissedValueWireFormat protobuf_unittest::TestMapLite message; // No value field in wire format - string data = "\x0A\x02\x08\x01"; + ProtoString data = "\x0A\x02\x08\x01"; EXPECT_TRUE(message.ParseFromString(data)); - EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_EQ(1, message.map_int32_int32().size()); + ASSERT_NE(message.map_int32_int32().find(1), + message.map_int32_int32().end()); EXPECT_EQ(0, message.map_int32_int32().at(1)); } } TEST(Lite, AllLite39) { - string data; + ProtoString data; { // UnknownFieldWireFormat protobuf_unittest::TestMapLite message; // Unknown field in wire format - string data = "\x0A\x06\x08\x02\x10\x03\x18\x01"; + ProtoString data = "\x0A\x06\x08\x02\x10\x03\x18\x01"; EXPECT_TRUE(message.ParseFromString(data)); - EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_EQ(1, message.map_int32_int32().size()); EXPECT_EQ(3, message.map_int32_int32().at(2)); } } TEST(Lite, AllLite40) { - string data; + ProtoString data; { // CorruptedWireFormat protobuf_unittest::TestMapLite message; // corrupted data in wire format - string data = "\x0A\x06\x08\x02\x11\x03"; + ProtoString data = "\x0A\x06\x08\x02\x11\x03"; EXPECT_FALSE(message.ParseFromString(data)); } } TEST(Lite, AllLite41) { - string data; + ProtoString data; { // IsInitialized @@ -831,7 +838,7 @@ TEST(Lite, AllLite41) { } TEST(Lite, AllLite42) { - string data; + ProtoString data; { // Check that adding more values to enum does not corrupt message @@ -840,7 +847,7 @@ TEST(Lite, AllLite42) { v2_message.set_int_field(800); // Set enum field to the value not understood by the old client. v2_message.set_enum_field(protobuf_unittest::V2_SECOND); - string v2_bytes = v2_message.SerializeAsString(); + ProtoString v2_bytes = v2_message.SerializeAsString(); protobuf_unittest::V1MessageLite v1_message; v1_message.ParseFromString(v2_bytes); @@ -851,7 +858,7 @@ TEST(Lite, AllLite42) { EXPECT_EQ(v1_message.enum_field(), protobuf_unittest::V1_FIRST); // However, when re-serialized, it should preserve enum value. - string v1_bytes = v1_message.SerializeAsString(); + ProtoString v1_bytes = v1_message.SerializeAsString(); protobuf_unittest::V2MessageLite same_v2_message; same_v2_message.ParseFromString(v1_bytes); @@ -867,7 +874,7 @@ TEST(Lite, AllLite43) { protobuf_unittest::TestOneofParsingLite message1; message1.set_oneof_int32(17); - string serialized; + ProtoString serialized; EXPECT_TRUE(message1.SerializeToString(&serialized)); // Submessage @@ -909,7 +916,7 @@ TEST(Lite, AllLite44) { { protobuf_unittest::TestOneofParsingLite original; original.set_oneof_int32(17); - string serialized; + ProtoString serialized; EXPECT_TRUE(original.SerializeToString(&serialized)); protobuf_unittest::TestOneofParsingLite parsed; for (int i = 0; i < 2; ++i) { @@ -925,7 +932,7 @@ TEST(Lite, AllLite44) { { protobuf_unittest::TestOneofParsingLite original; original.mutable_oneof_submessage()->set_optional_int32(5); - string serialized; + ProtoString serialized; EXPECT_TRUE(original.SerializeToString(&serialized)); protobuf_unittest::TestOneofParsingLite parsed; for (int i = 0; i < 2; ++i) { @@ -941,7 +948,7 @@ TEST(Lite, AllLite44) { { protobuf_unittest::TestOneofParsingLite original; original.set_oneof_string("string"); - string serialized; + ProtoString serialized; EXPECT_TRUE(original.SerializeToString(&serialized)); protobuf_unittest::TestOneofParsingLite parsed; for (int i = 0; i < 2; ++i) { @@ -957,7 +964,7 @@ TEST(Lite, AllLite44) { { protobuf_unittest::TestOneofParsingLite original; original.set_oneof_bytes("bytes"); - string serialized; + ProtoString serialized; EXPECT_TRUE(original.SerializeToString(&serialized)); protobuf_unittest::TestOneofParsingLite parsed; for (int i = 0; i < 2; ++i) { @@ -973,7 +980,7 @@ TEST(Lite, AllLite44) { { protobuf_unittest::TestOneofParsingLite original; original.set_oneof_enum(protobuf_unittest::V2_SECOND); - string serialized; + ProtoString serialized; EXPECT_TRUE(original.SerializeToString(&serialized)); protobuf_unittest::TestOneofParsingLite parsed; for (int i = 0; i < 2; ++i) { @@ -990,7 +997,7 @@ TEST(Lite, AllLite44) { TEST(Lite, AllLite45) { // Test unknown fields are not discarded upon parsing. - string data = "\20\1"; // varint 1 with field number 2 + ProtoString data = "\20\1"; // varint 1 with field number 2 protobuf_unittest::ForeignMessageLite a; EXPECT_TRUE(a.ParseFromString(data)); @@ -998,7 +1005,7 @@ TEST(Lite, AllLite45) { reinterpret_cast(data.data()), data.size()); EXPECT_TRUE(a.MergePartialFromCodedStream(&input_stream)); - string serialized = a.SerializeAsString(); + ProtoString serialized = a.SerializeAsString(); EXPECT_EQ(serialized.substr(0, 2), data); EXPECT_EQ(serialized.substr(2), data); } @@ -1013,7 +1020,7 @@ TEST(Lite, AllLite45) { TEST(Lite, AllLite46) { protobuf_unittest::PackedInt32 packed; packed.add_repeated_int32(42); - string serialized; + ProtoString serialized; ASSERT_TRUE(packed.SerializeToString(&serialized)); protobuf_unittest::NonPackedInt32 non_packed; @@ -1025,7 +1032,7 @@ TEST(Lite, AllLite46) { TEST(Lite, AllLite47) { protobuf_unittest::NonPackedFixed32 non_packed; non_packed.add_repeated_fixed32(42); - string serialized; + ProtoString serialized; ASSERT_TRUE(non_packed.SerializeToString(&serialized)); protobuf_unittest::PackedFixed32 packed; @@ -1034,5 +1041,19 @@ TEST(Lite, AllLite47) { EXPECT_EQ(42, packed.repeated_fixed32(0)); } +TEST(Lite, MapCrash) { + // See b/113635730 + Arena arena; + auto msg = Arena::CreateMessage(&arena); + // Payload for the map with a enum varint that's longer > 10 + // bytes. This causes a parse fail and a subsequent delete. + // field 16 (map) tag = 128+2 = \202 \1 + // 13 long \15 + // int32 key = 1 (\10 \1) + // MapEnumLite value = too long varint (parse error) + EXPECT_FALSE(msg->ParseFromString( + "\202\1\15\10\1\200\200\200\200\200\200\200\200\200\200\1")); +} + } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/map.h b/src/google/protobuf/map.h index c5afa2001c..a7126c1639 100644 --- a/src/google/protobuf/map.h +++ b/src/google/protobuf/map.h @@ -53,6 +53,8 @@ #error "You cannot SWIG proto headers" #endif +#include + namespace google { namespace protobuf { @@ -626,7 +628,7 @@ class Map { } DestroyNode(item); --num_elements_; - if (GOOGLE_PREDICT_FALSE(b == index_of_first_non_null_)) { + if (PROTOBUF_PREDICT_FALSE(b == index_of_first_non_null_)) { while (index_of_first_non_null_ < num_buckets_ && table_[index_of_first_non_null_] == NULL) { ++index_of_first_non_null_; @@ -683,7 +685,7 @@ class Map { if (TableEntryIsEmpty(b)) { result = InsertUniqueInList(b, node); } else if (TableEntryIsNonEmptyList(b)) { - if (GOOGLE_PREDICT_FALSE(TableEntryIsTooLong(b))) { + if (PROTOBUF_PREDICT_FALSE(TableEntryIsTooLong(b))) { TreeConvert(b); result = InsertUniqueInTree(b, node); GOOGLE_DCHECK_EQ(result.bucket_index_, b & ~static_cast(1)); @@ -738,13 +740,13 @@ class Map { // We don't care how many elements are in trees. If a lot are, // we may resize even though there are many empty buckets. In // practice, this seems fine. - if (GOOGLE_PREDICT_FALSE(new_size >= hi_cutoff)) { + if (PROTOBUF_PREDICT_FALSE(new_size >= hi_cutoff)) { if (num_buckets_ <= max_size() / 2) { Resize(num_buckets_ * 2); return true; } - } else if (GOOGLE_PREDICT_FALSE(new_size <= lo_cutoff && - num_buckets_ > kMinTableSize)) { + } else if (PROTOBUF_PREDICT_FALSE(new_size <= lo_cutoff && + num_buckets_ > kMinTableSize)) { size_type lg2_of_size_reduction_factor = 1; // It's possible we want to shrink a lot here... size() could even be 0. // So, estimate how much to shrink by making sure we don't shrink so @@ -1219,4 +1221,6 @@ class Map { } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_MAP_H__ diff --git a/src/google/protobuf/map_entry.h b/src/google/protobuf/map_entry.h index 53f35077b4..fbc792f39a 100644 --- a/src/google/protobuf/map_entry.h +++ b/src/google/protobuf/map_entry.h @@ -121,7 +121,7 @@ class MapEntry InternalMetadataWithArena _internal_metadata_; private: - friend class ::GOOGLE_PROTOBUF_NAMESPACE_ID::Arena; + friend class ::PROTOBUF_NAMESPACE_ID::Arena; template diff --git a/src/google/protobuf/map_entry_lite.h b/src/google/protobuf/map_entry_lite.h index 982f0f4468..98b2acae8b 100644 --- a/src/google/protobuf/map_entry_lite.h +++ b/src/google/protobuf/map_entry_lite.h @@ -40,9 +40,13 @@ #include #include #include +#include #include #include +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER +#include +#endif #ifdef SWIG #error "You cannot SWIG proto headers" @@ -186,7 +190,7 @@ class MapEntryImpl : public Base { // MapEntryImpl is for implementation only and this function isn't called // anywhere. Just provide a fake implementation here for MessageLite. - string GetTypeName() const override { return ""; } + std::string GetTypeName() const override { return ""; } void CheckTypeAndMergeFrom(const MessageLite& other) override { MergeFromInternal(*::google::protobuf::down_cast(&other)); @@ -338,6 +342,9 @@ class MapEntryImpl : public Base { class Parser { public: explicit Parser(MapField* mf) : mf_(mf), map_(mf->MutableMap()) {} + ~Parser() { + if (entry_ != nullptr && entry_->GetArena() == nullptr) delete entry_; + } // This does what the typical MergePartialFromCodedStream() is expected to // do, with the additional side-effect that if successful (i.e., if true is @@ -355,11 +362,11 @@ class MapEntryImpl : public Base { int size; input->GetDirectBufferPointerInline(&data, &size); // We could use memcmp here, but we don't bother. The tag is one byte. - GOOGLE_COMPILE_ASSERT(kTagSize == 1, tag_size_error); + static_assert(kTagSize == 1, "tag size must be 1"); if (size > 0 && *reinterpret_cast(data) == kValueTag) { typename Map::size_type map_size = map_->size(); value_ptr_ = &(*map_)[key_]; - if (GOOGLE_PREDICT_TRUE(map_size != map_->size())) { + if (PROTOBUF_PREDICT_TRUE(map_size != map_->size())) { // We created a new key-value pair. Fill in the value. typedef typename MapIf::type T; @@ -377,19 +384,53 @@ class MapEntryImpl : public Base { key_ = Key(); } - entry_.reset(mf_->NewEntry()); + NewEntry(); *entry_->mutable_key() = key_; const bool result = entry_->MergePartialFromCodedStream(input); if (result) UseKeyAndValueFromEntry(); - if (entry_->GetArena() != NULL) entry_.release(); return result; } +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + bool ParseMap(const char* begin, const char* end) { + io::CodedInputStream input(reinterpret_cast(begin), + end - begin); + return MergePartialFromCodedStream(&input) && + input.ConsumedEntireMessage(); + } + template + bool ParseMapEnumValidation(const char* begin, const char* end, uint32 num, + Metadata* metadata, + bool (*validate_enum)(int)) { + io::CodedInputStream input(reinterpret_cast(begin), + end - begin); + auto entry = NewEntry(); + // TODO(gerbens) implement _InternalParse for maps. We can't use + // ParseFromString as this will call _InternalParse + if (!(entry->MergePartialFromCodedStream(&input) && + input.ConsumedEntireMessage())) + return false; + if (!validate_enum(entry->value())) { + auto unknown_fields = metadata->mutable_unknown_fields(); + WriteLengthDelimited(num, StringPiece(begin, end - begin), + unknown_fields); + return true; + } + (*map_)[entry->key()] = static_cast(entry->value()); + return true; + } +#endif + + MapEntryImpl* NewEntry() { return entry_ = mf_->NewEntry(); } + const Key& key() const { return key_; } const Value& value() const { return *value_ptr_; } + const Key& entry_key() const { return entry_->key(); } + const Value& entry_value() const { return entry_->value(); } + private: - void UseKeyAndValueFromEntry() GOOGLE_PROTOBUF_ATTRIBUTE_COLD { + void UseKeyAndValueFromEntry() PROTOBUF_COLD { // Update key_ in case we need it later (because key() is called). // This is potentially inefficient, especially if the key is // expensive to copy (e.g., a long string), but this is a cold @@ -406,8 +447,7 @@ class MapEntryImpl : public Base { // After reading a key and value successfully, and inserting that data // into map_, we are not at the end of the input. This is unusual, but // allowed by the spec. - bool ReadBeyondKeyValuePair(io::CodedInputStream* input) - GOOGLE_PROTOBUF_ATTRIBUTE_COLD { + bool ReadBeyondKeyValuePair(io::CodedInputStream* input) PROTOBUF_COLD { typedef MoveHelper ValueMover; - entry_.reset(mf_->NewEntry()); + NewEntry(); ValueMover::Move(value_ptr_, entry_->mutable_value()); map_->erase(key_); KeyMover::Move(&key_, entry_->mutable_key()); const bool result = entry_->MergePartialFromCodedStream(input); if (result) UseKeyAndValueFromEntry(); - if (entry_->GetArena() != NULL) entry_.release(); return result; } @@ -432,9 +471,7 @@ class MapEntryImpl : public Base { Map* const map_; Key key_; Value* value_ptr_; - // On the fast path entry_ is not used. And, when entry_ is used, it's set - // to mf_->NewEntry(), so in the arena case we must call entry_.release. - std::unique_ptr entry_; + MapEntryImpl* entry_ = nullptr; }; protected: @@ -477,7 +514,7 @@ class MapEntryImpl : public Base { const Key& key_; const Value& value_; - friend class ::GOOGLE_PROTOBUF_NAMESPACE_ID::Arena; + friend class ::PROTOBUF_NAMESPACE_ID::Arena; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; }; @@ -507,7 +544,7 @@ class MapEntryImpl : public Base { const KeyMapEntryAccessorType& key_; const ValueMapEntryAccessorType value_; - friend class ::GOOGLE_PROTOBUF_NAMESPACE_ID::Arena; + friend class ::PROTOBUF_NAMESPACE_ID::Arena; typedef void DestructorSkippable_; }; @@ -522,7 +559,7 @@ class MapEntryImpl : public Base { uint32 _has_bits_[1]; private: - friend class ::GOOGLE_PROTOBUF_NAMESPACE_ID::Arena; + friend class ::PROTOBUF_NAMESPACE_ID::Arena; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; template struct FromHelper { - static ArenaStringPtr From(const string& x) { + static ArenaStringPtr From(const std::string& x) { ArenaStringPtr res; TaggedPtr<::std::string> ptr; - ptr.Set(const_cast(&x)); + ptr.Set(const_cast(&x)); res.UnsafeSetTaggedPointer(ptr); return res; } }; template <> struct FromHelper { - static ArenaStringPtr From(const string& x) { + static ArenaStringPtr From(const std::string& x) { ArenaStringPtr res; TaggedPtr<::std::string> ptr; - ptr.Set(const_cast(&x)); + ptr.Set(const_cast(&x)); res.UnsafeSetTaggedPointer(ptr); return res; } diff --git a/src/google/protobuf/map_field.h b/src/google/protobuf/map_field.h index 9e60191a4d..38dd35d995 100644 --- a/src/google/protobuf/map_field.h +++ b/src/google/protobuf/map_field.h @@ -66,7 +66,7 @@ class MapFieldAccessor; // This class provides access to map field using reflection, which is the same // as those provided for RepeatedPtrField. It is used for internal // reflection implentation only. Users should never use this directly. -class LIBPROTOBUF_EXPORT MapFieldBase { +class PROTOBUF_EXPORT MapFieldBase { public: MapFieldBase() : arena_(NULL), @@ -163,7 +163,7 @@ class LIBPROTOBUF_EXPORT MapFieldBase { // type helper for key and value. Call these help methods to deal with // different types. Real helper methods are implemented in // TypeDefinedMapFieldBase. - friend class ::GOOGLE_PROTOBUF_NAMESPACE_ID::MapIterator; + friend class ::PROTOBUF_NAMESPACE_ID::MapIterator; // Allocate map<...>::iterator for MapIterator. virtual void InitializeIterator(MapIterator* map_iter) const = 0; @@ -300,7 +300,7 @@ class MapField : public TypeDefinedMapFieldBase { void SetMapIteratorValue(MapIterator* map_iter) const override; - friend class ::GOOGLE_PROTOBUF_NAMESPACE_ID::Arena; + friend class ::PROTOBUF_NAMESPACE_ID::Arena; friend class MapFieldStateTest; // For testing, it needs raw access to impl_ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapField); }; @@ -315,7 +315,8 @@ struct MapEntryToMapField { +class PROTOBUF_EXPORT DynamicMapField + : public TypeDefinedMapFieldBase { public: explicit DynamicMapField(const Message* default_entry); DynamicMapField(const Message* default_entry, Arena* arena); @@ -359,7 +360,7 @@ class LIBPROTOBUF_EXPORT DynamicMapField: public TypeDefinedMapFieldBase friend class internal::TypeDefinedMapFieldBase; - friend class ::GOOGLE_PROTOBUF_NAMESPACE_ID::MapIterator; + friend class ::PROTOBUF_NAMESPACE_ID::MapIterator; friend class internal::DynamicMapField; union KeyValue { KeyValue() {} - string* string_value_; + std::string* string_value_; int64 int64_value_; int32 int32_value_; uint64 uint64_value_; @@ -554,7 +555,7 @@ class LIBPROTOBUF_EXPORT MapKey { } type_ = type; if (type_ == FieldDescriptor::CPPTYPE_STRING) { - val_.string_value_ = new string; + val_.string_value_ = new std::string; } } @@ -563,7 +564,7 @@ class LIBPROTOBUF_EXPORT MapKey { }; // MapValueRef points to a map value. -class LIBPROTOBUF_EXPORT MapValueRef { +class PROTOBUF_EXPORT MapValueRef { public: MapValueRef() : data_(NULL), type_(0) {} @@ -598,10 +599,10 @@ class LIBPROTOBUF_EXPORT MapValueRef { "MapValueRef::SetEnumValue"); *reinterpret_cast(data_) = value; } - void SetStringValue(const string& value) { + void SetStringValue(const std::string& value) { TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING, "MapValueRef::SetStringValue"); - *reinterpret_cast(data_) = value; + *reinterpret_cast(data_) = value; } void SetFloatValue(float value) { TYPE_CHECK(FieldDescriptor::CPPTYPE_FLOAT, @@ -644,10 +645,10 @@ class LIBPROTOBUF_EXPORT MapValueRef { "MapValueRef::GetEnumValue"); return *reinterpret_cast(data_); } - const string& GetStringValue() const { + const std::string& GetStringValue() const { TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING, "MapValueRef::GetStringValue"); - return *reinterpret_cast(data_); + return *reinterpret_cast(data_); } float GetFloatValue() const { TYPE_CHECK(FieldDescriptor::CPPTYPE_FLOAT, @@ -680,7 +681,7 @@ class LIBPROTOBUF_EXPORT MapValueRef { friend class internal::MapField; template friend class internal::TypeDefinedMapFieldBase; - friend class ::GOOGLE_PROTOBUF_NAMESPACE_ID::MapIterator; + friend class ::PROTOBUF_NAMESPACE_ID::MapIterator; friend class internal::GeneratedMessageReflection; friend class internal::DynamicMapField; @@ -718,7 +719,7 @@ class LIBPROTOBUF_EXPORT MapValueRef { HANDLE_TYPE(DOUBLE, double); HANDLE_TYPE(FLOAT, float); HANDLE_TYPE(BOOL, bool); - HANDLE_TYPE(STRING, string); + HANDLE_TYPE(STRING, std::string); HANDLE_TYPE(ENUM, int32); HANDLE_TYPE(MESSAGE, Message); #undef HANDLE_TYPE @@ -733,7 +734,7 @@ class LIBPROTOBUF_EXPORT MapValueRef { #undef TYPE_CHECK -class LIBPROTOBUF_EXPORT MapIterator { +class PROTOBUF_EXPORT MapIterator { public: MapIterator(Message* message, const FieldDescriptor* field) { const Reflection* reflection = message->GetReflection(); @@ -810,35 +811,33 @@ class LIBPROTOBUF_EXPORT MapIterator { GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_START template <> -struct hash<::GOOGLE_PROTOBUF_NAMESPACE_ID::MapKey> { - size_t operator()( - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::MapKey& map_key) const { +struct hash<::PROTOBUF_NAMESPACE_ID::MapKey> { + size_t operator()(const ::PROTOBUF_NAMESPACE_ID::MapKey& map_key) const { switch (map_key.type()) { - case ::GOOGLE_PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_DOUBLE: - case ::GOOGLE_PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_FLOAT: - case ::GOOGLE_PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_ENUM: - case ::GOOGLE_PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_MESSAGE: + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_DOUBLE: + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_FLOAT: + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_ENUM: + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_MESSAGE: GOOGLE_LOG(FATAL) << "Unsupported"; break; - case ::GOOGLE_PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_STRING: - return hash()(map_key.GetStringValue()); - case ::GOOGLE_PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_INT64: + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_STRING: + return hash()(map_key.GetStringValue()); + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_INT64: return hash<::google::protobuf::int64>()(map_key.GetInt64Value()); - case ::GOOGLE_PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_INT32: + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_INT32: return hash<::google::protobuf::int32>()(map_key.GetInt32Value()); - case ::GOOGLE_PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_UINT64: + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_UINT64: return hash<::google::protobuf::uint64>()(map_key.GetUInt64Value()); - case ::GOOGLE_PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_UINT32: + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_UINT32: return hash<::google::protobuf::uint32>()(map_key.GetUInt32Value()); - case ::GOOGLE_PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_BOOL: + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_BOOL: return hash()(map_key.GetBoolValue()); } GOOGLE_LOG(FATAL) << "Can't get here."; return 0; } - bool operator()( - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::MapKey& map_key1, - const ::GOOGLE_PROTOBUF_NAMESPACE_ID::MapKey& map_key2) const { + bool operator()(const ::PROTOBUF_NAMESPACE_ID::MapKey& map_key1, + const ::PROTOBUF_NAMESPACE_ID::MapKey& map_key2) const { return map_key1 < map_key2; } }; diff --git a/src/google/protobuf/map_field_inl.h b/src/google/protobuf/map_field_inl.h index 169b3e2bf4..0e78342c51 100644 --- a/src/google/protobuf/map_field_inl.h +++ b/src/google/protobuf/map_field_inl.h @@ -69,7 +69,7 @@ inline bool UnwrapMapKey(const MapKey& map_key) { return map_key.GetBoolValue(); } template<> -inline string UnwrapMapKey(const MapKey& map_key) { +inline std::string UnwrapMapKey(const MapKey& map_key) { return map_key.GetStringValue(); } @@ -97,7 +97,7 @@ inline void SetMapKey(MapKey* map_key, const bool& value) { map_key->SetBoolValue(value); } template<> -inline void SetMapKey(MapKey* map_key, const string& value) { +inline void SetMapKey(MapKey* map_key, const std::string& value) { map_key->SetStringValue(value); } diff --git a/src/google/protobuf/map_field_lite.h b/src/google/protobuf/map_field_lite.h index 36b5b80d2b..5b8d2e48db 100644 --- a/src/google/protobuf/map_field_lite.h +++ b/src/google/protobuf/map_field_lite.h @@ -31,6 +31,8 @@ #ifndef GOOGLE_PROTOBUF_MAP_FIELD_LITE_H__ #define GOOGLE_PROTOBUF_MAP_FIELD_LITE_H__ +#include +#include #include #include #include @@ -112,7 +114,7 @@ class MapFieldLite { Arena* arena_; Map map_; - friend class ::GOOGLE_PROTOBUF_NAMESPACE_ID::Arena; + friend class ::PROTOBUF_NAMESPACE_ID::Arena; }; // True if IsInitialized() is true for value field in all elements of t. T is diff --git a/src/google/protobuf/map_test.cc b/src/google/protobuf/map_test.cc index beaacc4755..080b9dfc3f 100644 --- a/src/google/protobuf/map_test.cc +++ b/src/google/protobuf/map_test.cc @@ -79,6 +79,8 @@ #include +#include + namespace google { namespace protobuf { @@ -1977,7 +1979,7 @@ TEST(GeneratedMapFieldTest, CopyAssignmentOperator) { MapTestUtil::ExpectMapFieldsSet(message2); } -#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || GOOGLE_PROTOBUF_RTTI +#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || PROTOBUF_RTTI TEST(GeneratedMapFieldTest, UpcastCopyFrom) { // Test the CopyFrom method that takes in the generic const Message& // parameter. @@ -2205,6 +2207,7 @@ TEST(GeneratedMapFieldTest, UnorderedWireFormat) { EXPECT_TRUE(message.ParseFromString(data)); EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_NE(message.map_int32_int32().find(2), message.map_int32_int32().end()); EXPECT_EQ(1, message.map_int32_int32().at(2)); } @@ -2280,10 +2283,21 @@ TEST(GeneratedMapFieldTest, KeysValuesUnknownsWireFormat) { wire_format.push_back(c); if (is_key) expected_key = static_cast(c); if (is_value) expected_value = static_cast(c); - ASSERT_TRUE(message.ParseFromString(wire_format)); - ASSERT_EQ(1, message.map_int32_int32().size()); - ASSERT_EQ(expected_key, message.map_int32_int32().begin()->first); - ASSERT_EQ(expected_value, message.map_int32_int32().begin()->second); + bool res = message.ParseFromString(wire_format); + bool expect_success = true; +#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER + // Unfortunately the old map parser accepts malformed input, the new + // parser accepts only correct input. + if (j != items - 1) expect_success = false; +#endif + if (expect_success) { + ASSERT_TRUE(res); + ASSERT_EQ(1, message.map_int32_int32().size()); + ASSERT_EQ(expected_key, message.map_int32_int32().begin()->first); + ASSERT_EQ(expected_value, message.map_int32_int32().begin()->second); + } else { + ASSERT_FALSE(res); + } } } } @@ -2308,6 +2322,7 @@ TEST(GeneratedMapFieldTest, MissedKeyWireFormat) { EXPECT_TRUE(message.ParseFromString(data)); EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_NE(message.map_int32_int32().find(0), message.map_int32_int32().end()); EXPECT_EQ(1, message.map_int32_int32().at(0)); } @@ -2319,6 +2334,7 @@ TEST(GeneratedMapFieldTest, MissedValueWireFormat) { EXPECT_TRUE(message.ParseFromString(data)); EXPECT_EQ(1, message.map_int32_int32().size()); + ASSERT_NE(message.map_int32_int32().find(1), message.map_int32_int32().end()); EXPECT_EQ(0, message.map_int32_int32().at(1)); } @@ -3178,6 +3194,23 @@ TEST(TextFormatMapTest, SerializeAndParse) { MapTestUtil::ExpectMapFieldsSet(dest); } +TEST(TextFormatMapTest, DynamicMessage) { + TestMap prototype; + DynamicMessageFactory factory; + std::unique_ptr message( + factory.GetPrototype(prototype.GetDescriptor())->New()); + MapReflectionTester tester(message->GetDescriptor()); + tester.SetMapFieldsViaReflection(message.get()); + + string expected_text; + GOOGLE_CHECK_OK(File::GetContents( + TestUtil::GetTestDataPath("net/proto2/internal/" + "testdata/map_test_data.txt"), + &expected_text, true)); + + EXPECT_EQ(message->DebugString(), expected_text); +} + TEST(TextFormatMapTest, Sorted) { unittest::TestMap message; MapReflectionTester tester(message.GetDescriptor()); @@ -3211,6 +3244,78 @@ TEST(TextFormatMapTest, ParseCorruptedString) { TestParseCorruptedString(message); } +// Previously, serializing to text format will disable iterator from generated +// API. Now, the iterator can be still used even after serializing to text +// format. +TEST(TextFormatMapTest, NoDisableIterator) { + unittest::TestMap source; + (*source.mutable_map_int32_int32())[1] = 1; + + // Get iterator. + Map::iterator iter = + source.mutable_map_int32_int32()->find(1); + + // Serialize message to text format, which will invalidate the previous + // iterator previously. + string output; + TextFormat::Printer printer; + printer.PrintToString(source, &output); + + // Modify map via the iterator (invalidated in prvious implementation.). + iter->second = 2; + + // In previous implementation, the new change won't be reflected in text + // format, because the previous iterator has been invalidated. + output.clear(); + printer.PrintToString(source, &output); + string expected = + "map_int32_int32 {\n" + " key: 1\n" + " value: 2\n" + "}\n"; + EXPECT_EQ(output, expected); +} + +// Previously, serializing to text format will disable iterator from reflection +// API. +TEST(TextFormatMapTest, NoDisableReflectionIterator) { + unittest::TestMap source; + (*source.mutable_map_int32_int32())[1] = 1; + + // Get iterator. This will also sync internal repeated field with map inside + // of MapField. + const Reflection* reflection = source.GetReflection(); + const FieldDescriptor* field_desc = + source.GetDescriptor()->FindFieldByName("map_int32_int32"); + RepeatedPtrField* map_field = + reflection->MutableRepeatedPtrField(&source, field_desc); + RepeatedPtrField::iterator iter = map_field->begin(); + + // Serialize message to text format, which will invalidate the prvious + // iterator previously. + string output; + TextFormat::Printer printer; + printer.PrintToString(source, &output); + + // Modify map via the iterator (invalidated in prvious implementation.). + const Reflection* map_entry_reflection = iter->GetReflection(); + const FieldDescriptor* value_field_desc = + iter->GetDescriptor()->FindFieldByName("value"); + map_entry_reflection->SetInt32(&(*iter), value_field_desc, 2); + GOOGLE_LOG(INFO) << iter->DebugString(); + + // In previous implementation, the new change won't be reflected in text + // format, because the previous iterator has been invalidated. + output.clear(); + printer.PrintToString(source, &output); + string expected = + "map_int32_int32 {\n" + " key: 1\n" + " value: 2\n" + "}\n"; + EXPECT_EQ(output, expected); +} + // arena support ================================================= TEST(ArenaTest, ParsingAndSerializingNoHeapAllocation) { diff --git a/src/google/protobuf/map_test_util.h b/src/google/protobuf/map_test_util.h index 53d1575652..105313d43c 100644 --- a/src/google/protobuf/map_test_util.h +++ b/src/google/protobuf/map_test_util.h @@ -107,15 +107,15 @@ class MapReflectionTester { void ExpectClearViaReflectionIterator(Message* message); void ExpectMapEntryClearViaReflection(Message* message); void GetMapValueViaMapReflection(Message* message, - const string& field_name, + const std::string& field_name, const MapKey& map_key, MapValueRef* map_val); - Message* GetMapEntryViaReflection(Message* message, const string& field_name, + Message* GetMapEntryViaReflection(Message* message, const std::string& field_name, int index); - MapIterator MapBegin(Message* message, const string& field_name); - MapIterator MapEnd(Message* message, const string& field_name); + MapIterator MapBegin(Message* message, const std::string& field_name); + MapIterator MapEnd(Message* message, const std::string& field_name); private: - const FieldDescriptor* F(const string& name); + const FieldDescriptor* F(const std::string& name); const Descriptor* base_descriptor_; diff --git a/src/google/protobuf/map_type_handler.h b/src/google/protobuf/map_type_handler.h index 0489851e55..2db3dc6c9f 100644 --- a/src/google/protobuf/map_type_handler.h +++ b/src/google/protobuf/map_type_handler.h @@ -245,7 +245,7 @@ class MapTypeHandler { int default_enum); \ static inline size_t SpaceUsedInMapEntryLong(const TypeOnMemory& value); \ static inline size_t SpaceUsedInMapLong(const TypeOnMemory& value); \ - static inline size_t SpaceUsedInMapLong(const string& value); \ + static inline size_t SpaceUsedInMapLong(const std::string& value); \ static inline void AssignDefaultValue(TypeOnMemory* value); \ static inline const MapEntryAccessorType& DefaultIfNotInitialized( \ const TypeOnMemory& value, const TypeOnMemory& default_value); \ @@ -575,7 +575,7 @@ inline bool MapTypeHandler \ inline size_t \ MapTypeHandler::SpaceUsedInMapLong( \ - const string& value) { \ + const std::string& value) { \ return sizeof(value); \ } \ template \ diff --git a/src/google/protobuf/message.cc b/src/google/protobuf/message.cc index b5a624b718..5a9acaf6e5 100644 --- a/src/google/protobuf/message.cc +++ b/src/google/protobuf/message.cc @@ -36,6 +36,7 @@ #include #include +#include #include #include @@ -51,6 +52,7 @@ #include #include #include +#include #include #include @@ -72,9 +74,12 @@ using internal::WireFormatLite; void Message::MergeFrom(const Message& from) { const Descriptor* descriptor = GetDescriptor(); GOOGLE_CHECK_EQ(from.GetDescriptor(), descriptor) - << ": Tried to merge from a message with a different type. " - "to: " << descriptor->full_name() << ", " - "from: " << from.GetDescriptor()->full_name(); + << ": Tried to merge from a message with a different type. " + "to: " + << descriptor->full_name() + << ", " + "from: " + << from.GetDescriptor()->full_name(); ReflectionOps::Merge(from, this); } @@ -85,19 +90,18 @@ void Message::CheckTypeAndMergeFrom(const MessageLite& other) { void Message::CopyFrom(const Message& from) { const Descriptor* descriptor = GetDescriptor(); GOOGLE_CHECK_EQ(from.GetDescriptor(), descriptor) - << ": Tried to copy from a message with a different type. " - "to: " << descriptor->full_name() << ", " - "from: " << from.GetDescriptor()->full_name(); + << ": Tried to copy from a message with a different type. " + "to: " + << descriptor->full_name() + << ", " + "from: " + << from.GetDescriptor()->full_name(); ReflectionOps::Copy(from, this); } -string Message::GetTypeName() const { - return GetDescriptor()->full_name(); -} +string Message::GetTypeName() const { return GetDescriptor()->full_name(); } -void Message::Clear() { - ReflectionOps::Clear(this); -} +void Message::Clear() { ReflectionOps::Clear(this); } bool Message::IsInitialized() const { return ReflectionOps::IsInitialized(*this); @@ -114,9 +118,9 @@ string Message::InitializationErrorString() const { } void Message::CheckInitialized() const { - GOOGLE_CHECK(IsInitialized()) - << "Message of type \"" << GetDescriptor()->full_name() - << "\" is missing required fields: " << InitializationErrorString(); + GOOGLE_CHECK(IsInitialized()) << "Message of type \"" << GetDescriptor()->full_name() + << "\" is missing required fields: " + << InitializationErrorString(); } void Message::DiscardUnknownFields() { @@ -156,27 +160,30 @@ class ReflectionAccessor { public: static void* GetOffset(void* msg, const google::protobuf::FieldDescriptor* f, const google::protobuf::Reflection* r) { - auto gr = - dynamic_cast(r); - GOOGLE_CHECK(gr != nullptr); - return static_cast(msg) + gr->schema_.GetFieldOffset(f); + return static_cast(msg) + CheckedCast(r)->schema_.GetFieldOffset(f); } - static google::protobuf::internal::ExtensionSet* GetExtensionSet( - void* msg, const google::protobuf::Reflection* r) { - auto gr = - dynamic_cast(r); - GOOGLE_CHECK(gr != nullptr); - return reinterpret_cast( - static_cast(msg) + gr->schema_.GetExtensionSetOffset()); + static ExtensionSet* GetExtensionSet(void* msg, const google::protobuf::Reflection* r) { + return reinterpret_cast( + static_cast(msg) + + CheckedCast(r)->schema_.GetExtensionSetOffset()); + } + static InternalMetadataWithArena* GetMetadata(void* msg, + const google::protobuf::Reflection* r) { + return reinterpret_cast( + static_cast(msg) + CheckedCast(r)->schema_.GetMetadataOffset()); } - static google::protobuf::internal::InternalMetadataWithArena* GetMetadata( - void* msg, const google::protobuf::Reflection* r) { - auto gr = - dynamic_cast(r); + static void* GetRepeatedEnum(const Reflection* reflection, + const FieldDescriptor* field, Message* msg) { + return reflection->MutableRawRepeatedField( + msg, field, FieldDescriptor::CPPTYPE_ENUM, 0, nullptr); + } + + private: + static const GeneratedMessageReflection* CheckedCast(const Reflection* r) { + auto gr = dynamic_cast(r); GOOGLE_CHECK(gr != nullptr); - return reinterpret_cast( - static_cast(msg) + gr->schema_.GetMetadataOffset()); + return gr; } }; @@ -276,16 +283,15 @@ ParseClosure GetPackedField(const FieldDescriptor* field, Message* msg, HANDLE_PACKED_TYPE(UINT64, uint64, UInt64); HANDLE_PACKED_TYPE(BOOL, bool, Bool); case FieldDescriptor::TYPE_ENUM: { + auto object = + internal::ReflectionAccessor::GetRepeatedEnum(reflection, field, msg); if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) { - auto object = - internal::ReflectionAccessor::GetOffset(msg, field, reflection); return {internal::PackedEnumParser, object}; } else { + GOOGLE_CHECK_EQ(field->file()->options().cc_api_version(), 2); ctx->extra_parse_data().SetEnumValidatorArg( ReflectiveValidator, field->enum_type(), reflection->MutableUnknownFields(msg), field->number()); - auto object = - internal::ReflectionAccessor::GetOffset(msg, field, reflection); return {internal::PackedValidEnumParserArg, object}; } } @@ -334,7 +340,7 @@ ParseClosure GetLenDelim(int field_number, const FieldDescriptor* field, ctx->extra_parse_data().SetFieldName(field->full_name().c_str()); utf8_level = kVerify; } - GOOGLE_FALLTHROUGH_INTENDED; + FALLTHROUGH_INTENDED; case FieldDescriptor::TYPE_BYTES: { if (field->is_repeated()) { int index = reflection->FieldSize(*msg, field); @@ -383,10 +389,11 @@ ParseClosure GetLenDelim(int field_number, const FieldDescriptor* field, } case FieldDescriptor::TYPE_MESSAGE: { Message* object; + auto factory = ctx->extra_parse_data().factory; if (field->is_repeated()) { - object = reflection->AddMessage(msg, field, nullptr); + object = reflection->AddMessage(msg, field, factory); } else { - object = reflection->MutableMessage(msg, field, nullptr); + object = reflection->MutableMessage(msg, field, factory); } return {object->_ParseFunc(), object}; } @@ -493,6 +500,10 @@ const char* Message::_InternalParse(const char* begin, const char* end, while (ptr < end) { ptr = Varint::Parse32Inline(ptr, &tag); if (ptr == nullptr) return nullptr; + if (tag == 0) { + if (ctx->ValidEndGroup(0)) return ptr; + return nullptr; + } if ((tag >> 3) == 0) return nullptr; const FieldDescriptor* field = nullptr; @@ -501,11 +512,14 @@ const char* Message::_InternalParse(const char* begin, const char* end, // If that failed, check if the field is an extension. if (field == nullptr && descriptor->IsExtensionNumber(field_number)) { - field = reflection->FindKnownExtensionByNumber(field_number); + auto pool = ctx->extra_parse_data().pool; + if (pool == NULL) { + field = reflection->FindKnownExtensionByNumber(field_number); + } else { + field = pool->FindExtensionByNumber(descriptor, field_number); + } } - // if (field) GOOGLE_LOG(ERROR) << "Encountered field " << field->name(); - switch (tag & 7) { case 0: { uint64 val; @@ -565,7 +579,7 @@ const char* Message::_InternalParse(const char* begin, const char* end, ptr = ptr + 4; if (field == nullptr || WireFormat::WireTypeForFieldType(field->type()) != 5) { - unknown->AddFixed64(field_number, val); + unknown->AddFixed32(field_number, val); break; } SetField(val, field, msg, reflection); @@ -593,8 +607,7 @@ group_continues: #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER -void Message::SerializeWithCachedSizes( - io::CodedOutputStream* output) const { +void Message::SerializeWithCachedSizes(io::CodedOutputStream* output) const { const internal::SerializationTable* table = static_cast(InternalGetTable()); if (table == 0) { @@ -653,51 +666,50 @@ void Reflection::AddAllocatedMessage(Message* /* message */, const FieldDescriptor* /*field */, Message* /* new_entry */) const {} -#define HANDLE_TYPE(TYPE, CPPTYPE, CTYPE) \ -template<> \ -const RepeatedField& Reflection::GetRepeatedField( \ - const Message& message, const FieldDescriptor* field) const { \ - return *static_cast* >( \ - MutableRawRepeatedField(const_cast(&message), \ - field, CPPTYPE, CTYPE, NULL)); \ -} \ - \ -template<> \ -RepeatedField* Reflection::MutableRepeatedField( \ - Message* message, const FieldDescriptor* field) const { \ - return static_cast* >( \ - MutableRawRepeatedField(message, field, CPPTYPE, CTYPE, NULL)); \ -} - -HANDLE_TYPE(int32, FieldDescriptor::CPPTYPE_INT32, -1); -HANDLE_TYPE(int64, FieldDescriptor::CPPTYPE_INT64, -1); +#define HANDLE_TYPE(TYPE, CPPTYPE, CTYPE) \ + template <> \ + const RepeatedField& Reflection::GetRepeatedField( \ + const Message& message, const FieldDescriptor* field) const { \ + return *static_cast*>(MutableRawRepeatedField( \ + const_cast(&message), field, CPPTYPE, CTYPE, NULL)); \ + } \ + \ + template <> \ + RepeatedField* Reflection::MutableRepeatedField( \ + Message * message, const FieldDescriptor* field) const { \ + return static_cast*>( \ + MutableRawRepeatedField(message, field, CPPTYPE, CTYPE, NULL)); \ + } + +HANDLE_TYPE(int32, FieldDescriptor::CPPTYPE_INT32, -1); +HANDLE_TYPE(int64, FieldDescriptor::CPPTYPE_INT64, -1); HANDLE_TYPE(uint32, FieldDescriptor::CPPTYPE_UINT32, -1); HANDLE_TYPE(uint64, FieldDescriptor::CPPTYPE_UINT64, -1); -HANDLE_TYPE(float, FieldDescriptor::CPPTYPE_FLOAT, -1); +HANDLE_TYPE(float, FieldDescriptor::CPPTYPE_FLOAT, -1); HANDLE_TYPE(double, FieldDescriptor::CPPTYPE_DOUBLE, -1); -HANDLE_TYPE(bool, FieldDescriptor::CPPTYPE_BOOL, -1); +HANDLE_TYPE(bool, FieldDescriptor::CPPTYPE_BOOL, -1); #undef HANDLE_TYPE -void* Reflection::MutableRawRepeatedString( - Message* message, const FieldDescriptor* field, bool is_string) const { +void* Reflection::MutableRawRepeatedString(Message* message, + const FieldDescriptor* field, + bool is_string) const { return MutableRawRepeatedField(message, field, - FieldDescriptor::CPPTYPE_STRING, FieldOptions::STRING, NULL); + FieldDescriptor::CPPTYPE_STRING, + FieldOptions::STRING, NULL); } -MapIterator Reflection::MapBegin( - Message* message, - const FieldDescriptor* field) const { +MapIterator Reflection::MapBegin(Message* message, + const FieldDescriptor* field) const { GOOGLE_LOG(FATAL) << "Unimplemented Map Reflection API."; MapIterator iter(message, field); return iter; } -MapIterator Reflection::MapEnd( - Message* message, - const FieldDescriptor* field) const { +MapIterator Reflection::MapEnd(Message* message, + const FieldDescriptor* field) const { GOOGLE_LOG(FATAL) << "Unimplemented Map Reflection API."; MapIterator iter(message, field); return iter; @@ -766,8 +778,8 @@ void GeneratedMessageFactory::RegisterFile(const char* file, void GeneratedMessageFactory::RegisterType(const Descriptor* descriptor, const Message* prototype) { GOOGLE_DCHECK_EQ(descriptor->file()->pool(), DescriptorPool::generated_pool()) - << "Tried to register a non-generated type with the generated " - "type registry."; + << "Tried to register a non-generated type with the generated " + "type registry."; // This should only be called as a result of calling a file registration // function during GetPrototype(), in which case we already have locked @@ -795,7 +807,8 @@ const Message* GeneratedMessageFactory::GetPrototype(const Descriptor* type) { FindPtrOrNull(file_map_, type->file()->name().c_str()); if (registration_data == NULL) { GOOGLE_LOG(DFATAL) << "File appears to be in generated pool but wasn't " - "registered: " << type->file()->name(); + "registered: " + << type->file()->name(); return NULL; } @@ -841,10 +854,10 @@ MessageFactory* Reflection::GetMessageFactory() const { return NULL; } -void* Reflection::RepeatedFieldData( - Message* message, const FieldDescriptor* field, - FieldDescriptor::CppType cpp_type, - const Descriptor* message_type) const { +void* Reflection::RepeatedFieldData(Message* message, + const FieldDescriptor* field, + FieldDescriptor::CppType cpp_type, + const Descriptor* message_type) const { GOOGLE_LOG(FATAL) << "Not implemented."; return NULL; } @@ -896,7 +909,7 @@ template <> #if defined(_MSC_VER) && (_MSC_VER >= 1800) // Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue // #240 -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE +PROTOBUF_NOINLINE #endif Message* GenericTypeHandler::NewFromPrototype(const Message* prototype, @@ -907,7 +920,7 @@ template <> #if defined(_MSC_VER) && (_MSC_VER >= 1800) // Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue // #240 -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE +PROTOBUF_NOINLINE #endif Arena* GenericTypeHandler::GetArena(Message* value) { @@ -917,7 +930,7 @@ template <> #if defined(_MSC_VER) && (_MSC_VER >= 1800) // Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue // #240 -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE +PROTOBUF_NOINLINE #endif void* GenericTypeHandler::GetMaybeArenaPointer(Message* value) { diff --git a/src/google/protobuf/message.h b/src/google/protobuf/message.h index 007dafa288..9f44132bce 100644 --- a/src/google/protobuf/message.h +++ b/src/google/protobuf/message.h @@ -163,8 +163,13 @@ namespace expr { class CelMapReflectionFriend; // field_backed_map_impl.cc } +namespace internal { +class MapFieldPrinterHelper; // text_format.cc +} + namespace internal { +class ReflectionAccessor; // message.cc class ReflectionOps; // reflection_ops.h class MapKeySorter; // wire_format.cc class WireFormat; // wire_format.h @@ -193,7 +198,7 @@ struct Metadata { // optimized for speed will want to override these with faster implementations, // but classes optimized for code size may be happy with keeping them. See // the optimize_for option in descriptor.proto. -class LIBPROTOBUF_EXPORT Message : public MessageLite { +class PROTOBUF_EXPORT Message : public MessageLite { public: inline Message() {} virtual ~Message() {} @@ -236,11 +241,11 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite { // This is much, much slower than IsInitialized() as it is implemented // purely via reflection. Generally, you should not call this unless you // have already determined that an error exists by calling IsInitialized(). - void FindInitializationErrors(std::vector* errors) const; + void FindInitializationErrors(std::vector* errors) const; // Like FindInitializationErrors, but joins all the strings, delimited by // commas, and returns them. - string InitializationErrorString() const override; + std::string InitializationErrorString() const override; // Clears all unknown fields from this message and all embedded messages. // Normally, if unknown tag numbers are encountered when parsing a message, @@ -264,18 +269,18 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite { // fields defined for the proto. virtual size_t SpaceUsedLong() const; - GOOGLE_PROTOBUF_DEPRECATED_MSG("Please use SpaceUsedLong() instead") + PROTOBUF_DEPRECATED_MSG("Please use SpaceUsedLong() instead") int SpaceUsed() const { return internal::ToIntSize(SpaceUsedLong()); } // Debugging & Testing---------------------------------------------- // Generates a human readable form of this message, useful for debugging // and other purposes. - string DebugString() const; + std::string DebugString() const; // Like DebugString(), but with less whitespace. - string ShortDebugString() const; + std::string ShortDebugString() const; // Like DebugString(), but do not escape UTF-8 byte sequences. - string Utf8DebugString() const; + std::string Utf8DebugString() const; // Convenience function useful in GDB. Prints DebugString() to stdout. void PrintDebugString() const; @@ -312,7 +317,7 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite { // These methods are pure-virtual in MessageLite, but Message provides // reflection-based default implementations. - string GetTypeName() const override; + std::string GetTypeName() const override; void Clear() override; bool IsInitialized() const override; void CheckTypeAndMergeFrom(const MessageLite& other) override; @@ -424,7 +429,7 @@ class MutableRepeatedFieldRef; // double the message's memory footprint, probably worse. Allocating the // objects on-demand, on the other hand, would be expensive and prone to // memory leaks. So, instead we ended up with this flat interface. -class LIBPROTOBUF_EXPORT Reflection { +class PROTOBUF_EXPORT Reflection { public: inline Reflection() {} virtual ~Reflection(); @@ -445,7 +450,7 @@ class LIBPROTOBUF_EXPORT Reflection { // Estimate the amount of memory used by the message object. virtual size_t SpaceUsedLong(const Message& message) const = 0; - GOOGLE_PROTOBUF_DEPRECATED_MSG("Please use SpaceUsedLong() instead") + PROTOBUF_DEPRECATED_MSG("Please use SpaceUsedLong() instead") int SpaceUsed(const Message& message) const { return internal::ToIntSize(SpaceUsedLong(message)); } @@ -542,7 +547,7 @@ class LIBPROTOBUF_EXPORT Reflection { const FieldDescriptor* field) const = 0; virtual bool GetBool (const Message& message, const FieldDescriptor* field) const = 0; - virtual string GetString(const Message& message, + virtual std::string GetString(const Message& message, const FieldDescriptor* field) const = 0; virtual const EnumValueDescriptor* GetEnum( const Message& message, const FieldDescriptor* field) const = 0; @@ -575,9 +580,9 @@ class LIBPROTOBUF_EXPORT Reflection { // a newly-constructed string, though, it's just as fast and more readable // to use code like: // string str = reflection->GetString(message, field); - virtual const string& GetStringReference(const Message& message, + virtual const std::string& GetStringReference(const Message& message, const FieldDescriptor* field, - string* scratch) const = 0; + std::string* scratch) const = 0; // Singular field mutators ----------------------------------------- @@ -599,7 +604,7 @@ class LIBPROTOBUF_EXPORT Reflection { const FieldDescriptor* field, bool value) const = 0; virtual void SetString(Message* message, const FieldDescriptor* field, - const string& value) const = 0; + const std::string& value) const = 0; virtual void SetEnum (Message* message, const FieldDescriptor* field, const EnumValueDescriptor* value) const = 0; @@ -670,7 +675,7 @@ class LIBPROTOBUF_EXPORT Reflection { virtual bool GetRepeatedBool (const Message& message, const FieldDescriptor* field, int index) const = 0; - virtual string GetRepeatedString(const Message& message, + virtual std::string GetRepeatedString(const Message& message, const FieldDescriptor* field, int index) const = 0; virtual const EnumValueDescriptor* GetRepeatedEnum( @@ -689,9 +694,9 @@ class LIBPROTOBUF_EXPORT Reflection { const FieldDescriptor* field, int index) const = 0; // See GetStringReference(), above. - virtual const string& GetRepeatedStringReference( + virtual const std::string& GetRepeatedStringReference( const Message& message, const FieldDescriptor* field, - int index, string* scratch) const = 0; + int index, std::string* scratch) const = 0; // Repeated field mutators ----------------------------------------- @@ -720,7 +725,7 @@ class LIBPROTOBUF_EXPORT Reflection { int index, bool value) const = 0; virtual void SetRepeatedString(Message* message, const FieldDescriptor* field, - int index, const string& value) const = 0; + int index, const std::string& value) const = 0; virtual void SetRepeatedEnum(Message* message, const FieldDescriptor* field, int index, const EnumValueDescriptor* value) const = 0; @@ -759,7 +764,7 @@ class LIBPROTOBUF_EXPORT Reflection { const FieldDescriptor* field, bool value) const = 0; virtual void AddString(Message* message, const FieldDescriptor* field, - const string& value) const = 0; + const std::string& value) const = 0; virtual void AddEnum (Message* message, const FieldDescriptor* field, const EnumValueDescriptor* value) const = 0; @@ -839,8 +844,7 @@ class LIBPROTOBUF_EXPORT Reflection { // // for T = Cord and all protobuf scalar types except enums. template - GOOGLE_PROTOBUF_DEPRECATED_MSG( - "Please use GetRepeatedFieldRef() instead") + PROTOBUF_DEPRECATED_MSG("Please use GetRepeatedFieldRef() instead") const RepeatedField& GetRepeatedField(const Message&, const FieldDescriptor*) const; @@ -848,8 +852,7 @@ class LIBPROTOBUF_EXPORT Reflection { // // for T = Cord and all protobuf scalar types except enums. template - GOOGLE_PROTOBUF_DEPRECATED_MSG( - "Please use GetMutableRepeatedFieldRef() instead") + PROTOBUF_DEPRECATED_MSG("Please use GetMutableRepeatedFieldRef() instead") RepeatedField* MutableRepeatedField(Message*, const FieldDescriptor*) const; @@ -858,8 +861,7 @@ class LIBPROTOBUF_EXPORT Reflection { // for T = string, google::protobuf::internal::StringPieceField // google::protobuf::Message & descendants. template - GOOGLE_PROTOBUF_DEPRECATED_MSG( - "Please use GetRepeatedFieldRef() instead") + PROTOBUF_DEPRECATED_MSG("Please use GetRepeatedFieldRef() instead") const RepeatedPtrField& GetRepeatedPtrField(const Message&, const FieldDescriptor*) const; @@ -868,8 +870,7 @@ class LIBPROTOBUF_EXPORT Reflection { // for T = string, google::protobuf::internal::StringPieceField // google::protobuf::Message & descendants. template - GOOGLE_PROTOBUF_DEPRECATED_MSG( - "Please use GetMutableRepeatedFieldRef() instead") + PROTOBUF_DEPRECATED_MSG("Please use GetMutableRepeatedFieldRef() instead") RepeatedPtrField* MutableRepeatedPtrField(Message*, const FieldDescriptor*) const; @@ -878,7 +879,7 @@ class LIBPROTOBUF_EXPORT Reflection { // Try to find an extension of this message type by fully-qualified field // name. Returns NULL if no extension is known for this name or number. virtual const FieldDescriptor* FindKnownExtensionByName( - const string& name) const = 0; + const std::string& name) const = 0; // Try to find an extension of this message type by field number. // Returns NULL if no extension is known for this name or number. @@ -987,6 +988,9 @@ class LIBPROTOBUF_EXPORT Reflection { friend class internal::MapKeySorter; friend class internal::WireFormat; friend class internal::ReflectionOps; + // Needed for implementing text format for map. + friend class internal::MapFieldPrinterHelper; + friend class internal::ReflectionAccessor; // Special version for specialized implementations of string. We can't call // MutableRawRepeatedField directly here because we don't have access to @@ -1057,7 +1061,7 @@ class LIBPROTOBUF_EXPORT Reflection { }; // Abstract interface for a factory for message objects. -class LIBPROTOBUF_EXPORT MessageFactory { +class PROTOBUF_EXPORT MessageFactory { public: inline MessageFactory() {} virtual ~MessageFactory(); @@ -1120,16 +1124,15 @@ class LIBPROTOBUF_EXPORT MessageFactory { GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFactory); }; -#define DECLARE_GET_REPEATED_FIELD(TYPE) \ -template<> \ -LIBPROTOBUF_EXPORT \ -const RepeatedField& Reflection::GetRepeatedField( \ - const Message& message, const FieldDescriptor* field) const; \ - \ -template<> \ -LIBPROTOBUF_EXPORT \ -RepeatedField* Reflection::MutableRepeatedField( \ - Message* message, const FieldDescriptor* field) const; +#define DECLARE_GET_REPEATED_FIELD(TYPE) \ + template <> \ + PROTOBUF_EXPORT const RepeatedField& \ + Reflection::GetRepeatedField(const Message& message, \ + const FieldDescriptor* field) const; \ + \ + template <> \ + PROTOBUF_EXPORT RepeatedField* Reflection::MutableRepeatedField( \ + Message * message, const FieldDescriptor* field) const; DECLARE_GET_REPEATED_FIELD(int32) DECLARE_GET_REPEATED_FIELD(int64) @@ -1196,16 +1199,16 @@ T dynamic_cast_if_available(Message* from) { // Such a type presumably is a descendant of google::protobuf::Message. template<> -inline const RepeatedPtrField& Reflection::GetRepeatedPtrField( +inline const RepeatedPtrField& Reflection::GetRepeatedPtrField( const Message& message, const FieldDescriptor* field) const { - return *static_cast* >( + return *static_cast* >( MutableRawRepeatedString(const_cast(&message), field, true)); } template<> -inline RepeatedPtrField* Reflection::MutableRepeatedPtrField( +inline RepeatedPtrField* Reflection::MutableRepeatedPtrField( Message* message, const FieldDescriptor* field) const { - return static_cast* >( + return static_cast* >( MutableRawRepeatedString(message, field, true)); } diff --git a/src/google/protobuf/message_lite.cc b/src/google/protobuf/message_lite.cc index 33ee632326..01bb0d3976 100644 --- a/src/google/protobuf/message_lite.cc +++ b/src/google/protobuf/message_lite.cc @@ -80,7 +80,8 @@ void ByteSizeConsistencyError(size_t byte_size_before_serialization, GOOGLE_CHECK_EQ(bytes_produced_by_serialization, byte_size_before_serialization) << "Byte size calculation and serialization were inconsistent. This " "may indicate a bug in protocol buffers or it may be caused by " - "concurrent modification of " << message.GetTypeName() << "."; + "concurrent modification of " + << message.GetTypeName() << "."; GOOGLE_LOG(FATAL) << "This shouldn't be called if all the sizes are equal."; } @@ -108,12 +109,16 @@ string InitializationErrorMessage(const char* action, #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER // This is wrapper to turn a ZeroCopyInputStream (ZCIS) into a // InputStreamWithOverlap. This is done by copying data around the seams, -// pictorially if ZCIS presents a stream in chunks like so +// hence the name EpsCopyInputStream, pictorially if ZCIS presents a stream +// in chunks like so // [---------------------------------------------------------------] // [---------------------] chunk 1 // [----------------------------] chunk 2 // chunk 3 [--------------] -// this class will convert this into chunks +// where '-' depicts bytes of the stream or chunks vertically alligned with the +// corresponding bytes between stream and chunk. +// +// This class will convert this into chunks // [-----------------....] chunk 1 // [----....] patch // [------------------------....] chunk 2 @@ -121,17 +126,58 @@ string InitializationErrorMessage(const char* action, // chunk 3 [----------....] // patch [----****] // by using a fixed size buffer to patch over the seams. This requires -// copying of an "epsilon" neighboorhood around the seams. - +// copying of an "epsilon" neighboorhood around the seams. In the picture above +// dots mean bytes beyond the end of the new chunks. Each chunk is kSlopBytes +// smalller as its original chunk (above depicted as 4 dots) and the number of +// of chunks is doubled because each seam in the original stream introduces a +// new patch. +// +// The algorithm is simple but not entirely trivial. Two complications arise +// 1) The original chunk could be less than kSlopBytes. Hence we can't simply +// chop the last kSlopBytes of a chunk. +// 2) We need to leave the underlying CodedInputStream (CIS) precisely at the +// last byte read in the parse. In most cases a parse ends on a limit or end of +// the ZeroCopyInputStream, which is not problematic because CIS will never give +// us data beyond that. But the parse can end on a 0 end tag or an end group. +// If that happens in the first kSlopBytes of the patch (which are copied +// from the previous buffer) the CIS has already moved to the next chunk to +// copy the remaining bytes of the patch buffer. There exist no API to rollback +// to a previous buffer. +// +// We model this as a state machine. A call to get the next chunk either returns +// an original chunk except the last kSlopBytes or it has to copy the last +// kSlopBytes of the current chunk to the patch buffer and copy the first +// kSlopBytes of the next chunk to the end of the patch buffer. +// +// In order to deal with problem 1, we need to deal with the case that a new +// chunk can be less or equal than kSlopBytes big. We can just copy the chunk +// to the end and return (buffer, chunk->size). Pictorially +// [--------] chunk 1 +// [--] chunk 2 +// [---] chunk 3 +// will become +// [----....] chunk 1 +// [--....] patch (not full range of the buffer, only two hyphens) +// [--] chunk 2 (too small so never returned as buffer) +// [---....] patch (not full range of the buffer, only three hyphens) +// [---] chunk 3 (too small so never returned as buffer) +// [----****] patch (full range, last bytes are garbage) +// Because of this the source (the dots in above) can overlap with the +// destination buffer and so we have to use memmove. +// +// To solve problem 2, we verify after copying the last kSlopBytes the parse +// won't end before we continue to get the next chunk. template class EpsCopyInputStream { public: EpsCopyInputStream(io::CodedInputStream* input) : input_(input) {} ~EpsCopyInputStream() { - if (skip_) input_->Skip(skip_); + ABSL_ASSERT(skip_ >= 0); + input_->Skip(skip_); } - StringPiece NextWithOverlap() { + template + StringPiece SafeNextWithOverlap(const EnsureNotEnd& ensure_not_end) { switch (next_state_) { case kEOS: // End of stream @@ -141,140 +187,118 @@ class EpsCopyInputStream { // To parse the last kSlopBytes we need to copy the bytes into the // buffer. Hence we set, next_state_ = kBuffer; + skip_ = chunk_.size() - kSlopBytes; return {chunk_.begin(), chunk_.size() - kSlopBytes}; - case kBuffer: + case kBuffer: { // We have to parse the last kSlopBytes of chunk_, which could alias // buffer_ so we have to memmove. std::memmove(buffer_, chunk_.end() - kSlopBytes, kSlopBytes); - chunk_ = GetChunk(); - if (chunk_.size() > kSlopBytes) { - next_state_ = kChunk; - std::memcpy(buffer_ + kSlopBytes, chunk_.begin(), kSlopBytes); - return {buffer_, kSlopBytes}; - } else if (chunk_.empty()) { + skip_ += kSlopBytes; + // We need to fill in the other half of buffer_ with the start of the + // next chunk. So we need to continue to the next buffer in the ZCIS, + // which makes it impossible to rollback to the current buffer :( + // We need to verify this won't happen. + if (!ensure_not_end(buffer_, kSlopBytes)) { + // We are guaranteed to exit in this interval. next_state_ = kEOS; return {buffer_, kSlopBytes}; - } else { - auto size = chunk_.size(); - // The next chunk is not big enough. So we copy it in the current - // after the current buffer. Resulting in a buffer with - // size + kSlopBytes bytes. - std::memcpy(buffer_ + kSlopBytes, chunk_.begin(), size); - chunk_ = {buffer_, size + kSlopBytes}; - return {buffer_, size}; - } - case kStart: { - size_t i = 0; - do { - chunk_ = GetChunk(); - if (chunk_.size() > kSlopBytes) { - if (i == 0) { - next_state_ = kBuffer; - return {chunk_.begin(), chunk_.size() - kSlopBytes}; - } - std::memcpy(buffer_ + i, chunk_.begin(), kSlopBytes); - next_state_ = kChunk; - return {buffer_, i}; - } - if (chunk_.empty()) { - next_state_ = kEOS; - return {buffer_, i}; - } - std::memcpy(buffer_ + i, chunk_.begin(), chunk_.size()); - i += chunk_.size(); - } while (i <= kSlopBytes); - chunk_ = {buffer_, i}; - next_state_ = kBuffer; - return {buffer_, i - kSlopBytes}; - } - } - } - - StringPiece NextWithOverlapEndingSafe(const char* ptr, int nesting) { - switch (next_state_) { - case kEOS: - // End of stream - return nullptr; - case kChunk: - // chunk_ contains a buffer of sufficient size (> kSlopBytes). - // To parse the last kSlopBytes we need to copy the bytes into the - // buffer. Hence we set, - next_state_ = kBuffer; - return {chunk_.begin(), chunk_.size() - kSlopBytes}; - case kBuffer: - // We have to parse the last kSlopBytes of chunk_, which could alias - // buffer_ so we have to memmove. - if (!SafeCopy(buffer_, chunk_.end() - kSlopBytes, nesting)) { - // We will terminate } chunk_ = GetChunk(); - if (chunk_.size() > kSlopBytes) { + auto size = chunk_.size(); + if (size > kSlopBytes) { next_state_ = kChunk; std::memcpy(buffer_ + kSlopBytes, chunk_.begin(), kSlopBytes); return {buffer_, kSlopBytes}; - } else if (chunk_.empty()) { + } else if (size == 0) { next_state_ = kEOS; return {buffer_, kSlopBytes}; } else { - auto size = chunk_.size(); + // next_state_ = kBuffer, but this is unnecessary + // The next chunk is not big enough. So we copy it in the current // after the current buffer. Resulting in a buffer with // size + kSlopBytes bytes. std::memcpy(buffer_ + kSlopBytes, chunk_.begin(), size); + // skip_ becomes negative here. + skip_ += size - kSlopBytes; chunk_ = {buffer_, size + kSlopBytes}; return {buffer_, size}; } + } case kStart: { + chunk_ = GetChunk(); + auto size = chunk_.size(); + if (PROTOBUF_PREDICT_TRUE(size > kSlopBytes)) { + next_state_ = kBuffer; + skip_ = size - kSlopBytes; + return {chunk_.begin(), size - kSlopBytes}; + } size_t i = 0; do { - chunk_ = GetChunk(); - if (chunk_.size() > kSlopBytes) { - if (i == 0) { - next_state_ = kBuffer; - return {chunk_.begin(), chunk_.size() - kSlopBytes}; - } - std::memcpy(buffer_ + i, chunk_.begin(), kSlopBytes); - next_state_ = kChunk; + if (size == 0) { + next_state_ = kEOS; return {buffer_, i}; } - if (chunk_.empty()) { + std::memcpy(buffer_ + i, chunk_.begin(), size); + ABSL_ASSERT(skip_ == 0); + skip_ = size; + i += size; + if (i > kSlopBytes) { + skip_ -= kSlopBytes; + chunk_ = {buffer_, i}; + next_state_ = kBuffer; + return {buffer_, i - kSlopBytes}; + } + if (!ensure_not_end(buffer_, i)) { next_state_ = kEOS; return {buffer_, i}; } - std::memcpy(buffer_ + i, chunk_.begin(), chunk_.size()); - i += chunk_.size(); - } while (i <= kSlopBytes); - chunk_ = {buffer_, i}; - next_state_ = kBuffer; - return {buffer_, i - kSlopBytes}; + chunk_ = GetChunk(); + size = chunk_.size(); + } while (size <= kSlopBytes); + std::memcpy(buffer_ + i, chunk_.begin(), kSlopBytes); + next_state_ = kChunk; + return {buffer_, i}; } } } - void Backup(const char* ptr) { skip_ = ptr - chunk_.data(); } + StringPiece NextWithOverlap() { + return SafeNextWithOverlap([](const char*, size_t) { return true; }); + } + + void AdjustPos(int delta) { + ABSL_ASSERT(delta <= kSlopBytes); + skip_ += delta; + } + + void SetError() { skip_ = 0; } private: io::CodedInputStream* input_; StringPiece chunk_; - char buffer_[2 * kSlopBytes]; + char buffer_[2 * kSlopBytes] = {}; enum State { - kEOS = 0, // -> end of stream. - kChunk = 1, // -> chunk_ contains the data for Next. - kBuffer = 2, // -> We need to copy the left over from previous chunk_ and - // load and patch the start of the next chunk in the - // local buffer. - kStart = 3, + kStart, + kEOS, // -> end of stream. + kChunk, // -> chunk_ contains the data for Next. + kBuffer, // -> We need to copy the left over from previous chunk_ and + // load and patch the start of the next chunk in the + // local buffer. }; State next_state_ = kStart; - int skip_ = 0; + int skip_ = 0; // how much bytes to skip to current position in the stream. StringPiece GetChunk() { const void* ptr; - if (skip_) input_->Skip(skip_); - if (!input_->GetDirectBufferPointer(&ptr, &skip_)) { + ABSL_ASSERT(skip_ >= 0); + input_->Skip(skip_); + skip_ = 0; + int size; + if (!input_->GetDirectBufferPointer(&ptr, &size)) { return nullptr; } - return StringPiece(static_cast(ptr), skip_); + return StringPiece(static_cast(ptr), size); } }; #endif @@ -287,29 +311,71 @@ class EpsCopyInputStream { // messages, every function call introduces significant overhead. To avoid // this without reproducing code, we use these forced-inline helpers. -inline bool InlineMergePartialFromCodedStream(io::CodedInputStream* input, +inline bool InlineMergeFromCodedStream(io::CodedInputStream* input, + MessageLite* message) { + if (!message->MergePartialFromCodedStream(input)) return false; + if (!message->IsInitialized()) { + GOOGLE_LOG(ERROR) << InitializationErrorMessage("parse", *message); + return false; + } + return true; +} + +inline bool InlineParsePartialFromCodedStream(io::CodedInputStream* input, MessageLite* message) { + message->Clear(); + return message->MergePartialFromCodedStream(input); +} + +inline bool InlineParseFromCodedStream(io::CodedInputStream* input, + MessageLite* message) { + message->Clear(); + return InlineMergeFromCodedStream(input, message); +} + #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER - EpsCopyInputStream eps_input(input); +template