diff options
Diffstat (limited to 'java/core/src/main/java')
71 files changed, 4397 insertions, 5522 deletions
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 09aaed18..fe1bebc7 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. - * <br> - * 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. + * + * <p>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<FieldDescriptor, Object> a, - Map<FieldDescriptor, Object> b) { + static boolean compareFields(Map<FieldDescriptor, Object> a, Map<FieldDescriptor, Object> 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<? extends EnumLite> list = (List<? extends EnumLite>) 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<BuilderType extends Builder<BuilderType>> - extends AbstractMessageLite.Builder - implements Message.Builder { + public abstract static class Builder<BuilderType extends Builder<BuilderType>> + 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<FieldDescriptor, Object> entry : - getAllFields().entrySet()) { + for (final Map.Entry<FieldDescriptor, Object> 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<FieldDescriptor, Object> 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<FieldDescriptor, Object> 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. + * <p>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. + * <p>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 b22bbaab..17205750 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<MessageType, BuilderType>, - BuilderType extends AbstractMessageLite.Builder<MessageType, BuilderType>> - implements MessageLite { + MessageType extends AbstractMessageLite<MessageType, BuilderType>, + BuilderType extends AbstractMessageLite.Builder<MessageType, BuilderType>> + 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<MessageType, BuilderType>, - BuilderType extends Builder<MessageType, BuilderType>> + MessageType extends AbstractMessageLite<MessageType, BuilderType>, + BuilderType extends Builder<MessageType, BuilderType>> 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 ba570e3d..abfaca8c 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)} + * <p>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<MessageType extends MessageLite> implements Parser<MessageType> { - /** - * 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<MessageType extends MessageLite> 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<MessageType extends MessageLite> @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<MessageType extends MessageLite> 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<MessageType extends MessageLite> @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<MessageType extends MessageLite> @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 b17db6e0..3220f640 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. - * <p> - * 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. + * + * <p>This implementation assumes all subclasses are array based, supporting random access. */ abstract class AbstractProtobufList<E> extends AbstractList<E> implements ProtobufList<E> { 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<E> extends AbstractList<E> implements Protob ensureIsMutable(); return super.addAll(c); } - + @Override public boolean addAll(int index, Collection<? extends E> c) { ensureIsMutable(); @@ -127,47 +122,47 @@ abstract class AbstractProtobufList<E> extends AbstractList<E> 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 d535efb9..8af80057 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; /** - * <p>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 d01f0b8f..e2b99c96 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 0dedb173..2c8929e5 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<Boolean> +final class BooleanArrayList extends AbstractProtobufList<Boolean> 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 6157a52f..2cb3ada6 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<SoftReference<byte[]>> BUFFER = new ThreadLocal<SoftReference<byte[]>>(); - /** - * 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 ee588753..dba7a379 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: * - * <p><b>Traditional write operations:</b> - * (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. + * <p><b>Traditional write operations:</b> (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. * * <p><b>Lazy write operations:</b> 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. * * <p>NOTE: This method <strong>MUST NOT</strong> 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. * * <p>NOTE: This method <strong>MUST NOT</strong> 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 ddda0f26..844d8a53 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<Byte>, 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[]}. * - * <p>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 + * <p>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<Byte>, 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<Byte>, 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<Byte>, 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<Byte>, Serializable { } /** - * This interface extends {@code Iterator<Byte>}, so that we can return an - * unboxed {@code byte}. + * This interface extends {@code Iterator<Byte>}, so that we can return an unboxed {@code byte}. */ public interface ByteIterator extends Iterator<Byte> { /** - * 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<Byte>, Serializable { * Compares two {@link ByteString}s lexicographically, treating their contents as unsigned byte * values between 0 and 255 (inclusive). * - * <p>For example, {@code (byte) -1} is considered to be greater than {@code (byte) 1} because - * it is interpreted as an unsigned value, {@code 255}. + * <p>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<ByteString> UNSIGNED_LEXICOGRAPHICAL_COMPARATOR = new Comparator<ByteString>() { @@ -271,12 +263,12 @@ public abstract class ByteString implements Iterable<Byte>, Serializable { * Returns a {@link Comparator<ByteString>} which compares {@link ByteString}-s lexicographically * as sequences of unsigned bytes (i.e. values between 0 and 255, inclusive). * - * <p>For example, {@code (byte) -1} is considered to be greater than {@code (byte) 1} because - * it is interpreted as an unsigned value, {@code 255}: + * <p>For example, {@code (byte) -1} is considered to be greater than {@code (byte) 1} because it + * is interpreted as an unsigned value, {@code 255}: * * <ul> - * <li>{@code `-1` -> 0b11111111 (two's complement) -> 255} - * <li>{@code `1` -> 0b00000001 -> 1} + * <li>{@code `-1` -> 0b11111111 (two's complement) -> 255} + * <li>{@code `1` -> 0b00000001 -> 1} * </ul> */ public static Comparator<ByteString> unsignedLexicographicalComparator() { @@ -287,56 +279,49 @@ public abstract class ByteString implements Iterable<Byte>, 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 <code>true</code> if the byte sequence represented by the - * argument is a prefix of the byte sequence represented by - * this string; <code>false</code> otherwise. + * @return <code>true</code> if the byte sequence represented by the argument is a prefix of the + * byte sequence represented by this string; <code>false</code> 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 <code>true</code> if the byte sequence represented by the - * argument is a suffix of the byte sequence represented by - * this string; <code>false</code> otherwise. + * @return <code>true</code> if the byte sequence represented by the argument is a suffix of the + * byte sequence represented by this string; <code>false</code> 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<Byte>, 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<Byte>, 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<Byte>, 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<Byte>, 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<Byte>, 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<Byte>, 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<Byte>, 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<Byte>, 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. - * - * <b>Performance notes:</b> 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. - * - * <p>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. + * + * <p><b>Performance notes:</b> 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. + * + * <p>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. - * - * <b>Performance notes:</b> 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. - * - * <p>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. + * + * <p><b>Performance notes:</b> 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. + * + * <p>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<ByteString> results = new ArrayList<ByteString>(); // copy the inbound bytes into a list of chunks; the chunk size @@ -536,42 +505,39 @@ public abstract class ByteString implements Iterable<Byte>, 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, <a + * 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, <a * href="http://www.cs.ubc.ca/local/reading/proceedings/spe91-95/spe/vol25/issue12/spe986.pdf"> * BAP95 </a>. In general, the concatenate involves no copying. * @@ -580,21 +546,20 @@ public abstract class ByteString implements Iterable<Byte>, 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). * - * <p>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. + * <p>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<Byte>, Serializable { final int size; if (!(byteStrings instanceof Collection)) { int tempSize = 0; - for (Iterator<ByteString> iter = byteStrings.iterator(); iter.hasNext(); - iter.next(), ++tempSize) { - } + for (Iterator<ByteString> iter = byteStrings.iterator(); + iter.hasNext(); + iter.next(), ++tempSize) {} size = tempSize; } else { size = ((Collection<ByteString>) byteStrings).size(); @@ -676,13 +641,11 @@ public abstract class ByteString implements Iterable<Byte>, 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<Byte>, 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<Byte>, 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}. * * <p>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. - * <p> - * 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. + * + * <p>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<ByteBuffer> 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<Byte>, 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<Byte>, 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<Byte>, 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. * - * <p>More precisely, returns {@code true} whenever: <pre> {@code + * <p>More precisely, returns {@code true} whenever: + * + * <pre>{@code * Arrays.equals(byteString.toByteArray(), * new String(byteString.toByteArray(), "UTF-8").getBytes("UTF-8")) * }</pre> * - * <p>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. + * <p>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. * * <p>See the Unicode Standard,<br> * Table 3-6. <em>UTF-8 Bit Distribution</em>,<br> * Table 3-7. <em>Well Formed UTF-8 Byte Sequences</em>. * - * @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<Byte>, 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<Byte>, 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<Byte>, 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<Byte>, Serializable { /** * Creates an {@code InputStream} which can be used to read the bytes. - * <p> - * 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}. - * <p> - * The methods in the returned {@link InputStream} might <b>not</b> be - * thread safe. + * + * <p>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}. + * + * <p>The methods in the returned {@link InputStream} might <b>not</b> 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<Byte>, Serializable { /** * Creates a new {@link Output} with the given initial capacity. Call {@link * Output#toByteString()} to create the {@code ByteString} instance. - * <p> - * 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. + * + * <p>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<Byte>, Serializable { } /** - * Creates a new {@link Output}. Call {@link Output#toByteString()} to create - * the {@code ByteString} instance. - * <p> - * 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. + * + * <p>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<Byte>, 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<Byte>, 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<Byte>, 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<Byte>, 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<Byte>, 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<Byte>, 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<Byte>, Serializable { @Override public String toString() { - return String.format("<ByteString.Output@%s size=%d>", + return String.format( + "<ByteString.Output@%s size=%d>", 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<Byte>, 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}. * - * <p>This is package-private because it's a somewhat confusing interface. - * Users can call {@link Message#toByteString()} instead of calling this - * directly. + * <p>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<Byte>, 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<Byte>, 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<Byte>, Serializable { @Override public final String toString() { - return String.format("<ByteString@%s size=%d>", - Integer.toHexString(System.identityHashCode(this)), size()); + return String.format( + "<ByteString@%s size=%d>", 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<Byte>, 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<Byte>, 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<Byte>, 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<Byte>, 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<Byte>, 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)}. * - * <p>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. + * <p>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<Byte>, 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<Byte>, 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<Byte>, 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 4545d0ae..df4cc664 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 7b1ac651..975cb90e 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. * - * <p>This class contains two kinds of methods: methods that write specific - * protocol message constructs and field types (e.g. {@link #writeTag} and - * {@link #writeInt32}) and methods that write low-level values (e.g. - * {@link #writeRawVarint32} and {@link #writeRawBytes}). If you are - * writing encoded protocol messages, you should use the former methods, but if - * you are writing some other format of your own design, use the latter. + * <p>This class contains two kinds of methods: methods that write specific protocol message + * constructs and field types (e.g. {@link #writeTag} and {@link #writeInt32}) and methods that + * write low-level values (e.g. {@link #writeRawVarint32} and {@link #writeRawBytes}). If you are + * writing encoded protocol messages, you should use the former methods, but if you are writing some + * other format of your own design, use the latter. * * <p>This class is totally unsynchronized. */ @@ -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}. * - * <p> NOTE: The provided {@link OutputStream} <strong>MUST NOT</strong> retain access or - * modify the provided byte arrays. Doing so may result in corrupted data, which would be - * difficult to debug. + * <p>NOTE: The provided {@link OutputStream} <strong>MUST NOT</strong> 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. * - * <p> NOTE: The provided {@link OutputStream} <strong>MUST NOT</strong> retain access or - * modify the provided byte arrays. Doing so may result in corrupted data, which would be - * difficult to debug. + * <p>NOTE: The provided {@link OutputStream} <strong>MUST NOT</strong> 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: * * <ul> - * <li>repeated serialization of a message will return the same bytes - * <li>different processes of the same binary (which may be executing on different machines) will - * serialize equal messages to the same bytes. + * <li>repeated serialization of a message will return the same bytes + * <li>different processes of the same binary (which may be executing on different machines) + * will serialize equal messages to the same bytes. * </ul> * * <p>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. * - * <p> Once set, the serializer will: (Note this is an implementation detail and may subject to + * <p>Once set, the serializer will: (Note this is an implementation detail and may subject to * change in the future) * * <ul> - * <li> 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. + * <li>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. * </ul> */ 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}. * - * <p> NOTE: The {@link ByteOutput} <strong>MUST NOT</strong> modify the provided buffers. Doing - * so may result in corrupted data, which would be difficult to debug. + * <p>NOTE: The {@link ByteOutput} <strong>MUST NOT</strong> 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 75b16fe3..8f751925 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. + * <p>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}. + * <p>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<Descriptor> 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<FileDescriptor> descriptors = new ArrayList<FileDescriptor>(); 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<String, FileDescriptor> nameToFileMap = - new HashMap<String, FileDescriptor>(); + HashMap<String, FileDescriptor> nameToFileMap = new HashMap<String, FileDescriptor>(); 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: + * * <pre> * for all i in [0, file.getMessageTypeCount()): * file.getMessageType(i).getIndex() == i * </pre> + * * Similarly, for a {@link Descriptor} {@code messageType}: + * * <pre> * for all i in [0, messageType.getNestedTypeCount()): * messageType.getNestedType(i).getIndex() == i * </pre> */ - 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}: + * * <pre> * package foo.bar; * option java_package = "com.example.protos" * message Baz {} * </pre> + * * {@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<FieldDescriptor> 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<FieldDescriptor>, - FieldSet.FieldDescriptorLite<FieldDescriptor> { + public static final class FieldDescriptor extends GenericDescriptor + implements Comparable<FieldDescriptor>, FieldSet.FieldDescriptorLite<FieldDescriptor> { /** * 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: + * * <pre> * message Foo { * extensions 1000 to max; @@ -1072,14 +1066,14 @@ public final class Descriptors { * } * } * </pre> - * 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<EnumValueDescriptor> { /** * 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<EnumValueDescriptor> 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<Integer, WeakReference<EnumValueDescriptor>> unknownValues = new WeakHashMap<Integer, WeakReference<EnumValueDescriptor>>(); - 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<MethodDescriptor> 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}.<p> + * 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. + * <p>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<FileDescriptor>(); 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<String, GenericDescriptor> descriptorsByName = - new HashMap<String, GenericDescriptor>(); + new HashMap<String, GenericDescriptor>(); private final Map<DescriptorIntPair, FieldDescriptor> fieldsByNumber = - new HashMap<DescriptorIntPair, FieldDescriptor>(); - private final Map<DescriptorIntPair, EnumValueDescriptor> enumValuesByNumber - = new HashMap<DescriptorIntPair, EnumValueDescriptor>(); + new HashMap<DescriptorIntPair, FieldDescriptor>(); + private final Map<DescriptorIntPair, EnumValueDescriptor> enumValuesByNumber = + new HashMap<DescriptorIntPair, EnumValueDescriptor>(); /** 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 7ae94349..fefa636e 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. * * <p>Usage example: + * * <pre>{@code - * private final static Parser<Foo> FOO_PARSER = DiscardUnknownFieldsParser.wrap(Foo.parser()); - * Foo parseFooDiscardUnknown(ByteBuffer input) throws IOException { - * return FOO_PARSER.parseFrom(input); - * } + * private final static Parser<Foo> FOO_PARSER = DiscardUnknownFieldsParser.wrap(Foo.parser()); + * Foo parseFooDiscardUnknown(ByteBuffer input) throws IOException { + * return FOO_PARSER.parseFrom(input); + * } * }</pre> * * <p>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 8d987b2e..e7b8fa83 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<Double> +final class DoubleArrayList extends AbstractProtobufList<Double> 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 2c346e03..63dda6b9 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. + * <p>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<FieldDescriptor> fields, - FieldDescriptor[] oneofCases, - UnknownFieldSet unknownFields) { + DynamicMessage( + Descriptor type, + FieldSet<FieldDescriptor> 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.<FieldDescriptor>emptySet(), - oneofCases, - UnknownFieldSet.getDefaultInstance()); + return new DynamicMessage( + type, + FieldSet.<FieldDescriptor>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<FieldDescriptor> fields) { + static boolean isInitialized(Descriptor type, FieldSet<FieldDescriptor> 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<Builder> { private final Descriptor type; private FieldSet<FieldDescriptor> 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 3cd4c884..d55b278c 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. * * <p>Usage guidelines: + * * <ol> - * <li>This annotation is used only on public API. Internal interfaces should not use it.</li> - * <li>This annotation should only be added to new APIs. Adding it to an existing API is - * considered API-breaking.</li> - * <li>Removing this annotation from an API gives it stable status.</li> + * <li>This annotation is used only on public API. Internal interfaces should not use it. + * <li>This annotation should only be added to new APIs. Adding it to an existing API is + * considered API-breaking. + * <li>Removing this annotation from an API gives it stable status. * </ol> */ @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 5df12e64..e5da634f 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<ContainingType extends MessageLite, Type> // 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<ContainingType extends MessageLite, Type> 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 f8f5bd2c..0fb5f49e 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. - * <p> - * Methods are for use by generated code only. You can hold a reference to - * extensions using this type name. + * + * <p>Methods are for use by generated code only. You can hold a reference to extensions using this + * type name. */ public abstract class ExtensionLite<ContainingType extends MessageLite, Type> { @@ -50,12 +50,9 @@ public abstract class ExtensionLite<ContainingType extends MessageLite, Type> { /** 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 a22a74a0..aeeaee53 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. * * <p>For example, if you had the {@code .proto} file: * @@ -70,25 +69,22 @@ import java.util.Set; * * <p>Background: * - * <p>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. + * <p>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. * - * <p>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. + * <p>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<ExtensionInfo> getAllMutableExtensionsByExtendedType(final String fullName) { HashSet<ExtensionInfo> extensions = new HashSet<ExtensionInfo>(); @@ -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<ExtensionInfo> getAllImmutableExtensionsByExtendedType(final String fullName) { HashSet<ExtensionInfo> extensions = new HashSet<ExtensionInfo>(); @@ -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<String, ExtensionInfo>(); this.mutableExtensionsByName = new HashMap<String, ExtensionInfo>(); - this.immutableExtensionsByNumber = - new HashMap<DescriptorIntPair, ExtensionInfo>(); - this.mutableExtensionsByNumber = - new HashMap<DescriptorIntPair, ExtensionInfo>(); + this.immutableExtensionsByNumber = new HashMap<DescriptorIntPair, ExtensionInfo>(); + this.mutableExtensionsByNumber = new HashMap<DescriptorIntPair, ExtensionInfo>(); } 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<String, ExtensionInfo> immutableExtensionsByName; @@ -316,24 +290,19 @@ public class ExtensionRegistry extends ExtensionRegistryLite { ExtensionRegistry(boolean empty) { super(EMPTY_REGISTRY_LITE); - this.immutableExtensionsByName = - Collections.<String, ExtensionInfo>emptyMap(); - this.mutableExtensionsByName = - Collections.<String, ExtensionInfo>emptyMap(); - this.immutableExtensionsByNumber = - Collections.<DescriptorIntPair, ExtensionInfo>emptyMap(); - this.mutableExtensionsByNumber = - Collections.<DescriptorIntPair, ExtensionInfo>emptyMap(); + this.immutableExtensionsByName = Collections.<String, ExtensionInfo>emptyMap(); + this.mutableExtensionsByName = Collections.<String, ExtensionInfo>emptyMap(); + this.immutableExtensionsByNumber = Collections.<DescriptorIntPair, ExtensionInfo>emptyMap(); + this.mutableExtensionsByNumber = Collections.<DescriptorIntPair, ExtensionInfo>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<String, ExtensionInfo> 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 89f7ab9b..f070aae7 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}. * - * <p> - * 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}. + * <p>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 f3d48d3a..0ce5f549 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. - * <p> - * 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. - * <p> - * 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: + * + * <p>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. + * + * <p>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: + * * <pre> * Extended type Inner type Extension Use registry * ======================================================================= @@ -60,13 +58,12 @@ import java.util.Map; * regular regular regular ExtensionRegistry * all other combinations not supported * </pre> - * <p> - * 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. + * + * <p>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 <ContainingType extends MessageLite> - GeneratedMessageLite.GeneratedExtension<ContainingType, ?> - findLiteExtensionByNumber( - final ContainingType containingTypeDefaultInstance, - final int fieldNumber) { + GeneratedMessageLite.GeneratedExtension<ContainingType, ?> findLiteExtensionByNumber( + final ContainingType containingTypeDefaultInstance, final int fieldNumber) { return (GeneratedMessageLite.GeneratedExtension<ContainingType, ?>) - 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<ObjectIntPair, - GeneratedMessageLite.GeneratedExtension<?, ?>>(); + new HashMap<ObjectIntPair, GeneratedMessageLite.GeneratedExtension<?, ?>>(); } - 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<ObjectIntPair, - GeneratedMessageLite.GeneratedExtension<?, ?>> + private final Map<ObjectIntPair, GeneratedMessageLite.GeneratedExtension<?, ?>> 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 c09daa32..40a37625 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<FieldDescriptorType extends - FieldSet.FieldDescriptorLite<FieldDescriptorType>> { +final class FieldSet< + FieldDescriptorType extends FieldSet.FieldDescriptorLite<FieldDescriptorType>> { /** - * 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<T extends FieldDescriptorLite<T>> - extends Comparable<T> { + public interface FieldDescriptorLite<T extends FieldDescriptorLite<T>> extends Comparable<T> { 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<FieldDescriptorType, Object> fields; @@ -78,27 +81,23 @@ final class FieldSet<FieldDescriptorType extends this.fields = SmallSortedMap.newFieldMap(16); } - /** - * Construct an empty FieldSet. This is only used to initialize - * DEFAULT_INSTANCE. - */ + /** Construct an empty FieldSet. This is only used to initialize DEFAULT_INSTANCE. */ private FieldSet(final boolean dummy) { this.fields = SmallSortedMap.newFieldMap(0); makeImmutable(); } /** Construct a new FieldSet. */ - public static <T extends FieldSet.FieldDescriptorLite<T>> - FieldSet<T> newFieldSet() { + public static <T extends FieldSet.FieldDescriptorLite<T>> FieldSet<T> newFieldSet() { return new FieldSet<T>(); } /** Get an immutable empty FieldSet. */ @SuppressWarnings("unchecked") - public static <T extends FieldSet.FieldDescriptorLite<T>> - FieldSet<T> emptySet() { + public static <T extends FieldSet.FieldDescriptorLite<T>> FieldSet<T> emptySet() { return DEFAULT_INSTANCE; } + @SuppressWarnings("rawtypes") private static final FieldSet DEFAULT_INSTANCE = new FieldSet(true); @@ -118,8 +117,8 @@ final class FieldSet<FieldDescriptorType extends } /** - * Returns whether the FieldSet is immutable. This is true if it is the - * {@link #emptySet} or if {@link #makeImmutable} were called. + * Returns whether the FieldSet is immutable. This is true if it is the {@link #emptySet} or if + * {@link #makeImmutable} were called. * * @return whether the FieldSet is immutable. */ @@ -147,8 +146,8 @@ final class FieldSet<FieldDescriptorType extends } /** - * Clones the FieldSet. The returned FieldSet will be mutable even if the - * original FieldSet was immutable. + * Clones the FieldSet. The returned FieldSet will be mutable even if the original FieldSet was + * immutable. * * @return the newly cloned FieldSet */ @@ -162,8 +161,7 @@ final class FieldSet<FieldDescriptorType extends FieldDescriptorType descriptor = entry.getKey(); clone.setField(descriptor, entry.getValue()); } - for (Map.Entry<FieldDescriptorType, Object> entry : - fields.getOverflowEntries()) { + for (Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) { FieldDescriptorType descriptor = entry.getKey(); clone.setField(descriptor, entry.getValue()); } @@ -180,18 +178,14 @@ final class FieldSet<FieldDescriptorType extends hasLazyField = false; } - /** - * Get a simple map containing all the fields. - */ + /** Get a simple map containing all the fields. */ public Map<FieldDescriptorType, Object> getAllFields() { if (hasLazyField) { - SmallSortedMap<FieldDescriptorType, Object> result = - SmallSortedMap.newFieldMap(16); + SmallSortedMap<FieldDescriptorType, Object> result = SmallSortedMap.newFieldMap(16); for (int i = 0; i < fields.getNumArrayEntries(); i++) { cloneFieldEntry(result, fields.getArrayEntryAt(i)); } - for (Map.Entry<FieldDescriptorType, Object> entry : - fields.getOverflowEntries()) { + for (Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) { cloneFieldEntry(result, entry); } if (fields.isImmutable()) { @@ -202,8 +196,8 @@ final class FieldSet<FieldDescriptorType extends return fields.isImmutable() ? fields : Collections.unmodifiableMap(fields); } - private void cloneFieldEntry(Map<FieldDescriptorType, Object> map, - Map.Entry<FieldDescriptorType, Object> entry) { + private void cloneFieldEntry( + Map<FieldDescriptorType, Object> map, Map.Entry<FieldDescriptorType, Object> entry) { FieldDescriptorType key = entry.getKey(); Object value = entry.getValue(); if (value instanceof LazyField) { @@ -214,37 +208,30 @@ final class FieldSet<FieldDescriptorType extends } /** - * Get an iterator to the field map. This iterator should not be leaked out - * of the protobuf library as it is not protected from mutation when fields - * is not immutable. + * Get an iterator to the field map. This iterator should not be leaked out of the protobuf + * library as it is not protected from mutation when fields is not immutable. */ public Iterator<Map.Entry<FieldDescriptorType, Object>> iterator() { if (hasLazyField) { - return new LazyIterator<FieldDescriptorType>( - fields.entrySet().iterator()); + return new LazyIterator<FieldDescriptorType>(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<FieldDescriptorType extends } /** - * Useful for implementing - * {@link Message.Builder#setField(Descriptors.FieldDescriptor,Object)}. + * Useful for implementing {@link Message.Builder#setField(Descriptors.FieldDescriptor,Object)}. */ @SuppressWarnings({"unchecked", "rawtypes"}) - public void setField(final FieldDescriptorType descriptor, - Object value) { + public void setField(final FieldDescriptorType descriptor, Object value) { if (descriptor.isRepeated()) { if (!(value instanceof List)) { throw new IllegalArgumentException( - "Wrong object type used with protocol message reflection."); + "Wrong object type used with protocol message reflection."); } // Wrap the contents in a new list so that the caller cannot change @@ -285,10 +270,7 @@ final class FieldSet<FieldDescriptorType extends fields.put(descriptor, value); } - /** - * Useful for implementing - * {@link Message.Builder#clearField(Descriptors.FieldDescriptor)}. - */ + /** Useful for implementing {@link Message.Builder#clearField(Descriptors.FieldDescriptor)}. */ public void clearField(final FieldDescriptorType descriptor) { fields.remove(descriptor); if (fields.isEmpty()) { @@ -296,14 +278,11 @@ final class FieldSet<FieldDescriptorType extends } } - /** - * Useful for implementing - * {@link Message#getRepeatedFieldCount(Descriptors.FieldDescriptor)}. - */ + /** Useful for implementing {@link Message#getRepeatedFieldCount(Descriptors.FieldDescriptor)}. */ public int getRepeatedFieldCount(final FieldDescriptorType descriptor) { if (!descriptor.isRepeated()) { throw new IllegalArgumentException( - "getRepeatedField() can only be called on repeated fields."); + "getRepeatedField() can only be called on repeated fields."); } final Object value = getField(descriptor); @@ -314,15 +293,11 @@ final class FieldSet<FieldDescriptorType extends } } - /** - * Useful for implementing - * {@link Message#getRepeatedField(Descriptors.FieldDescriptor,int)}. - */ - public Object getRepeatedField(final FieldDescriptorType descriptor, - final int index) { + /** Useful for implementing {@link Message#getRepeatedField(Descriptors.FieldDescriptor,int)}. */ + public Object getRepeatedField(final FieldDescriptorType descriptor, final int index) { if (!descriptor.isRepeated()) { throw new IllegalArgumentException( - "getRepeatedField() can only be called on repeated fields."); + "getRepeatedField() can only be called on repeated fields."); } final Object value = getField(descriptor); @@ -335,16 +310,15 @@ final class FieldSet<FieldDescriptorType extends } /** - * Useful for implementing - * {@link Message.Builder#setRepeatedField(Descriptors.FieldDescriptor,int,Object)}. + * Useful for implementing {@link + * Message.Builder#setRepeatedField(Descriptors.FieldDescriptor,int,Object)}. */ @SuppressWarnings("unchecked") - public void setRepeatedField(final FieldDescriptorType descriptor, - final int index, - final Object value) { + public void setRepeatedField( + final FieldDescriptorType descriptor, final int index, final Object value) { if (!descriptor.isRepeated()) { throw new IllegalArgumentException( - "getRepeatedField() can only be called on repeated fields."); + "getRepeatedField() can only be called on repeated fields."); } final Object list = getField(descriptor); @@ -357,15 +331,14 @@ final class FieldSet<FieldDescriptorType extends } /** - * Useful for implementing - * {@link Message.Builder#addRepeatedField(Descriptors.FieldDescriptor,Object)}. + * Useful for implementing {@link + * Message.Builder#addRepeatedField(Descriptors.FieldDescriptor,Object)}. */ @SuppressWarnings("unchecked") - public void addRepeatedField(final FieldDescriptorType descriptor, - final Object value) { + public void addRepeatedField(final FieldDescriptorType descriptor, final Object value) { if (!descriptor.isRepeated()) { throw new IllegalArgumentException( - "addRepeatedField() can only be called on repeated fields."); + "addRepeatedField() can only be called on repeated fields."); } verifyType(descriptor.getLiteType(), value); @@ -383,36 +356,45 @@ final class FieldSet<FieldDescriptorType extends } /** - * Verifies that the given object is of the correct type to be a valid - * value for the given field. (For repeated fields, this checks if the - * object is the right type to be one element of the field.) + * Verifies that the given object is of the correct type to be a valid value for the given field. + * (For repeated fields, this checks if the object is the right type to be one element of the + * field.) * * @throws IllegalArgumentException The value is not of the right type. */ - private static void verifyType(final WireFormat.FieldType type, - final Object value) { + private static void verifyType(final WireFormat.FieldType type, final Object value) { checkNotNull(value); boolean isValid = false; switch (type.getJavaType()) { - case INT: isValid = value instanceof Integer ; break; - case LONG: isValid = value instanceof Long ; break; - case FLOAT: isValid = value instanceof Float ; break; - case DOUBLE: isValid = value instanceof Double ; break; - case BOOLEAN: isValid = value instanceof Boolean ; break; - case STRING: isValid = value instanceof String ; break; + case INT: + isValid = value instanceof Integer; + break; + case LONG: + isValid = value instanceof Long; + break; + case FLOAT: + isValid = value instanceof Float; + break; + case DOUBLE: + isValid = value instanceof Double; + break; + case BOOLEAN: + isValid = value instanceof Boolean; + break; + case STRING: + isValid = value instanceof String; + break; case BYTE_STRING: isValid = value instanceof ByteString || value instanceof byte[]; break; case ENUM: // TODO(kenton): Caller must do type checking here, I guess. - isValid = - (value instanceof Integer || value instanceof Internal.EnumLite); + isValid = (value instanceof Integer || value instanceof Internal.EnumLite); break; case MESSAGE: // TODO(kenton): Caller must do type checking here, I guess. - isValid = - (value instanceof MessageLite) || (value instanceof LazyField); + isValid = (value instanceof MessageLite) || (value instanceof LazyField); break; } @@ -425,7 +407,7 @@ final class FieldSet<FieldDescriptorType extends // isn't a big deal, though, since it would only really apply when using // reflection and generally people don't chain reflection setters. throw new IllegalArgumentException( - "Wrong object type used with protocol message reflection."); + "Wrong object type used with protocol message reflection."); } } @@ -433,10 +415,9 @@ final class FieldSet<FieldDescriptorType extends // Parsing and serialization /** - * See {@link Message#isInitialized()}. Note: Since {@code FieldSet} - * itself does not have any way of knowing about required fields that - * aren't actually present in the set, it is up to the caller to check - * that all required fields are present. + * See {@link Message#isInitialized()}. Note: Since {@code FieldSet} itself does not have any way + * of knowing about required fields that aren't actually present in the set, it is up to the + * caller to check that all required fields are present. */ public boolean isInitialized() { for (int i = 0; i < fields.getNumArrayEntries(); i++) { @@ -444,8 +425,7 @@ final class FieldSet<FieldDescriptorType extends return false; } } - for (final Map.Entry<FieldDescriptorType, Object> entry : - fields.getOverflowEntries()) { + for (final Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) { if (!isInitialized(entry)) { return false; } @@ -454,13 +434,11 @@ final class FieldSet<FieldDescriptorType extends } @SuppressWarnings("unchecked") - private boolean isInitialized( - final Map.Entry<FieldDescriptorType, Object> entry) { + private boolean isInitialized(final Map.Entry<FieldDescriptorType, Object> entry) { final FieldDescriptorType descriptor = entry.getKey(); if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE) { if (descriptor.isRepeated()) { - for (final MessageLite element: - (List<MessageLite>) entry.getValue()) { + for (final MessageLite element : (List<MessageLite>) entry.getValue()) { if (!element.isInitialized()) { return false; } @@ -485,11 +463,9 @@ final class FieldSet<FieldDescriptorType extends /** * Given a field type, return the wire type. * - * @returns One of the {@code WIRETYPE_} constants defined in - * {@link WireFormat}. + * @return One of the {@code WIRETYPE_} constants defined in {@link WireFormat}. */ - static int getWireFormatForFieldType(final WireFormat.FieldType type, - boolean isPacked) { + static int getWireFormatForFieldType(final WireFormat.FieldType type, boolean isPacked) { if (isPacked) { return WireFormat.WIRETYPE_LENGTH_DELIMITED; } else { @@ -497,16 +473,12 @@ final class FieldSet<FieldDescriptorType extends } } - /** - * Like {@link Message.Builder#mergeFrom(Message)}, but merges from another - * {@link FieldSet}. - */ + /** Like {@link Message.Builder#mergeFrom(Message)}, but merges from another {@link FieldSet}. */ public void mergeFrom(final FieldSet<FieldDescriptorType> other) { for (int i = 0; i < other.fields.getNumArrayEntries(); i++) { mergeFromField(other.fields.getArrayEntryAt(i)); } - for (final Map.Entry<FieldDescriptorType, Object> entry : - other.fields.getOverflowEntries()) { + for (final Map.Entry<FieldDescriptorType, Object> entry : other.fields.getOverflowEntries()) { mergeFromField(entry); } } @@ -523,8 +495,7 @@ final class FieldSet<FieldDescriptorType extends } @SuppressWarnings({"unchecked", "rawtypes"}) - private void mergeFromField( - final Map.Entry<FieldDescriptorType, Object> entry) { + private void mergeFromField(final Map.Entry<FieldDescriptorType, Object> entry) { final FieldDescriptorType descriptor = entry.getKey(); Object otherValue = entry.getValue(); if (otherValue instanceof LazyField) { @@ -546,9 +517,10 @@ final class FieldSet<FieldDescriptorType extends fields.put(descriptor, cloneIfMutable(otherValue)); } else { // Merge the messages. - value = descriptor.internalMergeFrom( - ((MessageLite) value).toBuilder(), (MessageLite) otherValue) - .build(); + value = + descriptor + .internalMergeFrom(((MessageLite) value).toBuilder(), (MessageLite) otherValue) + .build(); fields.put(descriptor, value); } @@ -561,72 +533,59 @@ final class FieldSet<FieldDescriptorType extends // other class. Probably WireFormat. /** - * Read a field of any primitive type for immutable messages from a - * CodedInputStream. Enums, groups, and embedded messages are not handled by - * this method. + * Read a field of any primitive type for immutable messages from a CodedInputStream. Enums, + * groups, and embedded messages are not handled by this method. * * @param input The stream from which to read. * @param type Declared type of the field. * @param checkUtf8 When true, check that the input is valid utf8. - * @return An object representing the field's value, of the exact - * type which would be returned by - * {@link Message#getField(Descriptors.FieldDescriptor)} for - * this field. + * @return An object representing the field's value, of the exact type which would be returned by + * {@link Message#getField(Descriptors.FieldDescriptor)} for this field. */ public static Object readPrimitiveField( - CodedInputStream input, - final WireFormat.FieldType type, - boolean checkUtf8) throws IOException { + CodedInputStream input, final WireFormat.FieldType type, boolean checkUtf8) + throws IOException { if (checkUtf8) { - return WireFormat.readPrimitiveField(input, type, - WireFormat.Utf8Validation.STRICT); + return WireFormat.readPrimitiveField(input, type, WireFormat.Utf8Validation.STRICT); } else { - return WireFormat.readPrimitiveField(input, type, - WireFormat.Utf8Validation.LOOSE); + return WireFormat.readPrimitiveField(input, type, WireFormat.Utf8Validation.LOOSE); } } /** See {@link Message#writeTo(CodedOutputStream)}. */ - public void writeTo(final CodedOutputStream output) - throws IOException { + public void writeTo(final CodedOutputStream output) throws IOException { for (int i = 0; i < fields.getNumArrayEntries(); i++) { - final Map.Entry<FieldDescriptorType, Object> entry = - fields.getArrayEntryAt(i); + final Map.Entry<FieldDescriptorType, Object> entry = fields.getArrayEntryAt(i); writeField(entry.getKey(), entry.getValue(), output); } - for (final Map.Entry<FieldDescriptorType, Object> entry : - fields.getOverflowEntries()) { + for (final Map.Entry<FieldDescriptorType, Object> 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<FieldDescriptorType, Object> entry : - fields.getOverflowEntries()) { + for (final Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) { writeMessageSetTo(entry, output); } } private void writeMessageSetTo( - final Map.Entry<FieldDescriptorType, Object> entry, - final CodedOutputStream output) throws IOException { + final Map.Entry<FieldDescriptorType, Object> 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<FieldDescriptorType extends * Write a single tag-value pair to the stream. * * @param output The output stream. - * @param type The field's type. + * @param type The field's type. * @param number The field's number. - * @param value Object representing the field's value. Must be of the exact - * type which would be returned by - * {@link Message#getField(Descriptors.FieldDescriptor)} for - * this field. + * @param value Object representing the field's value. Must be of the exact type which would be + * returned by {@link Message#getField(Descriptors.FieldDescriptor)} for this field. */ static void writeElement( final CodedOutputStream output, final WireFormat.FieldType type, final int number, - final Object value) throws IOException { + final Object value) + throws IOException { // Special case for groups, which need a start and end tag; other fields // can just use writeTag() and writeFieldNoTag(). if (type == WireFormat.FieldType.GROUP) { @@ -663,26 +621,43 @@ final class FieldSet<FieldDescriptorType extends * * @param output The output stream. * @param type The field's type. - * @param value Object representing the field's value. Must be of the exact - * type which would be returned by - * {@link Message#getField(Descriptors.FieldDescriptor)} for - * this field. + * @param value Object representing the field's value. Must be of the exact type which would be + * returned by {@link Message#getField(Descriptors.FieldDescriptor)} for this field. */ static void writeElementNoTag( - final CodedOutputStream output, - final WireFormat.FieldType type, - final Object value) throws IOException { + final CodedOutputStream output, final WireFormat.FieldType type, final Object value) + throws IOException { switch (type) { - case DOUBLE : output.writeDoubleNoTag ((Double ) value); break; - case FLOAT : output.writeFloatNoTag ((Float ) value); break; - case INT64 : output.writeInt64NoTag ((Long ) value); break; - case UINT64 : output.writeUInt64NoTag ((Long ) value); break; - case INT32 : output.writeInt32NoTag ((Integer ) value); break; - case FIXED64 : output.writeFixed64NoTag ((Long ) value); break; - case FIXED32 : output.writeFixed32NoTag ((Integer ) value); break; - case BOOL : output.writeBoolNoTag ((Boolean ) value); break; - case GROUP : output.writeGroupNoTag ((MessageLite) value); break; - case MESSAGE : output.writeMessageNoTag ((MessageLite) value); break; + case DOUBLE: + output.writeDoubleNoTag((Double) value); + break; + case FLOAT: + output.writeFloatNoTag((Float) value); + break; + case INT64: + output.writeInt64NoTag((Long) value); + break; + case UINT64: + output.writeUInt64NoTag((Long) value); + break; + case INT32: + output.writeInt32NoTag((Integer) value); + break; + case FIXED64: + output.writeFixed64NoTag((Long) value); + break; + case FIXED32: + output.writeFixed32NoTag((Integer) value); + break; + case BOOL: + output.writeBoolNoTag((Boolean) value); + break; + case GROUP: + output.writeGroupNoTag((MessageLite) value); + break; + case MESSAGE: + output.writeMessageNoTag((MessageLite) value); + break; case STRING: if (value instanceof ByteString) { output.writeBytesNoTag((ByteString) value); @@ -697,11 +672,21 @@ final class FieldSet<FieldDescriptorType extends output.writeByteArrayNoTag((byte[]) value); } break; - case UINT32 : output.writeUInt32NoTag ((Integer ) value); break; - case SFIXED32: output.writeSFixed32NoTag((Integer ) value); break; - case SFIXED64: output.writeSFixed64NoTag((Long ) value); break; - case SINT32 : output.writeSInt32NoTag ((Integer ) value); break; - case SINT64 : output.writeSInt64NoTag ((Long ) value); break; + case UINT32: + output.writeUInt32NoTag((Integer) value); + break; + case SFIXED32: + output.writeSFixed32NoTag((Integer) value); + break; + case SFIXED64: + output.writeSFixed64NoTag((Long) value); + break; + case SINT32: + output.writeSInt32NoTag((Integer) value); + break; + case SINT64: + output.writeSInt64NoTag((Long) value); + break; case ENUM: if (value instanceof Internal.EnumLite) { @@ -714,14 +699,13 @@ final class FieldSet<FieldDescriptorType extends } /** Write a single field. */ - public static void writeField(final FieldDescriptorLite<?> 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<FieldDescriptorType extends } /** - * See {@link Message#getSerializedSize()}. It's up to the caller to cache - * the resulting size if desired. + * See {@link Message#getSerializedSize()}. It's up to the caller to cache the resulting size if + * desired. */ public int getSerializedSize() { int size = 0; for (int i = 0; i < fields.getNumArrayEntries(); i++) { - final Map.Entry<FieldDescriptorType, Object> entry = - fields.getArrayEntryAt(i); + final Map.Entry<FieldDescriptorType, Object> entry = fields.getArrayEntryAt(i); size += computeFieldSize(entry.getKey(), entry.getValue()); } - for (final Map.Entry<FieldDescriptorType, Object> entry : - fields.getOverflowEntries()) { + for (final Map.Entry<FieldDescriptorType, Object> 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<FieldDescriptorType, Object> entry : - fields.getOverflowEntries()) { + for (final Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) { size += getMessageSetSerializedSize(entry); } return size; } - private int getMessageSetSerializedSize( - final Map.Entry<FieldDescriptorType, Object> entry) { + private int getMessageSetSerializedSize(final Map.Entry<FieldDescriptorType, Object> 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<FieldDescriptorType extends } /** - * Compute the number of bytes that would be needed to encode a - * single tag/value pair of arbitrary type. + * Compute the number of bytes that would be needed to encode a single tag/value pair of arbitrary + * type. * - * @param type The field's type. + * @param type The field's type. * @param number The field's number. - * @param value Object representing the field's value. Must be of the exact - * type which would be returned by - * {@link Message#getField(Descriptors.FieldDescriptor)} for - * this field. + * @param value Object representing the field's value. Must be of the exact type which would be + * returned by {@link Message#getField(Descriptors.FieldDescriptor)} for this field. */ static int computeElementSize( final WireFormat.FieldType type, final int number, final Object value) { @@ -822,46 +799,57 @@ final class FieldSet<FieldDescriptorType extends } /** - * Compute the number of bytes that would be needed to encode a - * particular value of arbitrary type, excluding tag. + * Compute the number of bytes that would be needed to encode a particular value of arbitrary + * type, excluding tag. * - * @param type The field's type. - * @param value Object representing the field's value. Must be of the exact - * type which would be returned by - * {@link Message#getField(Descriptors.FieldDescriptor)} for - * this field. + * @param type The field's type. + * @param value Object representing the field's value. Must be of the exact type which would be + * returned by {@link Message#getField(Descriptors.FieldDescriptor)} for this field. */ - static int computeElementSizeNoTag( - final WireFormat.FieldType type, final Object value) { + static int computeElementSizeNoTag(final WireFormat.FieldType type, final Object value) { switch (type) { - // Note: Minor violation of 80-char limit rule here because this would - // actually be harder to read if we wrapped the lines. - case DOUBLE : return CodedOutputStream.computeDoubleSizeNoTag ((Double )value); - case FLOAT : return CodedOutputStream.computeFloatSizeNoTag ((Float )value); - case INT64 : return CodedOutputStream.computeInt64SizeNoTag ((Long )value); - case UINT64 : return CodedOutputStream.computeUInt64SizeNoTag ((Long )value); - case INT32 : return CodedOutputStream.computeInt32SizeNoTag ((Integer )value); - case FIXED64 : return CodedOutputStream.computeFixed64SizeNoTag ((Long )value); - case FIXED32 : return CodedOutputStream.computeFixed32SizeNoTag ((Integer )value); - case BOOL : return CodedOutputStream.computeBoolSizeNoTag ((Boolean )value); - case GROUP : return CodedOutputStream.computeGroupSizeNoTag ((MessageLite)value); - case BYTES : + // Note: Minor violation of 80-char limit rule here because this would + // actually be harder to read if we wrapped the lines. + case DOUBLE: + return CodedOutputStream.computeDoubleSizeNoTag((Double) value); + case FLOAT: + return CodedOutputStream.computeFloatSizeNoTag((Float) value); + case INT64: + return CodedOutputStream.computeInt64SizeNoTag((Long) value); + case UINT64: + return CodedOutputStream.computeUInt64SizeNoTag((Long) value); + case INT32: + return CodedOutputStream.computeInt32SizeNoTag((Integer) value); + case FIXED64: + return CodedOutputStream.computeFixed64SizeNoTag((Long) value); + case FIXED32: + return CodedOutputStream.computeFixed32SizeNoTag((Integer) value); + case BOOL: + return CodedOutputStream.computeBoolSizeNoTag((Boolean) value); + case GROUP: + return CodedOutputStream.computeGroupSizeNoTag((MessageLite) value); + case BYTES: if (value instanceof ByteString) { return CodedOutputStream.computeBytesSizeNoTag((ByteString) value); } else { return CodedOutputStream.computeByteArraySizeNoTag((byte[]) value); } - case STRING : + case STRING: if (value instanceof ByteString) { return CodedOutputStream.computeBytesSizeNoTag((ByteString) value); } else { return CodedOutputStream.computeStringSizeNoTag((String) value); } - case UINT32 : return CodedOutputStream.computeUInt32SizeNoTag ((Integer )value); - case SFIXED32: return CodedOutputStream.computeSFixed32SizeNoTag((Integer )value); - case SFIXED64: return CodedOutputStream.computeSFixed64SizeNoTag((Long )value); - case SINT32 : return CodedOutputStream.computeSInt32SizeNoTag ((Integer )value); - case SINT64 : return CodedOutputStream.computeSInt64SizeNoTag ((Long )value); + case UINT32: + return CodedOutputStream.computeUInt32SizeNoTag((Integer) value); + case SFIXED32: + return CodedOutputStream.computeSFixed32SizeNoTag((Integer) value); + case SFIXED64: + return CodedOutputStream.computeSFixed64SizeNoTag((Long) value); + case SINT32: + return CodedOutputStream.computeSInt32SizeNoTag((Integer) value); + case SINT64: + return CodedOutputStream.computeSInt64SizeNoTag((Long) value); case MESSAGE: if (value instanceof LazyField) { @@ -872,36 +860,31 @@ final class FieldSet<FieldDescriptorType extends case ENUM: if (value instanceof Internal.EnumLite) { - return CodedOutputStream.computeEnumSizeNoTag( - ((Internal.EnumLite) value).getNumber()); + return CodedOutputStream.computeEnumSizeNoTag(((Internal.EnumLite) value).getNumber()); } else { return CodedOutputStream.computeEnumSizeNoTag((Integer) value); } } - throw new RuntimeException( - "There is no way to get here, but the compiler thinks otherwise."); + throw new RuntimeException("There is no way to get here, but the compiler thinks otherwise."); } - /** - * Compute the number of bytes needed to encode a particular field. - */ - public static int computeFieldSize(final FieldDescriptorLite<?> descriptor, - final Object value) { + /** 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 41749f6d..85e09bec 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<Float> +final class FloatArrayList extends AbstractProtobufList<Float> 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 ff670fd8..0034c58c 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<MessageType, BuilderType>, - BuilderType extends GeneratedMessageLite.Builder<MessageType, BuilderType>> - extends AbstractMessageLite<MessageType, BuilderType> { + MessageType extends GeneratedMessageLite<MessageType, BuilderType>, + BuilderType extends GeneratedMessageLite.Builder<MessageType, BuilderType>> + extends AbstractMessageLite<MessageType, BuilderType> { // 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. - * <p> - * 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. - * <p> - * NOTE: This implementation is liable to change in the future, and should not be relied on in + * + * <p>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. + * + * <p>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<MessageType, BuilderType>, - BuilderType extends GeneratedMessageLite.Builder<MessageType, BuilderType>> - BuilderType createBuilder() { + MessageType extends GeneratedMessageLite<MessageType, BuilderType>, + BuilderType extends GeneratedMessageLite.Builder<MessageType, BuilderType>> + BuilderType createBuilder() { return (BuilderType) dynamicMethod(MethodToInvoke.NEW_BUILDER); } protected final < - MessageType extends GeneratedMessageLite<MessageType, BuilderType>, - BuilderType extends GeneratedMessageLite.Builder<MessageType, BuilderType>> - BuilderType createBuilder(MessageType prototype) { + MessageType extends GeneratedMessageLite<MessageType, BuilderType>, + BuilderType extends GeneratedMessageLite.Builder<MessageType, BuilderType>> + 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...)}. - * <p> - * For use by generated code only. + * + * <p>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<MessageType, BuilderType>, - BuilderType extends Builder<MessageType, BuilderType>> - extends AbstractMessageLite.Builder<MessageType, BuilderType> { + MessageType extends GeneratedMessageLite<MessageType, BuilderType>, + BuilderType extends Builder<MessageType, BuilderType>> + extends AbstractMessageLite.Builder<MessageType, BuilderType> { 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<MessageType, BuilderType>, - BuilderType extends ExtendableBuilder<MessageType, BuilderType>> - extends MessageLiteOrBuilder { + MessageType extends ExtendableMessage<MessageType, BuilderType>, + BuilderType extends ExtendableBuilder<MessageType, BuilderType>> + extends MessageLiteOrBuilder { /** Check if a singular extension is present. */ - <Type> boolean hasExtension( - ExtensionLite<MessageType, Type> extension); + <Type> boolean hasExtension(ExtensionLite<MessageType, Type> extension); /** Get the number of elements in a repeated extension. */ - <Type> int getExtensionCount( - ExtensionLite<MessageType, List<Type>> extension); + <Type> int getExtensionCount(ExtensionLite<MessageType, List<Type>> extension); /** Get the value of an extension. */ <Type> Type getExtension(ExtensionLite<MessageType, Type> extension); /** Get one element of a repeated extension. */ - <Type> Type getExtension( - ExtensionLite<MessageType, List<Type>> extension, - int index); + <Type> Type getExtension(ExtensionLite<MessageType, List<Type>> extension, int index); } - /** - * Lite equivalent of {@link GeneratedMessage.ExtendableMessage}. - */ + /** Lite equivalent of {@link GeneratedMessage.ExtendableMessage}. */ public abstract static class ExtendableMessage< - MessageType extends ExtendableMessage<MessageType, BuilderType>, - BuilderType extends ExtendableBuilder<MessageType, BuilderType>> - extends GeneratedMessageLite<MessageType, BuilderType> - implements ExtendableMessageOrBuilder<MessageType, BuilderType> { + MessageType extends ExtendableMessage<MessageType, BuilderType>, + BuilderType extends ExtendableBuilder<MessageType, BuilderType>> + extends GeneratedMessageLite<MessageType, BuilderType> + implements ExtendableMessageOrBuilder<MessageType, BuilderType> { /** Represents the set of extensions on this message. For use by generated code only. */ protected FieldSet<ExtensionDescriptor> 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<MessageType, ?> extension = extensionRegistry.findLiteExtensionByNumber( - defaultInstance, fieldNumber); + GeneratedExtension<MessageType, ?> 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<ExtensionDescriptor> ensureExtensionsAreMutable() { @@ -847,22 +821,19 @@ public abstract class GeneratedMessageLite< return extensions; } - private void verifyExtensionContainingType( - final GeneratedExtension<MessageType, ?> extension) { - if (extension.getContainingTypeDefaultInstance() != - getDefaultInstanceForType()) { + private void verifyExtensionContainingType(final GeneratedExtension<MessageType, ?> 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 <Type> boolean hasExtension(final ExtensionLite<MessageType, Type> extension) { - GeneratedExtension<MessageType, Type> extensionLite = - checkIsLite(extension); + GeneratedExtension<MessageType, Type> extensionLite = checkIsLite(extension); verifyExtensionContainingType(extensionLite); return extensions.hasField(extensionLite.descriptor); @@ -872,8 +843,7 @@ public abstract class GeneratedMessageLite< @Override public final <Type> int getExtensionCount( final ExtensionLite<MessageType, List<Type>> extension) { - GeneratedExtension<MessageType, List<Type>> extensionLite = - checkIsLite(extension); + GeneratedExtension<MessageType, List<Type>> extensionLite = checkIsLite(extension); verifyExtensionContainingType(extensionLite); return extensions.getRepeatedFieldCount(extensionLite.descriptor); @@ -883,8 +853,7 @@ public abstract class GeneratedMessageLite< @Override @SuppressWarnings("unchecked") public final <Type> Type getExtension(final ExtensionLite<MessageType, Type> extension) { - GeneratedExtension<MessageType, Type> extensionLite = - checkIsLite(extension); + GeneratedExtension<MessageType, Type> 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> Type getExtension( final ExtensionLite<MessageType, List<Type>> extension, final int index) { - GeneratedExtension<MessageType, List<Type>> extensionLite = - checkIsLite(extension); + GeneratedExtension<MessageType, List<Type>> 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<Map.Entry<ExtensionDescriptor, Object>> iter = - extensions.iterator(); + private final Iterator<Map.Entry<ExtensionDescriptor, Object>> iter = extensions.iterator(); private Map.Entry<ExtensionDescriptor, Object> 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<MessageType, BuilderType>, - BuilderType extends ExtendableBuilder<MessageType, BuilderType>> + MessageType extends ExtendableMessage<MessageType, BuilderType>, + BuilderType extends ExtendableBuilder<MessageType, BuilderType>> extends Builder<MessageType, BuilderType> implements ExtendableMessageOrBuilder<MessageType, BuilderType> { protected ExtendableBuilder(MessageType defaultInstance) { @@ -1029,14 +993,12 @@ public abstract class GeneratedMessageLite< return super.buildPartial(); } - private void verifyExtensionContainingType( - final GeneratedExtension<MessageType, ?> extension) { - if (extension.getContainingTypeDefaultInstance() != - getDefaultInstanceForType()) { + private void verifyExtensionContainingType(final GeneratedExtension<MessageType, ?> 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 <Type> BuilderType setExtension( - final ExtensionLite<MessageType, Type> extension, - final Type value) { - GeneratedExtension<MessageType, Type> extensionLite = - checkIsLite(extension); + final ExtensionLite<MessageType, Type> extension, final Type value) { + GeneratedExtension<MessageType, Type> 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 <Type> BuilderType setExtension( - final ExtensionLite<MessageType, List<Type>> extension, - final int index, final Type value) { - GeneratedExtension<MessageType, List<Type>> extensionLite = - checkIsLite(extension); + final ExtensionLite<MessageType, List<Type>> extension, final int index, final Type value) { + GeneratedExtension<MessageType, List<Type>> extensionLite = checkIsLite(extension); verifyExtensionContainingType(extensionLite); copyOnWrite(); @@ -1099,10 +1057,8 @@ public abstract class GeneratedMessageLite< /** Append a value to a repeated extension. */ public final <Type> BuilderType addExtension( - final ExtensionLite<MessageType, List<Type>> extension, - final Type value) { - GeneratedExtension<MessageType, List<Type>> extensionLite = - checkIsLite(extension); + final ExtensionLite<MessageType, List<Type>> extension, final Type value) { + GeneratedExtension<MessageType, List<Type>> extensionLite = checkIsLite(extension); verifyExtensionContainingType(extensionLite); copyOnWrite(); @@ -1112,8 +1068,7 @@ public abstract class GeneratedMessageLite< } /** Clear an extension. */ - public final <Type> BuilderType clearExtension( - final ExtensionLite<MessageType, ?> extension) { + public final <Type> BuilderType clearExtension(final ExtensionLite<MessageType, ?> extension) { GeneratedExtension<MessageType, ?> extensionLite = checkIsLite(extension); verifyExtensionContainingType(extensionLite); @@ -1127,50 +1082,45 @@ public abstract class GeneratedMessageLite< /** For use by generated code only. */ public static <ContainingType extends MessageLite, Type> - GeneratedExtension<ContainingType, Type> - 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<ContainingType, Type> 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<ContainingType, Type>( 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 <ContainingType extends MessageLite, Type> - GeneratedExtension<ContainingType, Type> - 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<ContainingType, Type> 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<ContainingType, Type>( 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> { 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(). + * <p>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<ContainingType, Type> { + public static class GeneratedExtension<ContainingType extends MessageLite, Type> + extends ExtensionLite<ContainingType, Type> { /** * 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. + * <p>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<MessageType, BuilderType>, - BuilderType extends ExtendableBuilder<MessageType, BuilderType>, - T> - GeneratedExtension<MessageType, T> checkIsLite( - ExtensionLite<MessageType, T> extension) { + MessageType extends ExtendableMessage<MessageType, BuilderType>, + BuilderType extends ExtendableBuilder<MessageType, BuilderType>, + T> + GeneratedExtension<MessageType, T> checkIsLite(ExtensionLite<MessageType, T> 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. - * <p> - * For use by generated code only. + * + * <p>For use by generated code only. */ protected static final <T extends GeneratedMessageLite<T, ?>> boolean isInitialized( T message, boolean shouldMemoize) { @@ -1601,8 +1539,8 @@ public abstract class GeneratedMessageLite< /** * A {@link Parser} implementation that delegates to the default instance. - * <p> - * For use by generated code only. + * + * <p>For use by generated code only. */ protected static class DefaultInstanceBasedParser<T extends GeneratedMessageLite<T, ?>> extends AbstractParser<T> { @@ -1632,7 +1570,7 @@ public abstract class GeneratedMessageLite< // TODO(dweis): Should this verify that the last tag was 0? static <T extends GeneratedMessageLite<T, ?>> 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 extends GeneratedMessageLite<T, ?>> 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 extends GeneratedMessageLite<T, ?>> 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 extends GeneratedMessageLite<T, ?>> 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 extends GeneratedMessageLite<T, ?>> 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 extends GeneratedMessageLite<T, ?>> 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 extends GeneratedMessageLite<T, ?>> 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 extends GeneratedMessageLite<T, ?>> 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 extends GeneratedMessageLite<T, ?>> 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 extends GeneratedMessageLite<T, ?>> 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 extends MessageLite> T visitMessage(T mine, T other); <T> ProtobufList<T> visitList(ProtobufList<T> mine, ProtobufList<T> 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<ExtensionDescriptor> visitExtensions( FieldSet<ExtensionDescriptor> mine, FieldSet<ExtensionDescriptor> other); + UnknownFieldSetLite visitUnknownFields(UnknownFieldSetLite mine, UnknownFieldSetLite other); + <K, V> MapFieldLite<K, V> visitMap(MapFieldLite<K, V> mine, MapFieldLite<K, V> 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<ExtensionDescriptor> visitExtensions( - FieldSet<ExtensionDescriptor> mine, - FieldSet<ExtensionDescriptor> other) { + FieldSet<ExtensionDescriptor> mine, FieldSet<ExtensionDescriptor> 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<ExtensionDescriptor> visitExtensions( - FieldSet<ExtensionDescriptor> mine, - FieldSet<ExtensionDescriptor> other) { + FieldSet<ExtensionDescriptor> mine, FieldSet<ExtensionDescriptor> 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<ExtensionDescriptor> visitExtensions( - FieldSet<ExtensionDescriptor> mine, - FieldSet<ExtensionDescriptor> other) { + FieldSet<ExtensionDescriptor> mine, FieldSet<ExtensionDescriptor> 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 4993eea7..c9b12c42 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<Integer> +final class IntArrayList extends AbstractProtobufList<Integer> 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 878573d5..713ccb58 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> 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> 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. - * <p> - * The protocol compiler does not actually contain a UTF-8 decoder -- it - * just pushes UTF-8-encoded text around without touching it. The one place - * where this presents a problem is when generating Java string literals. - * Unicode characters in the string literal would normally need to be encoded - * using a Unicode escape sequence, which would require decoding them. - * To get around this, protoc instead embeds the UTF-8 bytes into the - * generated code and leaves it to the runtime library to decode them. - * <p> - * It gets worse, though. If protoc just generated a byte array, like: - * new byte[] {0x12, 0x34, 0x56, 0x78} - * Java actually generates *code* which allocates an array and then fills - * in each value. This is much less efficient than just embedding the bytes - * directly into the bytecode. To get around this, we need another - * work-around. String literals are embedded directly, so protoc actually - * generates a string literal corresponding to the bytes. The easiest way - * to do this is to use the ISO-8859-1 character set, which corresponds to - * the first 256 characters of the Unicode range. Protoc can then use - * good old CEscape to generate the string. - * <p> - * So we have a string literal which represents a set of bytes which - * represents another string. This function -- stringDefaultValue -- - * converts from the generated string to the string we actually want. The - * generated code calls this automatically. + * Helper called by generated code to construct default values for string fields. + * + * <p>The protocol compiler does not actually contain a UTF-8 decoder -- it just pushes + * UTF-8-encoded text around without touching it. The one place where this presents a problem is + * when generating Java string literals. Unicode characters in the string literal would normally + * need to be encoded using a Unicode escape sequence, which would require decoding them. To get + * around this, protoc instead embeds the UTF-8 bytes into the generated code and leaves it to the + * runtime library to decode them. + * + * <p>It gets worse, though. If protoc just generated a byte array, like: new byte[] {0x12, 0x34, + * 0x56, 0x78} Java actually generates *code* which allocates an array and then fills in each + * value. This is much less efficient than just embedding the bytes directly into the bytecode. To + * get around this, we need another work-around. String literals are embedded directly, so protoc + * actually generates a string literal corresponding to the bytes. The easiest way to do this is + * to use the ISO-8859-1 character set, which corresponds to the first 256 characters of the + * Unicode range. Protoc can then use good old CEscape to generate the string. + * + * <p>So we have a string literal which represents a set of bytes which represents another string. + * This function -- stringDefaultValue -- converts from the generated string to the string we + * actually want. The generated code calls this automatically. */ public static String stringDefaultValue(String bytes) { return new String(bytes.getBytes(ISO_8859_1), UTF_8); } /** - * Helper called by generated code to construct default values for bytes - * fields. - * <p> - * This is a lot like {@link #stringDefaultValue}, but for bytes fields. - * In this case we only need the second of the two hacks -- allowing us to - * embed raw bytes as a string literal with ISO-8859-1 encoding. + * Helper called by generated code to construct default values for bytes fields. + * + * <p>This is a lot like {@link #stringDefaultValue}, but for bytes fields. In this case we only + * need the second of the two hacks -- allowing us to embed raw bytes as a string literal with + * ISO-8859-1 encoding. */ public static ByteString bytesDefaultValue(String bytes) { return ByteString.copyFrom(bytes.getBytes(ISO_8859_1)); } /** - * Helper called by generated code to construct default values for bytes - * fields. - * <p> - * This is like {@link #bytesDefaultValue}, but returns a byte array. + * Helper called by generated code to construct default values for bytes fields. + * + * <p>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. - * <p> - * This is like {@link #bytesDefaultValue}, but returns a ByteBuffer. + * Helper called by generated code to construct default values for bytes fields. + * + * <p>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: - * <pre> {@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: + * + * <pre>{@code * Arrays.equals(byteString.toByteArray(), * new String(byteString.toByteArray(), "UTF-8").getBytes("UTF-8")) * }</pre> * - * <p>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 + * <p>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. * * <p>See the Unicode Standard,<br> * Table 3-6. <em>UTF-8 Bit Distribution</em>,<br> * Table 3-7. <em>Well Formed UTF-8 Byte Sequences</em>. * - * <p>As of 2011-02, this method simply returns the result of {@link - * ByteString#isValidUtf8()}. Calling that method directly is preferred. + * <p>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 extends EnumLite> { 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. - * <p> - * 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. + * + * <p>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<? extends EnumLite> 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<byte[]> a, List<byte[]> 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<byte[]> 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<ByteBuffer> a, List<ByteBuffer> b) { + /** Helper method for implementing {@link Message#equals(Object)} for bytes field. */ + public static boolean equalsByteBuffer(List<ByteBuffer> a, List<ByteBuffer> 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<ByteBuffer> 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<T>} around a {@code List<F>}. * - * Protobuf internal. Used in protobuf generated code only. + * <p>Protobuf internal. Used in protobuf generated code only. */ public static class ListAdapter<F, T> extends AbstractList<T> { - /** - * Convert individual elements of the List from F to T. - */ + /** Convert individual elements of the List from F to T. */ public interface Converter<F, T> { T convert(F from); } @@ -471,16 +417,12 @@ public final class Internal { } } - /** - * Wrap around a {@code Map<K, RealValue>} and provide a {@code Map<K, V>} - * interface. - */ + /** Wrap around a {@code Map<K, RealValue>} and provide a {@code Map<K, V>} interface. */ public static class MapAdapter<K, V, RealValue> extends AbstractMap<K, V> { - /** - * An interface used to convert between two types. - */ + /** An interface used to convert between two types. */ public interface Converter<A, B> { B doForward(A object); + A doBackward(B object); } @@ -503,8 +445,7 @@ public final class Internal { private final Map<K, RealValue> realMap; private final Converter<RealValue, V> valueConverter; - public MapAdapter(Map<K, RealValue> realMap, - Converter<RealValue, V> valueConverter) { + public MapAdapter(Map<K, RealValue> realMap, Converter<RealValue, V> valueConverter) { this.realMap = realMap; this.valueConverter = valueConverter; } @@ -535,6 +476,7 @@ public final class Internal { private class SetAdapter extends AbstractSet<Map.Entry<K, V>> { private final Set<Map.Entry<K, RealValue>> realSet; + public SetAdapter(Set<Map.Entry<K, RealValue>> realSet) { this.realSet = realSet; } @@ -553,8 +495,7 @@ public final class Internal { private class IteratorAdapter implements Iterator<Map.Entry<K, V>> { private final Iterator<Map.Entry<K, RealValue>> realIterator; - public IteratorAdapter( - Iterator<Map.Entry<K, RealValue>> realIterator) { + public IteratorAdapter(Iterator<Map.Entry<K, RealValue>> 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. - * <p> - * All implementations must support efficient random access. + * + * <p>All implementations must support efficient random access. */ public static interface ProtobufList<E> extends List<E>, 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<E> mutableCopyWithCapacity(int capacity); } @@ -634,24 +572,16 @@ public final class Internal { */ public static interface IntList extends ProtobufList<Integer> { - /** - * 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<Boolean> { - /** - * 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<Long> { - /** - * 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<Double> { - /** - * 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<Float> { - /** - * 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 510c6aac..22f31bbc 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 98e13ca1..891171d7 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()}. + * <p>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<K> implements Entry<K, Object> { private Entry<K, LazyField> 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 49ecfc0b..5651e131 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 + * <p>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 + * <p>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. + * + * <p>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. + * <p>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 + * <p>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. + * <p>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. * - * <p>LazyField is not thread-safe for write access. Synchronizations are needed - * under read/write situations. + * <p>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. * - * <p>LazyField is not thread-safe for write access. Synchronizations are needed - * under read/write situations. + * <p>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. * - * <p>LazyField is not thread-safe for write access. Synchronizations are needed - * under read/write situations. + * <p>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}. * - * <p>LazyField is not thread-safe for write access. Synchronizations are needed - * under read/write situations. + * <p>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. * - * <p>LazyField is not thread-safe for write access. Synchronizations are needed - * under read/write situations. + * <p>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 6cfc14a5..a2de6f9c 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. - * <p> - * <strong>Note that this implementation is not synchronized.</strong> - * If multiple threads access an <tt>ArrayList</tt> instance concurrently, - * and at least one of the threads modifies the list structurally, it - * <i>must</i> 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. - * <p> - * 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. + * + * <p><strong>Note that this implementation is not synchronized.</strong> If multiple threads access + * an <tt>ArrayList</tt> instance concurrently, and at least one of the threads modifies the list + * structurally, it <i>must</i> 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. + * + * <p>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<String> implements LazyStringList, RandomAccess { private static final LazyStringArrayList EMPTY_LIST = new LazyStringArrayList(); + static { EMPTY_LIST.makeImmutable(); } @@ -177,8 +174,8 @@ public class LazyStringArrayList extends AbstractProtobufList<String> 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<String> } } - private static class ByteArrayListView extends AbstractList<byte[]> - implements RandomAccess { + private static class ByteArrayListView extends AbstractList<byte[]> implements RandomAccess { private final LazyStringArrayList list; ByteArrayListView(LazyStringArrayList list) { @@ -368,8 +364,7 @@ public class LazyStringArrayList extends AbstractProtobufList<String> return new ByteArrayListView(this); } - private static class ByteStringListView extends AbstractList<ByteString> - implements RandomAccess { + private static class ByteStringListView extends AbstractList<ByteString> implements RandomAccess { private final LazyStringArrayList list; ByteStringListView(LazyStringArrayList list) { @@ -419,5 +414,4 @@ public class LazyStringArrayList extends AbstractProtobufList<String> } 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 3eeedca1..6b55022c 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<String>} 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<String>} 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 <tt>add</tt> operation - * is not supported by this list + * @throws UnsupportedOperationException if the <tt>add</tt> 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 <tt>add</tt> operation - * is not supported by this list + * @throws UnsupportedOperationException if the <tt>add</tt> 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 <tt>set</tt> operation - * is not supported by this list - * IndexOutOfBoundsException if the index is out of range - * ({@code index < 0 || index >= size()}) + * @throws UnsupportedOperationException if the <tt>set</tt> 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 <tt>set</tt> operation - * is not supported by this list - * IndexOutOfBoundsException if the index is out of range - * ({@code index < 0 || index >= size()}) + * @throws UnsupportedOperationException if the <tt>set</tt> 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 <tt>addAllByteString</tt> - * operation is not supported by this list + * @throws UnsupportedOperationException if the <tt>addAllByteString</tt> operation is not + * supported by this list */ boolean addAllByteString(Collection<? extends ByteString> 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 <tt>addAllByteArray</tt> - * operation is not supported by this list + * @throws UnsupportedOperationException if the <tt>addAllByteArray</tt> operation is not + * supported by this list */ boolean addAllByteArray(Collection<byte[]> 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<byte[]> 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 9a5056be..8cdab121 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<Long> +final class LongArrayList extends AbstractProtobufList<Long> 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 0849b821..01754522 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. + * <p>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. + * <p>Protobuf internal. Users shouldn't use this class. */ public final class MapEntry<K, V> extends AbstractMessage { @@ -61,15 +61,16 @@ public final class MapEntry<K, V> extends AbstractMessage { WireFormat.FieldType valueType) { super(keyType, defaultInstance.key, valueType, defaultInstance.value); this.descriptor = descriptor; - this.parser = new AbstractParser<MapEntry<K, V>>() { + this.parser = + new AbstractParser<MapEntry<K, V>>() { - @Override - public MapEntry<K, V> parsePartialFrom( - CodedInputStream input, ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - return new MapEntry<K, V>(Metadata.this, input, extensionRegistry); - } - }; + @Override + public MapEntry<K, V> parsePartialFrom( + CodedInputStream input, ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException { + return new MapEntry<K, V>(Metadata.this, input, extensionRegistry); + } + }; } } @@ -80,8 +81,10 @@ public final class MapEntry<K, V> 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<K, V>(descriptor, this, keyType, valueType); @@ -97,9 +100,7 @@ public final class MapEntry<K, V> extends AbstractMessage { /** Parsing constructor. */ private MapEntry( - Metadata<K, V> metadata, - CodedInputStream input, - ExtensionRegistryLite extensionRegistry) + Metadata<K, V> metadata, CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { try { this.metadata = metadata; @@ -114,17 +115,17 @@ public final class MapEntry<K, V> 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 <K, V> MapEntry<K, V> newDefaultInstance( Descriptor descriptor, - WireFormat.FieldType keyType, K defaultKey, - WireFormat.FieldType valueType, V defaultValue) { - return new MapEntry<K, V>( - descriptor, keyType, defaultKey, valueType, defaultValue); + WireFormat.FieldType keyType, + K defaultKey, + WireFormat.FieldType valueType, + V defaultValue) { + return new MapEntry<K, V>(descriptor, keyType, defaultKey, valueType, defaultValue); } public K getKey() { @@ -197,14 +198,17 @@ public final class MapEntry<K, V> 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<K, V> 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<K, V> extends AbstractMessage { return UnknownFieldSet.getDefaultInstance(); } - /** - * Builder to create {@link MapEntry} messages. - */ - public static class Builder<K, V> - extends AbstractMessage.Builder<Builder<K, V>> { + /** Builder to create {@link MapEntry} messages. */ + public static class Builder<K, V> extends AbstractMessage.Builder<Builder<K, V>> { private final Metadata<K, V> metadata; private K key; private V value; @@ -315,20 +313,21 @@ public final class MapEntry<K, V> 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<K, V> extends AbstractMessage { } @Override - public Builder<K, V> setRepeatedField(FieldDescriptor field, int index, - Object value) { - throw new RuntimeException( - "There is no repeated field in a map entry message."); + public Builder<K, V> setRepeatedField(FieldDescriptor field, int index, Object value) { + throw new RuntimeException("There is no repeated field in a map entry message."); } @Override public Builder<K, V> 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<K, V> 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<K, V> extends AbstractMessage { } return true; } - + /** Returns the metadata only for experimental runtime. */ final Metadata<K, V> 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 dcb5dfad..ca2a3c2a 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. + * <p>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. + * <p>Protobuf internal. Users shouldn't use. */ public class MapEntryLite<K, V> { @@ -52,8 +51,10 @@ public class MapEntryLite<K, V> { 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<K, V> { /** 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<K, V>(keyType, defaultKey, valueType, defaultValue); this.key = defaultKey; this.value = defaultValue; @@ -95,16 +95,13 @@ public class MapEntryLite<K, V> { /** * 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. + * <p>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 <K, V> MapEntryLite<K, V> newDefaultInstance( - WireFormat.FieldType keyType, K defaultKey, - WireFormat.FieldType valueType, V defaultValue) { - return new MapEntryLite<K, V>( - keyType, defaultKey, valueType, defaultValue); + WireFormat.FieldType keyType, K defaultKey, WireFormat.FieldType valueType, V defaultValue) { + return new MapEntryLite<K, V>(keyType, defaultKey, valueType, defaultValue); } static <K, V> void writeTo(CodedOutputStream output, Metadata<K, V> metadata, K key, V value) @@ -120,8 +117,11 @@ public class MapEntryLite<K, V> { @SuppressWarnings("unchecked") static <T> 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<K, V> { } /** - * 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<K, V> { } /** - * 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<K, V> { } /** - * 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<K, V> parseEntry(ByteString bytes, ExtensionRegistryLite extensionRegistry) throws IOException { @@ -170,7 +170,7 @@ public class MapEntryLite<K, V> { static <K, V> Map.Entry<K, V> parseEntry( CodedInputStream input, Metadata<K, V> metadata, ExtensionRegistryLite extensionRegistry) - throws IOException{ + throws IOException { K key = metadata.defaultKey; V value = metadata.defaultValue; while (true) { @@ -192,12 +192,12 @@ public class MapEntryLite<K, V> { } /** - * 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<K, V> 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 ad8ceb02..f4877360 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. + * <p>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. + * <p>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. + * <p>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<K, V> 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. + * <ul> + * <li>MAP: Data is stored in mapData. + * <li>LIST: Data is stored in listData. + * <li>BOTH: mapData and listData have the same data. + * </ul> * - * When the map field is accessed (through generated API or reflection API), - * it will shift between these 3 modes: + * <p>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 + * <pre> + * <b>getMap() getList() getMutableMap() getMutableList()</b> + * <b>MAP</b> MAP BOTH MAP LIST + * <b>LIST</b> BOTH LIST MAP LIST + * <b>BOTH</b> BOTH BOTH MAP LIST + * </pre> * - * As the map field changes its mode, the list/map reference returned in a - * previous method call may be invalidated. + * <p>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<K, V> implements MutabilityOracle { // Convert between a map entry Message and a key-value pair. private static interface Converter<K, V> { Message convertKeyAndValueToMessage(K key, V value); + void convertMessageToKeyAndValue(Message message, Map<K, V> map); Message getMessageDefaultInstance(); @@ -92,6 +99,7 @@ public class MapField<K, V> implements MutabilityOracle { private static class ImmutableMessageConverter<K, V> implements Converter<K, V> { private final MapEntry<K, V> defaultEntry; + public ImmutableMessageConverter(MapEntry<K, V> defaultEntry) { this.defaultEntry = defaultEntry; } @@ -117,10 +125,7 @@ public class MapField<K, V> implements MutabilityOracle { private final Converter<K, V> converter; - private MapField( - Converter<K, V> converter, - StorageMode mode, - Map<K, V> mapData) { + private MapField(Converter<K, V> converter, StorageMode mode, Map<K, V> mapData) { this.converter = converter; this.isMutable = true; this.mode = mode; @@ -128,26 +133,20 @@ public class MapField<K, V> implements MutabilityOracle { this.listData = null; } - private MapField( - MapEntry<K, V> defaultEntry, - StorageMode mode, - Map<K, V> mapData) { + private MapField(MapEntry<K, V> defaultEntry, StorageMode mode, Map<K, V> mapData) { this(new ImmutableMessageConverter<K, V>(defaultEntry), mode, mapData); } /** Returns an immutable empty MapField. */ - public static <K, V> MapField<K, V> emptyMapField( - MapEntry<K, V> defaultEntry) { - return new MapField<K, V>( - defaultEntry, StorageMode.MAP, Collections.<K, V>emptyMap()); + public static <K, V> MapField<K, V> emptyMapField(MapEntry<K, V> defaultEntry) { + return new MapField<K, V>(defaultEntry, StorageMode.MAP, Collections.<K, V>emptyMap()); } /** Creates a new mutable empty MapField. */ public static <K, V> MapField<K, V> newMapField(MapEntry<K, V> defaultEntry) { - return new MapField<K, V>( - defaultEntry, StorageMode.MAP, new LinkedHashMap<K, V>()); + return new MapField<K, V>(defaultEntry, StorageMode.MAP, new LinkedHashMap<K, V>()); } @@ -163,9 +162,7 @@ public class MapField<K, V> implements MutabilityOracle { private List<Message> convertMapToList(MutatabilityAwareMap<K, V> mapData) { List<Message> listData = new ArrayList<Message>(); for (Map.Entry<K, V> 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<K, V> implements MutabilityOracle { /** Returns a deep copy of this MapField. */ public MapField<K, V> copy() { - return new MapField<K, V>( - converter, StorageMode.MAP, MapFieldLite.copy(getMap())); + return new MapField<K, V>(converter, StorageMode.MAP, MapFieldLite.copy(getMap())); } /** Gets the content of this MapField as a read-only List. */ @@ -258,25 +254,20 @@ public class MapField<K, V> 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<K, V> implements MutabilityOracle { } } - /** - * An internal map that checks for mutability before delegating. - */ + /** An internal map that checks for mutability before delegating. */ private static class MutatabilityAwareMap<K, V> implements Map<K, V> { private final MutabilityOracle mutabilityOracle; private final Map<K, V> delegate; @@ -388,9 +377,7 @@ public class MapField<K, V> 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<E> implements Collection<E> { private final MutabilityOracle mutabilityOracle; private final Collection<E> delegate; @@ -487,9 +474,7 @@ public class MapField<K, V> implements MutabilityOracle { } } - /** - * An internal set that checks for mutability before delegating. - */ + /** An internal set that checks for mutability before delegating. */ private static class MutatabilityAwareSet<E> implements Set<E> { private final MutabilityOracle mutabilityOracle; private final Set<E> delegate; @@ -586,9 +571,7 @@ public class MapField<K, V> implements MutabilityOracle { } } - /** - * An internal iterator that checks for mutability before delegating. - */ + /** An internal iterator that checks for mutability before delegating. */ private static class MutatabilityAwareIterator<E> implements Iterator<E> { private final MutabilityOracle mutabilityOracle; private final Iterator<E> 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 a8b3dd88..7467487b 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. + * <p>This class is a protobuf implementation detail. Users shouldn't use this class directly. */ public final class MapFieldLite<K, V> extends LinkedHashMap<K, V> { @@ -60,6 +59,7 @@ public final class MapFieldLite<K, V> extends LinkedHashMap<K, V> { @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<K, V> extends LinkedHashMap<K, V> { } @SuppressWarnings({"unchecked", "cast"}) - @Override public Set<Map.Entry<K, V>> entrySet() { + @Override + public Set<Map.Entry<K, V>> entrySet() { return isEmpty() ? Collections.<Map.Entry<K, V>>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<K, V> extends LinkedHashMap<K, V> { return put(entry.getKey(), entry.getValue()); } - @Override public void putAll(Map<? extends K, ? extends V> m) { + @Override + public void putAll(Map<? extends K, ? extends V> 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<K, V> extends LinkedHashMap<K, V> { } /** - * 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 <K, V> boolean equals(Map<K, V> a, Map<K, V> b) { if (a == b) { @@ -147,9 +151,7 @@ public final class MapFieldLite<K, V> extends LinkedHashMap<K, V> { 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<K, V> extends LinkedHashMap<K, V> { } /** - * 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 <K, V> int calculateHashCodeForMap(Map<K, V> a) { int result = 0; for (Map.Entry<K, V> 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<K, V> extends LinkedHashMap<K, V> { } /** - * 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 <K, V> Map<K, V> copy(Map<K, V> map) { @@ -214,16 +215,14 @@ public final class MapFieldLite<K, V> extends LinkedHashMap<K, V> { } /** - * 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 0770d417..52b4a208 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. - * <p> - * 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. + * + * <p>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:<br> - * * For singular primitive fields, if the field is set in {@code other}, - * then {@code other}'s value overwrites the value in this message.<br> - * * 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.<br> - * * For repeated fields, the elements in {@code other} are concatenated - * with the elements in this message.<br> - * * 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. + * <p>Merging occurs as follows. For each field:<br> + * * For singular primitive fields, if the field is set in {@code other}, then {@code other}'s + * value overwrites the value in this message.<br> + * * 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.<br> + * * For repeated fields, the elements in {@code other} are concatenated with the elements in + * this message.<br> + * * 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++. + * <p>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. - * <p> - * 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. - * <p> - * 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. - * <p> - * NOTE: implementations that do not support nested builders will throw - * <code>UnsupportedOperationException</code>. + * + * <p>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. + * + * <p>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. + * + * <p>NOTE: implementations that do not support nested builders will throw <code> + * UnsupportedOperationException</code>. */ Builder getFieldBuilder(Descriptors.FieldDescriptor field); /** * Get a nested builder instance for the given repeated field instance. - * <p> - * 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. - * <p> - * 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. - * <p> - * NOTE: implementations that do not support nested builders will throw - * <code>UnsupportedOperationException</code>. + * + * <p>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. + * + * <p>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. + * + * <p>NOTE: implementations that do not support nested builders will throw <code> + * UnsupportedOperationException</code>. */ - 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 88f531df..7d2ef33a 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. * - * <p>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: + * <p>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: + * * <pre> * option optimize_for = LITE_RUNTIME; * </pre> * - * <p>This is particularly useful on resource-constrained systems where the - * full protocol buffers runtime library is too big. + * <p>This is particularly useful on resource-constrained systems where the full protocol buffers + * runtime library is too big. * - * <p>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. + * <p>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<? extends MessageLite> 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. - * <p> - * 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. + * + * <p>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. + * + * <p>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: * - * <p>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: * <ul> - * <li>Call {@link #isInitialized()} to verify that all required fields - * are set before building. - * <li>Use {@code buildPartial()} to build, which ignores missing - * required fields. + * <li>Call {@link #isInitialized()} to verify that all required fields are set before + * building. + * <li>Use {@code buildPartial()} to build, which ignores missing required fields. * </ul> * - * <p>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. + * <p>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 <i>entire</i> 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. - * <p> - * 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 <i>entire</i> 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. + * + * <p>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:<br> - * * For singular primitive fields, if the field is set in {@code other}, - * then {@code other}'s value overwrites the value in this message.<br> - * * 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.<br> - * * 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. + * <p>Merging occurs as follows. For each field:<br> + * * For singular primitive fields, if the field is set in {@code other}, then {@code other}'s + * value overwrites the value in this message.<br> + * * 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.<br> + * * 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++. + * <p>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 818386ce..7a5ef3ed 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. * * <p>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 5e7d7821..0254df99 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<String> 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. - * <br> - * 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. <br> + * 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<Descriptors.FieldDescriptor, Object> 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 69ad7ddf..9fc72bd9 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<FieldDescriptor, Object>(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<Descriptors.FieldDescriptor, Object> entry : - fields.entrySet()) { + for (final Map.Entry<Descriptors.FieldDescriptor, Object> 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<FieldDescriptor, Object> fields) { + static int getSerializedSize(Message message, Map<FieldDescriptor, Object> fields) { int size = 0; final boolean isMessageSet = message.getDescriptorForType().getOptions().getMessageSetWireFormat(); - for (final Map.Entry<Descriptors.FieldDescriptor, Object> entry : - fields.entrySet()) { + for (final Map.Entry<Descriptors.FieldDescriptor, Object> 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<Message>) entry.getValue()) { + for (final Message element : (List<Message>) 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<String> results) { - for (final Descriptors.FieldDescriptor field : - message.getDescriptorForType().getFields()) { + private static void findMissingFields( + final MessageOrBuilder message, final String prefix, final List<String> 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<String> findMissingFields( - final MessageOrBuilder message) { + static List<String> findMissingFields(final MessageOrBuilder message) { final List<String> results = new ArrayList<String>(); 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 82b723c9..7c2f1575 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 76594809..64de6b1b 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 e07c6895..259b5a68 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. + * <p>The implementation should be stateless and thread-safe. * * <p>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<MessageType> { /** * Parses a message of {@code MessageType} from the input. * - * <p>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. + * <p>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<MessageType> { 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 <i>entire</i> 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. - * <p> - * 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 <i>entire</i> + * 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. + * + * <p>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 81255ec2..98341613 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<E> extends AbstractProtobufList<E> { private static final ProtobufArrayList<Object> EMPTY_LIST = new ProtobufArrayList<Object>(); + static { EMPTY_LIST.makeImmutable(); } - + @SuppressWarnings("unchecked") // Guaranteed safe by runtime. public static <E> ProtobufArrayList<E> emptyList() { return (ProtobufArrayList<E>) EMPTY_LIST; } - + private final List<E> list; ProtobufArrayList() { this(new ArrayList<E>(DEFAULT_CAPACITY)); } - + private ProtobufArrayList(List<E> list) { this.list = list; } @@ -69,7 +67,7 @@ final class ProtobufArrayList<E> extends AbstractProtobufList<E> { newList.addAll(list); return new ProtobufArrayList<E>(newList); } - + @Override public void add(int index, E element) { ensureIsMutable(); @@ -81,7 +79,7 @@ final class ProtobufArrayList<E> extends AbstractProtobufList<E> { public E get(int index) { return list.get(index); } - + @Override public E remove(int index) { ensureIsMutable(); @@ -89,7 +87,7 @@ final class ProtobufArrayList<E> extends AbstractProtobufList<E> { 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 a596d301..5d6f5ac4 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 d553b41e..5df3dbdb 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<String>} 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<String>} 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<String> { /** Returns a view of the data as a list of ByteStrings. */ List<ByteString> 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 b593b566..f3b09fba 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). - * <br> - * 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. - * <br> - * 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). <br> + * 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. <br> + * 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 <MType> the type of message for the field * @param <BType> the type of builder for the field * @param <IType> the common interface for the message and the builder - * * @author jonp@google.com (Jon Perlow) */ -public class RepeatedFieldBuilder - <MType extends GeneratedMessage, - BType extends GeneratedMessage.Builder, - IType extends MessageOrBuilder> +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<MType, BType, IType> - externalMessageOrBuilderList; + private MessageOrBuilderExternalList<MType, BType, IType> 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<SingleFieldBuilder<MType, BType, IType>>( - messages.size()); + this.builders = new ArrayList<SingleFieldBuilder<MType, BType, IType>>(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<MType, BType, IType> builder = builders.get(index); if (builder == null) { MType message = messages.get(index); - builder = new SingleFieldBuilder<MType, BType, IType>( - message, this, isClean); + builder = new SingleFieldBuilder<MType, BType, IType>(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<MType, BType, IType> setMessage( - int index, MType message) { + public RepeatedFieldBuilder<MType, BType, IType> setMessage(int index, MType message) { checkNotNull(message); ensureMutableMessageList(); messages.set(index, message); if (builders != null) { - SingleFieldBuilder<MType, BType, IType> entry = - builders.set(index, null); + SingleFieldBuilder<MType, BType, IType> 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<MType, BType, IType> addMessage( - MType message) { + public RepeatedFieldBuilder<MType, BType, IType> 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<MType, BType, IType> addMessage( - int index, MType message) { + public RepeatedFieldBuilder<MType, BType, IType> 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<MType> collection = (Collection<MType>) values; + @SuppressWarnings("unchecked") + final Collection<MType> collection = (Collection<MType>) values; if (collection.size() == 0) { return this; } @@ -375,8 +356,7 @@ public class RepeatedFieldBuilder ensureMutableMessageList(); if (size >= 0 && messages instanceof ArrayList) { - ((ArrayList<MType>) messages) - .ensureCapacity(messages.size() + size); + ((ArrayList<MType>) messages).ensureCapacity(messages.size() + size); } for (MType value : values) { @@ -398,8 +378,7 @@ public class RepeatedFieldBuilder ensureMutableMessageList(); ensureBuilders(); SingleFieldBuilder<MType, BType, IType> builder = - new SingleFieldBuilder<MType, BType, IType>( - message, this, isClean); + new SingleFieldBuilder<MType, BType, IType>(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<MType, BType, IType> builder = - new SingleFieldBuilder<MType, BType, IType>( - message, this, isClean); + new SingleFieldBuilder<MType, BType, IType>(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<MType, BType, IType> entry = - builders.remove(index); + SingleFieldBuilder<MType, BType, IType> 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<MType, BType, IType> entry : - builders) { + for (SingleFieldBuilder<MType, BType, IType> 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<MType> getMessageList() { if (externalMessageList == null) { - externalMessageList = - new MessageExternalList<MType, BType, IType>(this); + externalMessageList = new MessageExternalList<MType, BType, IType>(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<BType> getBuilderList() { if (externalBuilderList == null) { - externalBuilderList = - new BuilderExternalList<MType, BType, IType>(this); + externalBuilderList = new BuilderExternalList<MType, BType, IType>(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<IType> getMessageOrBuilderList() { if (externalMessageOrBuilderList == null) { - externalMessageOrBuilderList = - new MessageOrBuilderExternalList<MType, BType, IType>(this); + externalMessageOrBuilderList = new MessageOrBuilderExternalList<MType, BType, IType>(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 <IType> 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<MType> implements List<MType> { RepeatedFieldBuilder<MType, BType, IType> builder; - MessageExternalList( - RepeatedFieldBuilder<MType, BType, IType> builder) { + MessageExternalList(RepeatedFieldBuilder<MType, BType, IType> builder) { this.builder = builder; } @@ -638,15 +605,14 @@ public class RepeatedFieldBuilder * @param <IType> 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<BType> implements List<BType> { RepeatedFieldBuilder<MType, BType, IType> builder; - BuilderExternalList( - RepeatedFieldBuilder<MType, BType, IType> builder) { + BuilderExternalList(RepeatedFieldBuilder<MType, BType, IType> builder) { this.builder = builder; } @@ -673,15 +639,14 @@ public class RepeatedFieldBuilder * @param <IType> 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<IType> implements List<IType> { RepeatedFieldBuilder<MType, BType, IType> builder; - MessageOrBuilderExternalList( - RepeatedFieldBuilder<MType, BType, IType> builder) { + MessageOrBuilderExternalList(RepeatedFieldBuilder<MType, BType, IType> 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 30c991d4..fb1667c4 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). - * <br> - * 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. - * <br> - * 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). <br> + * 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. <br> + * 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 <MType> the type of message for the field * @param <BType> the type of builder for the field * @param <IType> the common interface for the message and the builder - * * @author jonp@google.com (Jon Perlow) */ -public class RepeatedFieldBuilderV3 - <MType extends AbstractMessage, - BType extends AbstractMessage.Builder, - IType extends MessageOrBuilder> +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<MType, BType, IType> - externalMessageOrBuilderList; + private MessageOrBuilderExternalList<MType, BType, IType> 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<SingleFieldBuilderV3<MType, BType, IType>>( - messages.size()); + this.builders = new ArrayList<SingleFieldBuilderV3<MType, BType, IType>>(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<MType, BType, IType> builder = builders.get(index); if (builder == null) { MType message = messages.get(index); - builder = new SingleFieldBuilderV3<MType, BType, IType>( - message, this, isClean); + builder = new SingleFieldBuilderV3<MType, BType, IType>(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<MType, BType, IType> setMessage( - int index, MType message) { + public RepeatedFieldBuilderV3<MType, BType, IType> setMessage(int index, MType message) { checkNotNull(message); ensureMutableMessageList(); messages.set(index, message); if (builders != null) { - SingleFieldBuilderV3<MType, BType, IType> entry = - builders.set(index, null); + SingleFieldBuilderV3<MType, BType, IType> 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<MType, BType, IType> addMessage( - MType message) { + public RepeatedFieldBuilderV3<MType, BType, IType> 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<MType, BType, IType> addMessage( - int index, MType message) { + public RepeatedFieldBuilderV3<MType, BType, IType> 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<MType> collection = (Collection<MType>) values; + @SuppressWarnings("unchecked") + final Collection<MType> collection = (Collection<MType>) values; if (collection.size() == 0) { return this; } @@ -375,8 +356,7 @@ public class RepeatedFieldBuilderV3 ensureMutableMessageList(); if (size >= 0 && messages instanceof ArrayList) { - ((ArrayList<MType>) messages) - .ensureCapacity(messages.size() + size); + ((ArrayList<MType>) messages).ensureCapacity(messages.size() + size); } for (MType value : values) { @@ -398,8 +378,7 @@ public class RepeatedFieldBuilderV3 ensureMutableMessageList(); ensureBuilders(); SingleFieldBuilderV3<MType, BType, IType> builder = - new SingleFieldBuilderV3<MType, BType, IType>( - message, this, isClean); + new SingleFieldBuilderV3<MType, BType, IType>(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<MType, BType, IType> builder = - new SingleFieldBuilderV3<MType, BType, IType>( - message, this, isClean); + new SingleFieldBuilderV3<MType, BType, IType>(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<MType, BType, IType> entry = - builders.remove(index); + SingleFieldBuilderV3<MType, BType, IType> 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<MType, BType, IType> entry : - builders) { + for (SingleFieldBuilderV3<MType, BType, IType> 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<MType> getMessageList() { if (externalMessageList == null) { - externalMessageList = - new MessageExternalList<MType, BType, IType>(this); + externalMessageList = new MessageExternalList<MType, BType, IType>(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<BType> getBuilderList() { if (externalBuilderList == null) { - externalBuilderList = - new BuilderExternalList<MType, BType, IType>(this); + externalBuilderList = new BuilderExternalList<MType, BType, IType>(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<IType> getMessageOrBuilderList() { if (externalMessageOrBuilderList == null) { - externalMessageOrBuilderList = - new MessageOrBuilderExternalList<MType, BType, IType>(this); + externalMessageOrBuilderList = new MessageOrBuilderExternalList<MType, BType, IType>(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 <IType> 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<MType> implements List<MType> { RepeatedFieldBuilderV3<MType, BType, IType> builder; - MessageExternalList( - RepeatedFieldBuilderV3<MType, BType, IType> builder) { + MessageExternalList(RepeatedFieldBuilderV3<MType, BType, IType> builder) { this.builder = builder; } @@ -638,15 +605,14 @@ public class RepeatedFieldBuilderV3 * @param <IType> 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<BType> implements List<BType> { RepeatedFieldBuilderV3<MType, BType, IType> builder; - BuilderExternalList( - RepeatedFieldBuilderV3<MType, BType, IType> builder) { + BuilderExternalList(RepeatedFieldBuilderV3<MType, BType, IType> builder) { this.builder = builder; } @@ -673,15 +639,14 @@ public class RepeatedFieldBuilderV3 * @param <IType> 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<IType> implements List<IType> { RepeatedFieldBuilderV3<MType, BType, IType> builder; - MessageOrBuilderExternalList( - RepeatedFieldBuilderV3<MType, BType, IType> builder) { + MessageOrBuilderExternalList(RepeatedFieldBuilderV3<MType, BType, IType> 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 6fa555df..154fd5da 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}. * * <p>Most of the operation here is inspired by the now-famous paper <a * href="https://web.archive.org/web/20060202015456/http://www.cs.ubc.ca/local/reading/proceedings/spe91-95/spe/vol25/issue12/spe986.pdf"> - * BAP95 </a> Ropes: an Alternative to Strings hans-j. boehm, russ atkinson and - * michael plass + * BAP95 </a> Ropes: an Alternative to Strings hans-j. boehm, russ atkinson and michael plass * - * <p>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}. + * <p>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}. * - * <p>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,... + * <p>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. * - * <p>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. + * <p>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. * * <p>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. * - * <p>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. + * <p>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. * - * <p>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}. + * <p>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. * - * <p>One surprising aspect of the algorithm is the result of balancing is not - * necessarily balanced, though it is nearly balanced. For details, see - * BAP95. + * <p>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. * - * <p>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 + * <p>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. * - * <p>This iterator is used to implement - * {@link RopeByteString#equalsFragments(ByteString)}. + * <p>This iterator is used to implement {@link RopeByteString#equalsFragments(ByteString)}. */ private static class PieceIterator implements Iterator<LeafByteString> { - private final Stack<RopeByteString> breadCrumbs = - new Stack<RopeByteString>(); + private final Stack<RopeByteString> breadCrumbs = new Stack<RopeByteString>(); 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. - * <p> - * This method assumes that all error checking has already happened. - * <p> - * 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. + * + * <p>This method assumes that all error checking has already happened. + * + * <p>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 10752968..51a34b63 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. * - * <p>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. + * <p>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 f272f4ad..13b5ec16 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; /** - * <p>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: * * <pre> * RpcChannel channel = rpcImpl.newChannel("remotehost.example.com:1234"); @@ -44,28 +43,26 @@ package com.google.protobuf; * service.myMethod(controller, request, callback); * </pre> * - * <p>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. + * <p>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<Message> done); + void callMethod( + Descriptors.MethodDescriptor method, + RpcController controller, + Message request, + Message responsePrototype, + RpcCallback<Message> 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 a92dd7be..073f27a2 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; /** - * <p>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. * - * <p>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. + * <p>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. * - * <p>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). + * <p>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. * - * <p>{@code notifyOnCancel()} must be called no more than once per request. - * It must be called on the server side only. + * <p>{@code notifyOnCancel()} must be called no more than once per request. It must be called on + * the server side only. */ void notifyOnCancel(RpcCallback<Object> 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 f7d555ae..7bd056a5 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<Message>} and convert it to an - * {@code RpcCallback} accepting a specific message type. This is always - * type-safe (parameter type contravariance). + * Take an {@code RpcCallback<Message>} and convert it to an {@code RpcCallback} accepting a + * specific message type. This is always type-safe (parameter type contravariance). */ @SuppressWarnings("unchecked") - public static <Type extends Message> RpcCallback<Type> - specializeCallback(final RpcCallback<Message> originalCallback) { - return (RpcCallback<Type>)originalCallback; + public static <Type extends Message> RpcCallback<Type> specializeCallback( + final RpcCallback<Message> originalCallback) { + return (RpcCallback<Type>) 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<Message>}. 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<Message>}. 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 <Type extends Message> - RpcCallback<Message> generalizeCallback( + public static <Type extends Message> RpcCallback<Message> generalizeCallback( final RpcCallback<Type> originalCallback, final Class<Type> 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 extends Message> 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 <ParameterType> - RpcCallback<ParameterType> newOneTimeCallback( + public static <ParameterType> RpcCallback<ParameterType> newOneTimeCallback( final RpcCallback<ParameterType> originalCallback) { return new RpcCallback<ParameterType>() { 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 ba7b033e..d45cdaec 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). * - * <p>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. + * <p>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(); /** - * <p>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. * * <p>Preconditions: + * * <ul> * <li>{@code method.getService() == getDescriptorForType()} - * <li>{@code request} is of the exact same class as the object returned by - * {@code getRequestPrototype(method)}. - * <li>{@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. + * <li>{@code request} is of the exact same class as the object returned by {@code + * getRequestPrototype(method)}. + * <li>{@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. * </ul> * * <p>Postconditions: + * * <ul> - * <li>{@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. - * <li>The parameter to {@code done} is the response. It must be of the - * exact same type as would be returned by - * {@code getResponsePrototype(method)}. - * <li>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}. + * <li>{@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. + * <li>The parameter to {@code done} is the response. It must be of the exact same type as would + * be returned by {@code getResponsePrototype(method)}. + * <li>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}. * </ul> */ - void callMethod(Descriptors.MethodDescriptor method, - RpcController controller, - Message request, - RpcCallback<Message> done); + void callMethod( + Descriptors.MethodDescriptor method, + RpcController controller, + Message request, + RpcCallback<Message> done); /** - * <p>{@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()}. * * <p>Example: + * * <pre> * 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 1f5ec8a2..acdc1de1 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. - * <br> - * 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. + * + * <p>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. * <br> - * 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 <MType> the type of message for the field * @param <BType> the type of builder for the field * @param <IType> the common interface for the message and the builder - * * @author jonp@google.com (Jon Perlow) */ -public class SingleFieldBuilder - <MType extends GeneratedMessage, - BType extends GeneratedMessage.Builder, - IType extends MessageOrBuilder> +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<MType, BType, IType> setMessage( - MType message) { + public SingleFieldBuilder<MType, BType, IType> 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<MType, BType, IType> mergeFrom( - MType value) { + public SingleFieldBuilder<MType, BType, IType> mergeFrom(MType value) { if (builder == null && message == message.getDefaultInstanceForType()) { message = value; } else { @@ -201,9 +189,11 @@ public class SingleFieldBuilder */ @SuppressWarnings("unchecked") public SingleFieldBuilder<MType, BType, IType> 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 8ab0f26d..78a4a216 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. - * <br> - * 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. + * + * <p>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. * <br> - * 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 <MType> the type of message for the field * @param <BType> the type of builder for the field * @param <IType> the common interface for the message and the builder - * * @author jonp@google.com (Jon Perlow) */ -public class SingleFieldBuilderV3 - <MType extends AbstractMessage, - BType extends AbstractMessage.Builder, - IType extends MessageOrBuilder> +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<MType, BType, IType> setMessage( - MType message) { + public SingleFieldBuilderV3<MType, BType, IType> 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<MType, BType, IType> mergeFrom( - MType value) { + public SingleFieldBuilderV3<MType, BType, IType> mergeFrom(MType value) { if (builder == null && message == message.getDefaultInstanceForType()) { message = value; } else { @@ -201,9 +189,11 @@ public class SingleFieldBuilderV3 */ @SuppressWarnings("unchecked") public SingleFieldBuilderV3<MType, BType, IType> 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 279edc4d..6bd65d6f 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: * - * <pre> {@code + * <pre>{@code * for (int i = 0; i < fieldMap.getNumArrayEntries(); i++) { * process(fieldMap.getArrayEntryAt(i)); * } @@ -60,24 +59,21 @@ import java.util.TreeMap; * } * }</pre> * - * 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. - * <p> - * 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. - * <p> - * The running time for all other operations is similar to that of - * {@code TreeMap}. - * <p> - * 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. + * + * <p>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. + * + * <p>The running time for all other operations is similar to that of {@code TreeMap}. + * + * <p>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<K extends Comparable<K>, V> extends AbstractMap<K, V> { /** - * 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 <FieldDescriptorType extends - FieldSet.FieldDescriptorLite<FieldDescriptorType>> + static <FieldDescriptorType extends FieldSet.FieldDescriptorLite<FieldDescriptorType>> SmallSortedMap<FieldDescriptorType, Object> newFieldMap(int arraySize) { return new SmallSortedMap<FieldDescriptorType, Object>(arraySize) { @Override @@ -103,15 +98,13 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> { public void makeImmutable() { if (!isImmutable()) { for (int i = 0; i < getNumArrayEntries(); i++) { - final Map.Entry<FieldDescriptorType, Object> entry = - getArrayEntryAt(i); + final Map.Entry<FieldDescriptorType, Object> entry = getArrayEntryAt(i); if (entry.getKey().isRepeated()) { final List value = (List) entry.getValue(); entry.setValue(Collections.unmodifiableList(value)); } } - for (Map.Entry<FieldDescriptorType, Object> entry : - getOverflowEntries()) { + for (Map.Entry<FieldDescriptorType, Object> entry : getOverflowEntries()) { if (entry.getKey().isRepeated()) { final List value = (List) entry.getValue(); entry.setValue(Collections.unmodifiableList(value)); @@ -126,11 +119,10 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> { /** * 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 <K extends Comparable<K>, V> SmallSortedMap<K, V> newInstanceForTest( - int arraySize) { + static <K extends Comparable<K>, V> SmallSortedMap<K, V> newInstanceForTest(int arraySize) { return new SmallSortedMap<K, V>(arraySize); } @@ -146,9 +138,8 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> { 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<K extends Comparable<K>, V> extends AbstractMap<K, V> { // 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.<K, V>emptyMap() : - Collections.unmodifiableMap(overflowEntries); + overflowEntries = + overflowEntries.isEmpty() + ? Collections.<K, V>emptyMap() + : Collections.unmodifiableMap(overflowEntries); isImmutable = true; } } @@ -192,9 +184,9 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> { /** @return An iterable over the overflow entries. */ public Iterable<Map.Entry<K, V>> getOverflowEntries() { - return overflowEntries.isEmpty() ? - EmptySet.<Map.Entry<K, V>>iterable() : - overflowEntries.entrySet(); + return overflowEntries.isEmpty() + ? EmptySet.<Map.Entry<K, V>>iterable() + : overflowEntries.entrySet(); } @@ -204,10 +196,9 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> { } /** - * 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} + * <p>{@inheritDoc} */ @Override public boolean containsKey(Object o) { @@ -217,10 +208,9 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> { } /** - * 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} + * <p>{@inheritDoc} */ @Override public V get(Object o) { @@ -251,8 +241,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> { 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<K extends Comparable<K>, V> extends AbstractMap<K, V> { } /** - * 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} + * <p>{@inheritDoc} */ @Override public V remove(Object o) { @@ -299,8 +287,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> { if (!overflowEntries.isEmpty()) { // Shift the first entry in the overflow to be the last entry in the // array. - final Iterator<Map.Entry<K, V>> iterator = - getOverflowEntriesMutable().entrySet().iterator(); + final Iterator<Map.Entry<K, V>> iterator = getOverflowEntriesMutable().entrySet().iterator(); entryList.add(new Entry(iterator.next())); iterator.remove(); } @@ -309,8 +296,8 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> { /** * @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<K extends Comparable<K>, V> extends AbstractMap<K, V> { 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<K extends Comparable<K>, V> extends AbstractMap<K, V> { } /** - * 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} + * <p>{@inheritDoc} */ @Override public Set<Map.Entry<K, V>> entrySet() { @@ -358,10 +345,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> { } - /** - * @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<K extends Comparable<K>, V> extends AbstractMap<K, V> { } /** - * @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<K, V> getOverflowEntriesMutable() { @@ -383,10 +365,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> { return (SortedMap<K, V>) 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<K extends Comparable<K>, V> extends AbstractMap<K, V> { } /** - * 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<K, V>, Comparable<Entry> { @@ -451,8 +429,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> { @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<K extends Comparable<K>, V> extends AbstractMap<K, V> { } } - /** - * Stateless view of the entries in the field map. - */ + /** Stateless view of the entries in the field map. */ private class EntrySet extends AbstractSet<Map.Entry<K, V>> { @Override @@ -484,7 +459,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> { /** * Throws a {@link ClassCastException} if o is not of the expected type. * - * {@inheritDoc} + * <p>{@inheritDoc} */ @Override public boolean contains(Object o) { @@ -492,8 +467,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> { final Map.Entry<K, V> entry = (Map.Entry<K, V>) 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<K extends Comparable<K>, V> extends AbstractMap<K, V> { /** * Throws a {@link ClassCastException} if o is not of the expected type. * - * {@inheritDoc} + * <p>{@inheritDoc} */ @Override public boolean remove(Object o) { @@ -529,8 +503,8 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> { /** - * 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<Map.Entry<K, V>> { @@ -571,10 +545,9 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> { } /** - * 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<Map.Entry<K, V>> getOverflowIterator() { if (lazyOverflowIterator == null) { @@ -585,9 +558,9 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> { } /** - * 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<K extends Comparable<K>, V> extends AbstractMap<K, V> { 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<K extends Comparable<K>, V> extends AbstractMap<K, V> { 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 79962e08..f89768a1 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<FieldDescriptor, Object> field - : message.getAllFields().entrySet()) { + for (Map.Entry<FieldDescriptor, Object> 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<Integer, UnknownFieldSet.Field> entry : - unknownFields.asMap().entrySet()) { + private void printUnknownFields( + final UnknownFieldSet unknownFields, final TextGenerator generator) throws IOException { + for (Map.Entry<Integer, UnknownFieldSet.Field> 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}. * - * <p>The Java standard library provides many classes that you might think - * would be useful for implementing this, but aren't. For example: + * <p>The Java standard library provides many classes that you might think would be useful for + * implementing this, but aren't. For example: * * <ul> - * <li>{@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'). - * <li>{@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. + * <li>{@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'). + * <li>{@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. * </ul> * - * <p>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. + * <p>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<ByteString> list = new ArrayList<ByteString>(); @@ -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<ByteString> list) - throws ParseException { - final char quote = currentToken.length() > 0 - ? currentToken.charAt(0) - : '\0'; + private void consumeByteString(List<ByteString> 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 extends Message> T parse(final CharSequence input, - final Class<T> protoClass) - throws ParseException { - Message.Builder builder = - Internal.getDefaultInstance(protoClass).newBuilderForType(); + public static <T extends Message> T parse(final CharSequence input, final Class<T> 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<T> 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. * - * <p>Use {@link TextFormat#getParser()} to obtain the default parser, or - * {@link Builder} to control the parser behavior. + * <p>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": + * * <ul> - * <li>"foo: 1 foo: 2" - * <li>"baz: 1 qux: 2" - * <li>merging "foo: 2" into a proto in which foo is already set, or - * <li>merging "qux: 2" into a proto in which baz is already set. + * <li>"foo: 1 foo: 2" + * <li>"baz: 1 qux: 2" + * <li>merging "foo: 2" into a proto in which foo is already set, or + * <li>merging "qux: 2" into a proto in which baz is already set. * </ul> */ 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<String> unknownFields) - throws ParseException { + private void checkUnknownFields(final List<String> 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<String> unknownFields = new ArrayList<String>(); @@ -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<String> 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<String> 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<String> 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<String> 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 da9ceadd..2501ec93 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 0127ce92..6ce9f783 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. * - * <p>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}. + * <p>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}. * * <p>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<TextFormatParseLocation> getLocations(final FieldDescriptor fieldDescriptor) { List<TextFormatParseLocation> result = locationsFromField.get(fieldDescriptor); return (result == null) ? Collections.<TextFormatParseLocation>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> T getFromList(List<T> list, int index, FieldDescriptor fieldDescriptor) { - if (index >= list.size() || index < 0) { - throw new IllegalArgumentException(String.format("Illegal index field: %s, index %d", - fieldDescriptor == null ? "<null>" : fieldDescriptor.getName(), index)); + if (index >= list.size() || index < 0) { + throw new IllegalArgumentException( + String.format( + "Illegal index field: %s, index %d", + fieldDescriptor == null ? "<null>" : fieldDescriptor.getName(), index)); } return list.get(index); } - /** - * Builder for a {@link TextFormatParseInfoTree}. - */ + /** Builder for a {@link TextFormatParseInfoTree}. */ public static class Builder { private Map<FieldDescriptor, List<TextFormatParseLocation>> locationsFromField; @@ -169,9 +166,7 @@ public class TextFormatParseInfoTree { // sub message location information. private Map<FieldDescriptor, List<Builder>> subtreeBuildersFromField; - /** - * Create a root level {@ParseInfoTree} builder. - */ + /** Create a root level {@ParseInfoTree} builder. */ private Builder() { locationsFromField = new HashMap<FieldDescriptor, List<TextFormatParseLocation>>(); subtreeBuildersFromField = new HashMap<FieldDescriptor, List<Builder>>(); 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 cce286e1..eebfb1b5 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 5714c063..c633a4e8 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 <b>do not</b> - * 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 <b>do + * not</b> 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<String> 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<String> 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<String> 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 b3fdebcb..39deec04 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. * - * <p>Every {@link Message} contains an {@code UnknownFieldSet} (and every - * {@link Message.Builder} contains an {@link Builder}). + * <p>Every {@link Message} contains an {@code UnknownFieldSet} (and every {@link Message.Builder} + * contains an {@link Builder}). * * <p>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.<Integer, Field>emptyMap(), - Collections.<Integer, Field>emptyMap()); + new UnknownFieldSet( + Collections.<Integer, Field>emptyMap(), Collections.<Integer, Field>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<Integer, Field> fields, - final Map<Integer, Field> fieldsDescending) { + UnknownFieldSet(final Map<Integer, Field> fields, final Map<Integer, Field> fieldsDescending) { this.fields = fields; } + private final Map<Integer, Field> 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<Integer, Field> 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<Integer, Field> 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. * - * <p>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. + * <p>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. * * <p>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. * - * <p>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. + * <p>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<Integer, Field> 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. * * <p>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<Integer,Field>(); + fields = new TreeMap<Integer, Field>(); } 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<Integer, Field> 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}. * - * <p>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. + * <p>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. * - * <p>{@code Field} is an immutable class. To construct one, you must use a - * {@link Builder}. + * <p>{@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<Long> getVarintList() { return varint; } + public List<Long> getVarintList() { + return varint; + } /** Get the list of fixed32 values for this field. */ - public List<Integer> getFixed32List() { return fixed32; } + public List<Integer> getFixed32List() { + return fixed32; + } /** Get the list of fixed64 values for this field. */ - public List<Long> getFixed64List() { return fixed64; } + public List<Long> getFixed64List() { + return fixed64; + } /** Get the list of length-delimited values for this field. */ - public List<ByteString> getLengthDelimitedList() { return lengthDelimited; } + public List<ByteString> 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<UnknownFieldSet> getGroupList() { return group; } + public List<UnknownFieldSet> 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<UnknownFieldSet> { @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 f0b919ad..7c5ec6e9 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. * * <p>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. - * + * * <p>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. * * <p>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 { * * <p>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 30e87911..415b2cde 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<String> 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<String> 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 878c7758..bcaf1d2f 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. * * <p><strong>DISCLAIMER:</strong> 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! + * + * <p>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: * - * <p>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: * <ul> - * <li>serialization may throw - * <li>serialization may succeed but the wrong bytes may be written out - * <li>messages are no longer threadsafe - * <li>hashCode may be incorrect - * <ul> - * <li>can result in a permanent memory leak when used as a key in a long-lived HashMap - * <li> the semantics of many programs may be violated if this is the case - * </ul> + * <li>serialization may throw + * <li>serialization may succeed but the wrong bytes may be written out + * <li>messages are no longer threadsafe + * <li>hashCode may be incorrect + * <ul> + * <li>can result in a permanent memory leak when used as a key in a long-lived HashMap + * <li>the semantics of many programs may be violated if this is the case + * </ul> * </ul> + * * 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). * * <p>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! * - * <p> NOTE: The {@link ByteOutput} <strong>MUST NOT</strong> modify the provided buffers. Doing - * so may result in corrupted data, which would be difficult to debug. + * <p>NOTE: The {@link ByteOutput} <strong>MUST NOT</strong> 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 f822ce51..50bc911d 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 b4a81ca3..4512bf9b 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. * - * <p>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. + * <p>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. * - * <p>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: <pre> {@code + * <p>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: + * + * <pre>{@code * Arrays.equals(bytes, new String(bytes, Internal.UTF_8).getBytes(Internal.UTF_8)) * }</pre> * - * <p>See the Unicode Standard,</br> - * Table 3-6. <em>UTF-8 Bit Distribution</em>,</br> - * Table 3-7. <em>Well Formed UTF-8 Byte Sequences</em>. + * <p>See the Unicode Standard,</br> Table 3-6. <em>UTF-8 Bit Distribution</em>,</br> Table 3-7. + * <em>Well Formed UTF-8 Byte Sequences</em>. * - * <p>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. + * <p>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. * - * <p>This is a convenience method, equivalent to a call to {@code - * isValidUtf8(bytes, 0, bytes.length)}. + * <p>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. * - * <p>This is a convenience method, equivalent to {@code - * partialIsValidUtf8(bytes, index, limit) == Utf8.COMPLETE}. + * <p>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. * - * <p>This is a convenience method, equivalent to {@code - * partialIsValidUtf8(bytes, index, limit) == Utf8.COMPLETE}. + * <p>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. * - * <p>This is a convenience method, equivalent to {@code - * partialIsValidUtf8(bytes, index, limit) == Utf8.COMPLETE}. + * <p>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 + * * <pre>{@code * byte[] a = string.getBytes(UTF_8); * System.arraycopy(a, 0, bytes, offset, a.length); * return offset + a.length; * }</pre> * - * 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}. * * <p>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. * * <p>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 8b837ee5..3c6e8dda 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. + * <p>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."); } } |