aboutsummaryrefslogtreecommitdiff
path: root/java
diff options
context:
space:
mode:
authorJoshua Haberman <jhaberman@gmail.com>2018-09-07 16:15:38 -0700
committerGitHub <noreply@github.com>2018-09-07 16:15:38 -0700
commitf9d8138376765d229a32635c9209061e4e4aed8c (patch)
tree50719686fd7262f405c9bda8694d6c72e7c038b8 /java
parent2e7563f40ec7f901ae8ae1cc749d701fa07e211d (diff)
parente53be9bce4556cf0d13e24f1a25a7d75f663144f (diff)
downloadprotobuf-f9d8138376765d229a32635c9209061e4e4aed8c.tar.gz
protobuf-f9d8138376765d229a32635c9209061e4e4aed8c.tar.bz2
protobuf-f9d8138376765d229a32635c9209061e4e4aed8c.zip
Merge pull request #5109 from haberman/integrate
Down-integrate from google3.
Diffstat (limited to 'java')
-rw-r--r--java/core/src/main/java/com/google/protobuf/AbstractMessage.java200
-rw-r--r--java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java80
-rw-r--r--java/core/src/main/java/com/google/protobuf/AbstractParser.java34
-rw-r--r--java/core/src/main/java/com/google/protobuf/AbstractProtobufList.java35
-rw-r--r--java/core/src/main/java/com/google/protobuf/BlockingRpcChannel.java12
-rw-r--r--java/core/src/main/java/com/google/protobuf/BlockingService.java25
-rw-r--r--java/core/src/main/java/com/google/protobuf/BooleanArrayList.java24
-rw-r--r--java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java32
-rw-r--r--java/core/src/main/java/com/google/protobuf/ByteOutput.java22
-rw-r--r--java/core/src/main/java/com/google/protobuf/ByteString.java624
-rw-r--r--java/core/src/main/java/com/google/protobuf/CodedInputStream.java12
-rw-r--r--java/core/src/main/java/com/google/protobuf/CodedOutputStream.java465
-rw-r--r--java/core/src/main/java/com/google/protobuf/Descriptors.java1089
-rw-r--r--java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java13
-rw-r--r--java/core/src/main/java/com/google/protobuf/DoubleArrayList.java23
-rw-r--r--java/core/src/main/java/com/google/protobuf/DynamicMessage.java148
-rw-r--r--java/core/src/main/java/com/google/protobuf/ExperimentalApi.java27
-rw-r--r--java/core/src/main/java/com/google/protobuf/Extension.java15
-rw-r--r--java/core/src/main/java/com/google/protobuf/ExtensionLite.java13
-rw-r--r--java/core/src/main/java/com/google/protobuf/ExtensionRegistry.java184
-rw-r--r--java/core/src/main/java/com/google/protobuf/ExtensionRegistryFactory.java11
-rw-r--r--java/core/src/main/java/com/google/protobuf/ExtensionRegistryLite.java88
-rw-r--r--java/core/src/main/java/com/google/protobuf/FieldSet.java485
-rw-r--r--java/core/src/main/java/com/google/protobuf/FloatArrayList.java23
-rw-r--r--java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java522
-rw-r--r--java/core/src/main/java/com/google/protobuf/IntArrayList.java23
-rw-r--r--java/core/src/main/java/com/google/protobuf/Internal.java350
-rw-r--r--java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java53
-rw-r--r--java/core/src/main/java/com/google/protobuf/LazyField.java20
-rw-r--r--java/core/src/main/java/com/google/protobuf/LazyFieldLite.java123
-rw-r--r--java/core/src/main/java/com/google/protobuf/LazyStringArrayList.java48
-rw-r--r--java/core/src/main/java/com/google/protobuf/LazyStringList.java102
-rw-r--r--java/core/src/main/java/com/google/protobuf/LongArrayList.java23
-rw-r--r--java/core/src/main/java/com/google/protobuf/MapEntry.java108
-rw-r--r--java/core/src/main/java/com/google/protobuf/MapEntryLite.java60
-rw-r--r--java/core/src/main/java/com/google/protobuf/MapField.java105
-rw-r--r--java/core/src/main/java/com/google/protobuf/MapFieldLite.java51
-rw-r--r--java/core/src/main/java/com/google/protobuf/Message.java165
-rw-r--r--java/core/src/main/java/com/google/protobuf/MessageLite.java285
-rw-r--r--java/core/src/main/java/com/google/protobuf/MessageLiteOrBuilder.java23
-rw-r--r--java/core/src/main/java/com/google/protobuf/MessageOrBuilder.java102
-rw-r--r--java/core/src/main/java/com/google/protobuf/MessageReflection.java332
-rw-r--r--java/core/src/main/java/com/google/protobuf/MutabilityOracle.java21
-rw-r--r--java/core/src/main/java/com/google/protobuf/NioByteString.java12
-rw-r--r--java/core/src/main/java/com/google/protobuf/Parser.java203
-rw-r--r--java/core/src/main/java/com/google/protobuf/ProtobufArrayList.java18
-rw-r--r--java/core/src/main/java/com/google/protobuf/ProtocolMessageEnum.java15
-rw-r--r--java/core/src/main/java/com/google/protobuf/ProtocolStringList.java12
-rw-r--r--java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilder.java203
-rw-r--r--java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java203
-rw-r--r--java/core/src/main/java/com/google/protobuf/RopeByteString.java232
-rw-r--r--java/core/src/main/java/com/google/protobuf/RpcCallback.java13
-rw-r--r--java/core/src/main/java/com/google/protobuf/RpcChannel.java43
-rw-r--r--java/core/src/main/java/com/google/protobuf/RpcController.java76
-rw-r--r--java/core/src/main/java/com/google/protobuf/RpcUtil.java50
-rw-r--r--java/core/src/main/java/com/google/protobuf/Service.java86
-rw-r--r--java/core/src/main/java/com/google/protobuf/SingleFieldBuilder.java80
-rw-r--r--java/core/src/main/java/com/google/protobuf/SingleFieldBuilderV3.java80
-rw-r--r--java/core/src/main/java/com/google/protobuf/SmallSortedMap.java182
-rw-r--r--java/core/src/main/java/com/google/protobuf/TextFormat.java920
-rw-r--r--java/core/src/main/java/com/google/protobuf/TextFormatEscaper.java125
-rw-r--r--java/core/src/main/java/com/google/protobuf/TextFormatParseInfoTree.java41
-rw-r--r--java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java7
-rw-r--r--java/core/src/main/java/com/google/protobuf/UninitializedMessageException.java37
-rw-r--r--java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java298
-rw-r--r--java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java139
-rw-r--r--java/core/src/main/java/com/google/protobuf/UnmodifiableLazyStringList.java8
-rw-r--r--java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java41
-rw-r--r--java/core/src/main/java/com/google/protobuf/UnsafeUtil.java16
-rw-r--r--java/core/src/main/java/com/google/protobuf/Utf8.java392
-rw-r--r--java/core/src/main/java/com/google/protobuf/WireFormat.java187
-rw-r--r--java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java193
-rw-r--r--java/core/src/test/java/com/google/protobuf/AnyTest.java8
-rw-r--r--java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java54
-rw-r--r--java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java30
-rw-r--r--java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/ByteStringTest.java235
-rw-r--r--java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java13
-rw-r--r--java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java2
-rw-r--r--java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java91
-rw-r--r--java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java24
-rw-r--r--java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java60
-rw-r--r--java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java16
-rw-r--r--java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java108
-rw-r--r--java/core/src/test/java/com/google/protobuf/EnumTest.java28
-rw-r--r--java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java75
-rw-r--r--java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java121
-rw-r--r--java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java16
-rw-r--r--java/core/src/test/java/com/google/protobuf/ForceFieldBuildersPreRun.java9
-rw-r--r--java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java591
-rw-r--r--java/core/src/test/java/com/google/protobuf/IntArrayListTest.java16
-rw-r--r--java/core/src/test/java/com/google/protobuf/IsValidUtf8Test.java51
-rw-r--r--java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java158
-rw-r--r--java/core/src/test/java/com/google/protobuf/LazyFieldTest.java10
-rw-r--r--java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java174
-rw-r--r--java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java62
-rw-r--r--java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java61
-rw-r--r--java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java281
-rw-r--r--java/core/src/test/java/com/google/protobuf/LongArrayListTest.java16
-rw-r--r--java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java117
-rw-r--r--java/core/src/test/java/com/google/protobuf/MapTest.java268
-rw-r--r--java/core/src/test/java/com/google/protobuf/MessageTest.java210
-rw-r--r--java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java77
-rw-r--r--java/core/src/test/java/com/google/protobuf/NioByteStringTest.java323
-rw-r--r--java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java53
-rw-r--r--java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java37
-rw-r--r--java/core/src/test/java/com/google/protobuf/RopeByteStringSubstringTest.java38
-rw-r--r--java/core/src/test/java/com/google/protobuf/RopeByteStringTest.java75
-rw-r--r--java/core/src/test/java/com/google/protobuf/ServiceTest.java16
-rw-r--r--java/core/src/test/java/com/google/protobuf/SingleFieldBuilderV3Test.java66
-rw-r--r--java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java75
-rw-r--r--java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java36
-rw-r--r--java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java14
-rw-r--r--java/core/src/test/java/com/google/protobuf/TestUtil.java4501
-rw-r--r--java/core/src/test/java/com/google/protobuf/TestUtilLite.java496
-rw-r--r--java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java7
-rw-r--r--java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/TextFormatTest.java909
-rw-r--r--java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java103
-rw-r--r--java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java121
-rw-r--r--java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java262
-rw-r--r--java/core/src/test/java/com/google/protobuf/WireFormatTest.java302
-rw-r--r--java/util/src/main/java/com/google/protobuf/util/JsonFormat.java6
-rw-r--r--java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java48
125 files changed, 9520 insertions, 11074 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.");
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java b/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java
index bb11bd0f..1020c69c 100644
--- a/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java
+++ b/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java
@@ -53,10 +53,9 @@ import junit.framework.TestCase;
*/
public class AbstractMessageTest extends TestCase {
/**
- * Extends AbstractMessage and wraps some other message object. The methods
- * of the Message interface which aren't explicitly implemented by
- * AbstractMessage are forwarded to the wrapped object. This allows us to
- * test that AbstractMessage's implementations work even if the wrapped
+ * Extends AbstractMessage and wraps some other message object. The methods of the Message
+ * interface which aren't explicitly implemented by AbstractMessage are forwarded to the wrapped
+ * object. This allows us to test that AbstractMessage's implementations work even if the wrapped
* object does not use them.
*/
private static class AbstractMessageWrapper extends AbstractMessage {
@@ -70,39 +69,47 @@ public class AbstractMessageTest extends TestCase {
public Descriptors.Descriptor getDescriptorForType() {
return wrappedMessage.getDescriptorForType();
}
+
@Override
public AbstractMessageWrapper getDefaultInstanceForType() {
- return new AbstractMessageWrapper(
- wrappedMessage.getDefaultInstanceForType());
+ return new AbstractMessageWrapper(wrappedMessage.getDefaultInstanceForType());
}
+
@Override
public Map<Descriptors.FieldDescriptor, Object> getAllFields() {
return wrappedMessage.getAllFields();
}
+
@Override
public boolean hasField(Descriptors.FieldDescriptor field) {
return wrappedMessage.hasField(field);
}
+
@Override
public Object getField(Descriptors.FieldDescriptor field) {
return wrappedMessage.getField(field);
}
+
@Override
public int getRepeatedFieldCount(Descriptors.FieldDescriptor field) {
return wrappedMessage.getRepeatedFieldCount(field);
}
+
@Override
public Object getRepeatedField(Descriptors.FieldDescriptor field, int index) {
return wrappedMessage.getRepeatedField(field, index);
}
+
@Override
public UnknownFieldSet getUnknownFields() {
return wrappedMessage.getUnknownFields();
}
+
@Override
public Builder newBuilderForType() {
return new Builder(wrappedMessage.newBuilderForType());
}
+
@Override
public Builder toBuilder() {
return new Builder(wrappedMessage.toBuilder());
@@ -119,85 +126,103 @@ public class AbstractMessageTest extends TestCase {
public AbstractMessageWrapper build() {
return new AbstractMessageWrapper(wrappedBuilder.build());
}
+
@Override
public AbstractMessageWrapper buildPartial() {
return new AbstractMessageWrapper(wrappedBuilder.buildPartial());
}
+
@Override
public Builder clone() {
return new Builder(wrappedBuilder.clone());
}
+
@Override
public boolean isInitialized() {
return clone().buildPartial().isInitialized();
}
+
@Override
public Descriptors.Descriptor getDescriptorForType() {
return wrappedBuilder.getDescriptorForType();
}
+
@Override
public AbstractMessageWrapper getDefaultInstanceForType() {
- return new AbstractMessageWrapper(
- wrappedBuilder.getDefaultInstanceForType());
+ return new AbstractMessageWrapper(wrappedBuilder.getDefaultInstanceForType());
}
+
@Override
public Map<Descriptors.FieldDescriptor, Object> getAllFields() {
return wrappedBuilder.getAllFields();
}
+
@Override
public Builder newBuilderForField(Descriptors.FieldDescriptor field) {
return new Builder(wrappedBuilder.newBuilderForField(field));
}
+
@Override
public boolean hasField(Descriptors.FieldDescriptor field) {
return wrappedBuilder.hasField(field);
}
+
@Override
public Object getField(Descriptors.FieldDescriptor field) {
return wrappedBuilder.getField(field);
}
+
@Override
public Builder setField(Descriptors.FieldDescriptor field, Object value) {
wrappedBuilder.setField(field, value);
return this;
}
+
@Override
public Builder clearField(Descriptors.FieldDescriptor field) {
wrappedBuilder.clearField(field);
return this;
}
+
@Override
public int getRepeatedFieldCount(Descriptors.FieldDescriptor field) {
return wrappedBuilder.getRepeatedFieldCount(field);
}
+
@Override
public Object getRepeatedField(Descriptors.FieldDescriptor field, int index) {
return wrappedBuilder.getRepeatedField(field, index);
}
+
@Override
public Builder setRepeatedField(Descriptors.FieldDescriptor field, int index, Object value) {
wrappedBuilder.setRepeatedField(field, index, value);
return this;
}
+
@Override
public Builder addRepeatedField(Descriptors.FieldDescriptor field, Object value) {
wrappedBuilder.addRepeatedField(field, value);
return this;
}
+
@Override
public UnknownFieldSet getUnknownFields() {
return wrappedBuilder.getUnknownFields();
}
+
@Override
public Builder setUnknownFields(UnknownFieldSet unknownFields) {
wrappedBuilder.setUnknownFields(unknownFields);
return this;
}
+
@Override
public Message.Builder getFieldBuilder(FieldDescriptor field) {
return wrappedBuilder.getFieldBuilder(field);
}
}
+
@Override
public Parser<? extends Message> getParserForType() {
return wrappedMessage.getParserForType();
@@ -207,7 +232,7 @@ public class AbstractMessageTest extends TestCase {
// =================================================================
TestUtil.ReflectionTester reflectionTester =
- new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);
+ new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);
TestUtil.ReflectionTester extensionsReflectionTester =
new TestUtil.ReflectionTester(
@@ -215,16 +240,17 @@ public class AbstractMessageTest extends TestCase {
public void testClear() throws Exception {
AbstractMessageWrapper message =
- new AbstractMessageWrapper.Builder(
- TestAllTypes.newBuilder(TestUtil.getAllSet()))
- .clear().build();
+ new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder(TestUtil.getAllSet()))
+ .clear()
+ .build();
TestUtil.assertClear((TestAllTypes) message.wrappedMessage);
}
public void testCopy() throws Exception {
AbstractMessageWrapper message =
- new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder())
- .mergeFrom(TestUtil.getAllSet()).build();
+ new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder())
+ .mergeFrom(TestUtil.getAllSet())
+ .build();
TestUtil.assertAllFieldsSet((TestAllTypes) message.wrappedMessage);
}
@@ -232,25 +258,21 @@ public class AbstractMessageTest extends TestCase {
TestAllTypes message = TestUtil.getAllSet();
Message abstractMessage = new AbstractMessageWrapper(TestUtil.getAllSet());
- assertEquals(message.getSerializedSize(),
- abstractMessage.getSerializedSize());
+ assertEquals(message.getSerializedSize(), abstractMessage.getSerializedSize());
}
public void testSerialization() throws Exception {
Message abstractMessage = new AbstractMessageWrapper(TestUtil.getAllSet());
- TestUtil.assertAllFieldsSet(
- TestAllTypes.parseFrom(abstractMessage.toByteString()));
+ TestUtil.assertAllFieldsSet(TestAllTypes.parseFrom(abstractMessage.toByteString()));
- assertEquals(TestUtil.getAllSet().toByteString(),
- abstractMessage.toByteString());
+ assertEquals(TestUtil.getAllSet().toByteString(), abstractMessage.toByteString());
}
public void testParsing() throws Exception {
AbstractMessageWrapper.Builder builder =
- new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder());
- AbstractMessageWrapper message =
- builder.mergeFrom(TestUtil.getAllSet().toByteString()).build();
+ new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder());
+ AbstractMessageWrapper message = builder.mergeFrom(TestUtil.getAllSet().toByteString()).build();
TestUtil.assertAllFieldsSet((TestAllTypes) message.wrappedMessage);
}
@@ -270,8 +292,8 @@ public class AbstractMessageTest extends TestCase {
}
// test DynamicMessage directly.
- Message.Builder dynamicMessageBuilder = DynamicMessage.newBuilder(
- TestRequiredForeign.getDescriptor());
+ Message.Builder dynamicMessageBuilder =
+ DynamicMessage.newBuilder(TestRequiredForeign.getDescriptor());
// mergeFrom() should not throw initialization error.
dynamicMessageBuilder.mergeFrom(bytes).buildPartial();
try {
@@ -283,65 +305,56 @@ public class AbstractMessageTest extends TestCase {
}
public void testPackedSerialization() throws Exception {
- Message abstractMessage =
- new AbstractMessageWrapper(TestUtil.getPackedSet());
+ Message abstractMessage = new AbstractMessageWrapper(TestUtil.getPackedSet());
- TestUtil.assertPackedFieldsSet(
- TestPackedTypes.parseFrom(abstractMessage.toByteString()));
+ TestUtil.assertPackedFieldsSet(TestPackedTypes.parseFrom(abstractMessage.toByteString()));
- assertEquals(TestUtil.getPackedSet().toByteString(),
- abstractMessage.toByteString());
+ assertEquals(TestUtil.getPackedSet().toByteString(), abstractMessage.toByteString());
}
public void testPackedParsing() throws Exception {
AbstractMessageWrapper.Builder builder =
- new AbstractMessageWrapper.Builder(TestPackedTypes.newBuilder());
+ new AbstractMessageWrapper.Builder(TestPackedTypes.newBuilder());
AbstractMessageWrapper message =
- builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
+ builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
TestUtil.assertPackedFieldsSet((TestPackedTypes) message.wrappedMessage);
}
public void testUnpackedSerialization() throws Exception {
- Message abstractMessage =
- new AbstractMessageWrapper(TestUtil.getUnpackedSet());
+ Message abstractMessage = new AbstractMessageWrapper(TestUtil.getUnpackedSet());
- TestUtil.assertUnpackedFieldsSet(
- TestUnpackedTypes.parseFrom(abstractMessage.toByteString()));
+ TestUtil.assertUnpackedFieldsSet(TestUnpackedTypes.parseFrom(abstractMessage.toByteString()));
- assertEquals(TestUtil.getUnpackedSet().toByteString(),
- abstractMessage.toByteString());
+ assertEquals(TestUtil.getUnpackedSet().toByteString(), abstractMessage.toByteString());
}
public void testParsePackedToUnpacked() throws Exception {
AbstractMessageWrapper.Builder builder =
- new AbstractMessageWrapper.Builder(TestUnpackedTypes.newBuilder());
+ new AbstractMessageWrapper.Builder(TestUnpackedTypes.newBuilder());
AbstractMessageWrapper message =
- builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
- TestUtil.assertUnpackedFieldsSet(
- (TestUnpackedTypes) message.wrappedMessage);
+ builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
+ TestUtil.assertUnpackedFieldsSet((TestUnpackedTypes) message.wrappedMessage);
}
public void testParseUnpackedToPacked() throws Exception {
AbstractMessageWrapper.Builder builder =
- new AbstractMessageWrapper.Builder(TestPackedTypes.newBuilder());
+ new AbstractMessageWrapper.Builder(TestPackedTypes.newBuilder());
AbstractMessageWrapper message =
- builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
+ builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
TestUtil.assertPackedFieldsSet((TestPackedTypes) message.wrappedMessage);
}
public void testUnpackedParsing() throws Exception {
AbstractMessageWrapper.Builder builder =
- new AbstractMessageWrapper.Builder(TestUnpackedTypes.newBuilder());
+ new AbstractMessageWrapper.Builder(TestUnpackedTypes.newBuilder());
AbstractMessageWrapper message =
- builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
- TestUtil.assertUnpackedFieldsSet(
- (TestUnpackedTypes) message.wrappedMessage);
+ builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
+ TestUtil.assertUnpackedFieldsSet((TestUnpackedTypes) message.wrappedMessage);
}
public void testOptimizedForSize() throws Exception {
// We're mostly only checking that this class was compiled successfully.
- TestOptimizedForSize message =
- TestOptimizedForSize.newBuilder().setI(1).build();
+ TestOptimizedForSize message = TestOptimizedForSize.newBuilder().setI(1).build();
message = TestOptimizedForSize.parseFrom(message.toByteString());
assertEquals(2, message.getSerializedSize());
}
@@ -351,8 +364,7 @@ public class AbstractMessageTest extends TestCase {
public void testIsInitialized() throws Exception {
TestRequired.Builder builder = TestRequired.newBuilder();
- AbstractMessageWrapper.Builder abstractBuilder =
- new AbstractMessageWrapper.Builder(builder);
+ AbstractMessageWrapper.Builder abstractBuilder = new AbstractMessageWrapper.Builder(builder);
assertFalse(abstractBuilder.isInitialized());
assertEquals("a, b, c", abstractBuilder.getInitializationErrorString());
@@ -369,8 +381,7 @@ public class AbstractMessageTest extends TestCase {
public void testForeignIsInitialized() throws Exception {
TestRequiredForeign.Builder builder = TestRequiredForeign.newBuilder();
- AbstractMessageWrapper.Builder abstractBuilder =
- new AbstractMessageWrapper.Builder(builder);
+ AbstractMessageWrapper.Builder abstractBuilder = new AbstractMessageWrapper.Builder(builder);
assertTrue(abstractBuilder.isInitialized());
assertEquals("", abstractBuilder.getInitializationErrorString());
@@ -378,8 +389,7 @@ public class AbstractMessageTest extends TestCase {
builder.setOptionalMessage(TEST_REQUIRED_UNINITIALIZED);
assertFalse(abstractBuilder.isInitialized());
assertEquals(
- "optional_message.b, optional_message.c",
- abstractBuilder.getInitializationErrorString());
+ "optional_message.b, optional_message.c", abstractBuilder.getInitializationErrorString());
builder.setOptionalMessage(TEST_REQUIRED_INITIALIZED);
assertTrue(abstractBuilder.isInitialized());
@@ -400,36 +410,37 @@ public class AbstractMessageTest extends TestCase {
// Tests for mergeFrom
static final TestAllTypes MERGE_SOURCE =
- TestAllTypes.newBuilder()
- .setOptionalInt32(1)
- .setOptionalString("foo")
- .setOptionalForeignMessage(ForeignMessage.getDefaultInstance())
- .addRepeatedString("bar")
- .build();
+ TestAllTypes.newBuilder()
+ .setOptionalInt32(1)
+ .setOptionalString("foo")
+ .setOptionalForeignMessage(ForeignMessage.getDefaultInstance())
+ .addRepeatedString("bar")
+ .build();
static final TestAllTypes MERGE_DEST =
- TestAllTypes.newBuilder()
- .setOptionalInt64(2)
- .setOptionalString("baz")
- .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(3).build())
- .addRepeatedString("qux")
- .build();
+ TestAllTypes.newBuilder()
+ .setOptionalInt64(2)
+ .setOptionalString("baz")
+ .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(3).build())
+ .addRepeatedString("qux")
+ .build();
static final String MERGE_RESULT_TEXT =
- "optional_int32: 1\n" +
- "optional_int64: 2\n" +
- "optional_string: \"foo\"\n" +
- "optional_foreign_message {\n" +
- " c: 3\n" +
- "}\n" +
- "repeated_string: \"qux\"\n" +
- "repeated_string: \"bar\"\n";
+ ""
+ + "optional_int32: 1\n"
+ + "optional_int64: 2\n"
+ + "optional_string: \"foo\"\n"
+ + "optional_foreign_message {\n"
+ + " c: 3\n"
+ + "}\n"
+ + "repeated_string: \"qux\"\n"
+ + "repeated_string: \"bar\"\n";
public void testMergeFrom() throws Exception {
AbstractMessageWrapper result =
- new AbstractMessageWrapper.Builder(
- TestAllTypes.newBuilder(MERGE_DEST))
- .mergeFrom(MERGE_SOURCE).build();
+ new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder(MERGE_DEST))
+ .mergeFrom(MERGE_SOURCE)
+ .build();
assertEquals(MERGE_RESULT_TEXT, result.toString());
}
@@ -443,8 +454,10 @@ public class AbstractMessageTest extends TestCase {
TestAllTypes c = TestAllTypes.newBuilder(b).addRepeatedString("x").build();
TestAllTypes d = TestAllTypes.newBuilder(c).addRepeatedString("y").build();
TestAllExtensions e = TestUtil.getAllExtensionsSet();
- TestAllExtensions f = TestAllExtensions.newBuilder(e)
- .addExtension(UnittestProto.repeatedInt32Extension, 999).build();
+ TestAllExtensions f =
+ TestAllExtensions.newBuilder(e)
+ .addExtension(UnittestProto.repeatedInt32Extension, 999)
+ .build();
checkEqualsIsConsistent(a);
checkEqualsIsConsistent(b);
@@ -489,9 +502,7 @@ public class AbstractMessageTest extends TestCase {
checkEqualsIsConsistent(eUnknownFields, eUnknownFields2);
}
- /**
- * Asserts that the given proto has symmetric equals and hashCode methods.
- */
+ /** Asserts that the given proto has symmetric equals and hashCode methods. */
private void checkEqualsIsConsistent(Message message) {
// Object should be equal to itself.
assertEquals(message, message);
@@ -501,9 +512,7 @@ public class AbstractMessageTest extends TestCase {
checkEqualsIsConsistent(message, dynamic);
}
- /**
- * Asserts that the given protos are equal and have the same hash code.
- */
+ /** Asserts that the given protos are equal and have the same hash code. */
private void checkEqualsIsConsistent(Message message1, Message message2) {
assertEquals(message1, message2);
assertEquals(message2, message1);
@@ -513,9 +522,8 @@ public class AbstractMessageTest extends TestCase {
/**
* Asserts that the given protos are not equal and have different hash codes.
*
- * @warning It's valid for non-equal objects to have the same hash code, so
- * this test is stricter than it needs to be. However, this should happen
- * relatively rarely.
+ * @warning It's valid for non-equal objects to have the same hash code, so this test is stricter
+ * than it needs to be. However, this should happen relatively rarely.
*/
private void checkNotEqual(Message m1, Message m2) {
String equalsError = String.format("%s should not be equal to %s", m1, m2);
@@ -535,7 +543,7 @@ public class AbstractMessageTest extends TestCase {
public void testCheckByteStringIsUtf8OnNonUtf8() {
ByteString byteString =
- ByteString.copyFrom(new byte[]{(byte) 0x80}); // A lone continuation byte.
+ ByteString.copyFrom(new byte[] {(byte) 0x80}); // A lone continuation byte.
try {
AbstractMessageLite.checkByteStringIsUtf8(byteString);
fail("Expected AbstractMessageLite.checkByteStringIsUtf8 to throw IllegalArgumentException");
@@ -543,5 +551,4 @@ public class AbstractMessageTest extends TestCase {
assertEquals("Byte string is not UTF-8.", exception.getMessage());
}
}
-
}
diff --git a/java/core/src/test/java/com/google/protobuf/AnyTest.java b/java/core/src/test/java/com/google/protobuf/AnyTest.java
index cf91ed91..2fe04a94 100644
--- a/java/core/src/test/java/com/google/protobuf/AnyTest.java
+++ b/java/core/src/test/java/com/google/protobuf/AnyTest.java
@@ -32,7 +32,7 @@ package com.google.protobuf;
import any_test.AnyTestProto.TestAny;
import protobuf_unittest.UnittestProto.TestAllTypes;
-
+import java.util.Objects;
import junit.framework.TestCase;
/**
@@ -56,7 +56,7 @@ public class AnyTest extends TestCase {
// Unpacking to a wrong type will throw an exception.
try {
- TestAny wrongMessage = container.getValue().unpack(TestAny.class);
+ container.getValue().unpack(TestAny.class);
fail("Exception is expected.");
} catch (InvalidProtocolBufferException e) {
// expected.
@@ -68,7 +68,7 @@ public class AnyTest extends TestCase {
ByteString.copyFrom(new byte[]{0x11}));
container = containerBuilder.build();
try {
- TestAllTypes parsingFailed = container.getValue().unpack(TestAllTypes.class);
+ container.getValue().unpack(TestAllTypes.class);
fail("Exception is expected.");
} catch (InvalidProtocolBufferException e) {
// expected.
@@ -132,6 +132,6 @@ public class AnyTest extends TestCase {
TestAllTypes result1 = container.getValue().unpack(TestAllTypes.class);
TestAllTypes result2 = container.getValue().unpack(TestAllTypes.class);
- assertTrue(result1 == result2);
+ assertTrue(Objects.equals(result1, result2));
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java b/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java
index febe8537..8ef8edd2 100644
--- a/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java
@@ -45,8 +45,7 @@ import junit.framework.TestCase;
*/
public class BooleanArrayListTest extends TestCase {
- private static final BooleanArrayList UNARY_LIST =
- newImmutableBooleanArrayList(true);
+ private static final BooleanArrayList UNARY_LIST = newImmutableBooleanArrayList(true);
private static final BooleanArrayList TERTIARY_LIST =
newImmutableBooleanArrayList(true, false, true);
@@ -78,10 +77,10 @@ public class BooleanArrayListTest extends TestCase {
list.addAll(asList(true, false, true, false));
Iterator<Boolean> iterator = list.iterator();
assertEquals(4, list.size());
- assertEquals(true, (boolean) list.get(0));
- assertEquals(true, (boolean) iterator.next());
+ assertTrue(list.get(0));
+ assertTrue(iterator.next());
list.set(0, true);
- assertEquals(false, (boolean) iterator.next());
+ assertFalse(iterator.next());
list.remove(0);
try {
@@ -102,9 +101,9 @@ public class BooleanArrayListTest extends TestCase {
}
public void testGet() {
- assertEquals(true, (boolean) TERTIARY_LIST.get(0));
- assertEquals(false, (boolean) TERTIARY_LIST.get(1));
- assertEquals(true, (boolean) TERTIARY_LIST.get(2));
+ assertTrue(TERTIARY_LIST.get(0));
+ assertFalse(TERTIARY_LIST.get(1));
+ assertTrue(TERTIARY_LIST.get(2));
try {
TERTIARY_LIST.get(-1);
@@ -122,9 +121,9 @@ public class BooleanArrayListTest extends TestCase {
}
public void testGetBoolean() {
- assertEquals(true, TERTIARY_LIST.getBoolean(0));
- assertEquals(false, TERTIARY_LIST.getBoolean(1));
- assertEquals(true, TERTIARY_LIST.getBoolean(2));
+ assertTrue(TERTIARY_LIST.getBoolean(0));
+ assertFalse(TERTIARY_LIST.getBoolean(1));
+ assertTrue(TERTIARY_LIST.getBoolean(2));
try {
TERTIARY_LIST.get(-1);
@@ -163,11 +162,11 @@ public class BooleanArrayListTest extends TestCase {
list.addBoolean(false);
list.addBoolean(false);
- assertEquals(false, (boolean) list.set(0, true));
- assertEquals(true, list.getBoolean(0));
+ assertFalse(list.set(0, true));
+ assertTrue(list.getBoolean(0));
- assertEquals(false, (boolean) list.set(1, false));
- assertEquals(false, list.getBoolean(1));
+ assertFalse(list.set(1, false));
+ assertFalse(list.getBoolean(1));
try {
list.set(-1, false);
@@ -188,11 +187,11 @@ public class BooleanArrayListTest extends TestCase {
list.addBoolean(true);
list.addBoolean(true);
- assertEquals(true, list.setBoolean(0, false));
- assertEquals(false, list.getBoolean(0));
+ assertTrue(list.setBoolean(0, false));
+ assertFalse(list.getBoolean(0));
- assertEquals(true, list.setBoolean(1, false));
- assertEquals(false, list.getBoolean(1));
+ assertTrue(list.setBoolean(1, false));
+ assertFalse(list.getBoolean(1));
try {
list.setBoolean(-1, false);
@@ -226,8 +225,7 @@ public class BooleanArrayListTest extends TestCase {
list.add(i % 2 == 0);
}
assertEquals(
- asList(false, true, false, false, true, true, false, true, false, true, false),
- list);
+ asList(false, true, false, false, true, true, false, true, false, true, false), list);
try {
list.add(-1, true);
@@ -257,8 +255,8 @@ public class BooleanArrayListTest extends TestCase {
assertTrue(list.addAll(Collections.singleton(true)));
assertEquals(1, list.size());
- assertEquals(true, (boolean) list.get(0));
- assertEquals(true, list.getBoolean(0));
+ assertTrue(list.get(0));
+ assertTrue(list.getBoolean(0));
assertTrue(list.addAll(asList(false, true, false, true, false)));
assertEquals(asList(true, false, true, false, true, false), list);
@@ -272,7 +270,7 @@ public class BooleanArrayListTest extends TestCase {
public void testRemove() {
list.addAll(TERTIARY_LIST);
- assertEquals(true, (boolean) list.remove(0));
+ assertTrue(list.remove(0));
assertEquals(asList(false, true), list);
assertTrue(list.remove(Boolean.TRUE));
@@ -281,7 +279,7 @@ public class BooleanArrayListTest extends TestCase {
assertFalse(list.remove(Boolean.TRUE));
assertEquals(asList(false), list);
- assertEquals(false, (boolean) list.remove(0));
+ assertFalse(list.remove(0));
assertEquals(asList(), list);
try {
@@ -299,16 +297,14 @@ public class BooleanArrayListTest extends TestCase {
}
public void testRemoveEndOfCapacity() {
- BooleanList toRemove =
- BooleanArrayList.emptyList().mutableCopyWithCapacity(1);
+ BooleanList toRemove = BooleanArrayList.emptyList().mutableCopyWithCapacity(1);
toRemove.addBoolean(true);
toRemove.remove(0);
assertEquals(0, toRemove.size());
}
public void testSublistRemoveEndOfCapacity() {
- BooleanList toRemove =
- BooleanArrayList.emptyList().mutableCopyWithCapacity(1);
+ BooleanList toRemove = BooleanArrayList.emptyList().mutableCopyWithCapacity(1);
toRemove.addBoolean(true);
toRemove.subList(0, 1).clear();
assertEquals(0, toRemove.size());
diff --git a/java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java b/java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java
index db10ee74..654d62bc 100644
--- a/java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java
+++ b/java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java
@@ -38,9 +38,9 @@ import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
/**
- * This class tests {@link BoundedByteString}, which extends {@link LiteralByteString},
- * by inheriting the tests from {@link LiteralByteStringTest}. The only method which
- * is strange enough that it needs to be overridden here is {@link #testToString()}.
+ * This class tests {@link BoundedByteString}, which extends {@link LiteralByteString}, by
+ * inheriting the tests from {@link LiteralByteStringTest}. The only method which is strange enough
+ * that it needs to be overridden here is {@link #testToString()}.
*
* @author carlanton@google.com (Carl Haverl)
*/
@@ -63,12 +63,16 @@ public class BoundedByteStringTest extends LiteralByteStringTest {
String testString = "I love unicode \u1234\u5678 characters";
ByteString unicode = ByteString.wrap(testString.getBytes(Internal.UTF_8));
ByteString chopped = unicode.substring(2, unicode.size() - 6);
- assertEquals(classUnderTest + ".substring() must have the expected type",
- classUnderTest, getActualClassName(chopped));
+ assertEquals(
+ classUnderTest + ".substring() must have the expected type",
+ classUnderTest,
+ getActualClassName(chopped));
String roundTripString = chopped.toString(UTF_8);
- assertEquals(classUnderTest + " unicode bytes must match",
- testString.substring(2, testString.length() - 6), roundTripString);
+ assertEquals(
+ classUnderTest + " unicode bytes must match",
+ testString.substring(2, testString.length() - 6),
+ roundTripString);
}
@Override
@@ -76,12 +80,16 @@ public class BoundedByteStringTest extends LiteralByteStringTest {
String testString = "I love unicode \u1234\u5678 characters";
ByteString unicode = ByteString.wrap(testString.getBytes(Internal.UTF_8));
ByteString chopped = unicode.substring(2, unicode.size() - 6);
- assertEquals(classUnderTest + ".substring() must have the expected type",
- classUnderTest, getActualClassName(chopped));
+ assertEquals(
+ classUnderTest + ".substring() must have the expected type",
+ classUnderTest,
+ getActualClassName(chopped));
String roundTripString = chopped.toString(Internal.UTF_8);
- assertEquals(classUnderTest + " unicode bytes must match",
- testString.substring(2, testString.length() - 6), roundTripString);
+ assertEquals(
+ classUnderTest + " unicode bytes must match",
+ testString.substring(2, testString.length() - 6),
+ roundTripString);
}
@Override
diff --git a/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java b/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java
index 6b1cfe78..5f0ef620 100644
--- a/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java
@@ -37,9 +37,7 @@ import java.util.Arrays;
import java.util.Random;
import junit.framework.TestCase;
-/**
- * Tests for {@link ByteBufferWriter}.
- */
+/** Tests for {@link ByteBufferWriter}. */
public class ByteBufferWriterTest extends TestCase {
public void testHeapBuffer() throws IOException {
diff --git a/java/core/src/test/java/com/google/protobuf/ByteStringTest.java b/java/core/src/test/java/com/google/protobuf/ByteStringTest.java
index fc22955d..83b343ad 100644
--- a/java/core/src/test/java/com/google/protobuf/ByteStringTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ByteStringTest.java
@@ -124,22 +124,24 @@ public class ByteStringTest extends TestCase {
public void testSubstring_BeginIndex() {
byte[] bytes = getTestBytes();
ByteString substring = ByteString.copyFrom(bytes).substring(500);
- assertTrue("substring must contain the tail of the string",
+ assertTrue(
+ "substring must contain the tail of the string",
isArrayRange(substring.toByteArray(), bytes, 500, bytes.length - 500));
}
public void testCopyFrom_BytesOffsetSize() {
byte[] bytes = getTestBytes();
ByteString byteString = ByteString.copyFrom(bytes, 500, 200);
- assertTrue("copyFrom sub-range must contain the expected bytes",
+ assertTrue(
+ "copyFrom sub-range must contain the expected bytes",
isArrayRange(byteString.toByteArray(), bytes, 500, 200));
}
public void testCopyFrom_Bytes() {
byte[] bytes = getTestBytes();
ByteString byteString = ByteString.copyFrom(bytes);
- assertTrue("copyFrom must contain the expected bytes",
- isArray(byteString.toByteArray(), bytes));
+ assertTrue(
+ "copyFrom must contain the expected bytes", isArray(byteString.toByteArray(), bytes));
}
public void testCopyFrom_ByteBufferSize() {
@@ -148,7 +150,8 @@ public class ByteStringTest extends TestCase {
byteBuffer.put(bytes);
byteBuffer.position(500);
ByteString byteString = ByteString.copyFrom(byteBuffer, 200);
- assertTrue("copyFrom byteBuffer sub-range must contain the expected bytes",
+ assertTrue(
+ "copyFrom byteBuffer sub-range must contain the expected bytes",
isArrayRange(byteString.toByteArray(), bytes, 500, 200));
}
@@ -158,7 +161,8 @@ public class ByteStringTest extends TestCase {
byteBuffer.put(bytes);
byteBuffer.position(500);
ByteString byteString = ByteString.copyFrom(byteBuffer);
- assertTrue("copyFrom byteBuffer sub-range must contain the expected bytes",
+ assertTrue(
+ "copyFrom byteBuffer sub-range must contain the expected bytes",
isArrayRange(byteString.toByteArray(), bytes, 500, bytes.length - 500));
}
@@ -166,7 +170,8 @@ public class ByteStringTest extends TestCase {
String testString = "I love unicode \u1234\u5678 characters";
ByteString byteString = ByteString.copyFrom(testString, UTF_16);
byte[] testBytes = testString.getBytes(UTF_16);
- assertTrue("copyFrom string must respect the charset",
+ assertTrue(
+ "copyFrom string must respect the charset",
isArrayRange(byteString.toByteArray(), testBytes, 0, testBytes.length));
}
@@ -174,7 +179,8 @@ public class ByteStringTest extends TestCase {
String testString = "I love unicode \u1234\u5678 characters";
ByteString byteString = ByteString.copyFromUtf8(testString);
byte[] testBytes = testString.getBytes(Internal.UTF_8);
- assertTrue("copyFromUtf8 string must respect the charset",
+ assertTrue(
+ "copyFromUtf8 string must respect the charset",
isArrayRange(byteString.toByteArray(), testBytes, 0, testBytes.length));
}
@@ -183,17 +189,20 @@ public class ByteStringTest extends TestCase {
final List<ByteString> pieces = makeConcretePieces(testBytes);
// Call copyFrom() on a Collection
ByteString byteString = ByteString.copyFrom(pieces);
- assertTrue("copyFrom a List must contain the expected bytes",
+ assertTrue(
+ "copyFrom a List must contain the expected bytes",
isArrayRange(byteString.toByteArray(), testBytes, 0, testBytes.length));
// Call copyFrom on an iteration that's not a collection
- ByteString byteStringAlt = ByteString.copyFrom(new Iterable<ByteString>() {
- @Override
- public Iterator<ByteString> iterator() {
- return pieces.iterator();
- }
- });
- assertEquals("copyFrom from an Iteration must contain the expected bytes",
- byteString, byteStringAlt);
+ ByteString byteStringAlt =
+ ByteString.copyFrom(
+ new Iterable<ByteString>() {
+ @Override
+ public Iterator<ByteString> iterator() {
+ return pieces.iterator();
+ }
+ });
+ assertEquals(
+ "copyFrom from an Iteration must contain the expected bytes", byteString, byteStringAlt);
}
public void testCopyFrom_LengthTooBig() {
@@ -229,15 +238,17 @@ public class ByteStringTest extends TestCase {
ByteString byteString = ByteString.copyFrom(bytes);
byte[] target = new byte[bytes.length + 1000];
byteString.copyTo(target, 400);
- assertTrue("copyFrom byteBuffer sub-range must contain the expected bytes",
+ assertTrue(
+ "copyFrom byteBuffer sub-range must contain the expected bytes",
isArrayRange(bytes, target, 400, bytes.length));
}
public void testReadFrom_emptyStream() throws IOException {
- ByteString byteString =
- ByteString.readFrom(new ByteArrayInputStream(new byte[0]));
- assertSame("reading an empty stream must result in the EMPTY constant "
- + "byte string", ByteString.EMPTY, byteString);
+ ByteString byteString = ByteString.readFrom(new ByteArrayInputStream(new byte[0]));
+ assertSame(
+ "reading an empty stream must result in the EMPTY constant byte string",
+ ByteString.EMPTY,
+ byteString);
}
public void testReadFrom_smallStream() throws IOException {
@@ -245,18 +256,18 @@ public class ByteStringTest extends TestCase {
}
public void testReadFrom_mutating() throws IOException {
- byte[] capturedArray = null;
EvilInputStream eis = new EvilInputStream();
ByteString byteString = ByteString.readFrom(eis);
+ byte[] capturedArray = eis.capturedArray;
- capturedArray = eis.capturedArray;
byte[] originalValue = byteString.toByteArray();
for (int x = 0; x < capturedArray.length; ++x) {
capturedArray[x] = (byte) 0;
}
byte[] newValue = byteString.toByteArray();
- assertTrue("copyFrom byteBuffer must not grant access to underlying array",
+ assertTrue(
+ "copyFrom byteBuffer must not grant access to underlying array",
Arrays.equals(originalValue, newValue));
}
@@ -318,8 +329,8 @@ public class ByteStringTest extends TestCase {
fail("readFrom must throw the underlying IOException");
} catch (IOException e) {
- assertEquals("readFrom must throw the expected exception",
- "synthetic failure", e.getMessage());
+ assertEquals(
+ "readFrom must throw the expected exception", "synthetic failure", e.getMessage());
}
}
@@ -329,7 +340,8 @@ public class ByteStringTest extends TestCase {
final byte[] data = getTestBytes(0x1000);
ByteString byteString = ByteString.readFrom(new ReluctantStream(data));
- assertTrue("readFrom byte stream must contain the expected bytes",
+ assertTrue(
+ "readFrom byte stream must contain the expected bytes",
isArray(byteString.toByteArray(), data));
// Same test as above, but with some specific chunk sizes.
@@ -344,11 +356,10 @@ public class ByteStringTest extends TestCase {
// Fails unless ByteString.readFrom reads the bytes correctly from a
// reluctant stream with the given chunkSize parameter.
- private void assertReadFromReluctantStream(byte[] bytes, int chunkSize)
- throws IOException {
+ private void assertReadFromReluctantStream(byte[] bytes, int chunkSize) throws IOException {
ByteString b = ByteString.readFrom(new ReluctantStream(bytes), chunkSize);
- assertTrue("readFrom byte stream must contain the expected bytes",
- isArray(b.toByteArray(), bytes));
+ assertTrue(
+ "readFrom byte stream must contain the expected bytes", isArray(b.toByteArray(), bytes));
}
// Tests that ByteString.readFrom works with streams that implement
@@ -357,21 +368,23 @@ public class ByteStringTest extends TestCase {
final byte[] data = getTestBytes(0x1001);
ByteString byteString = ByteString.readFrom(new AvailableStream(data));
- assertTrue("readFrom byte stream must contain the expected bytes",
+ assertTrue(
+ "readFrom byte stream must contain the expected bytes",
isArray(byteString.toByteArray(), data));
}
// Fails unless ByteString.readFrom reads the bytes correctly.
private void assertReadFrom(byte[] bytes) throws IOException {
- ByteString byteString =
- ByteString.readFrom(new ByteArrayInputStream(bytes));
- assertTrue("readFrom byte stream must contain the expected bytes",
+ ByteString byteString = ByteString.readFrom(new ByteArrayInputStream(bytes));
+ assertTrue(
+ "readFrom byte stream must contain the expected bytes",
isArray(byteString.toByteArray(), bytes));
}
// A stream that fails when read.
private static final class FailStream extends InputStream {
- @Override public int read() throws IOException {
+ @Override
+ public int read() throws IOException {
throw new IOException("synthetic failure");
}
}
@@ -386,7 +399,8 @@ public class ByteStringTest extends TestCase {
this.data = data;
}
- @Override public int read() {
+ @Override
+ public int read() {
if (pos == data.length) {
return -1;
} else {
@@ -394,11 +408,13 @@ public class ByteStringTest extends TestCase {
}
}
- @Override public int read(byte[] buf) {
+ @Override
+ public int read(byte[] buf) {
return read(buf, 0, buf.length);
}
- @Override public int read(byte[] buf, int offset, int size) {
+ @Override
+ public int read(byte[] buf, int offset, int size) {
if (pos == data.length) {
return -1;
}
@@ -415,7 +431,8 @@ public class ByteStringTest extends TestCase {
super(data);
}
- @Override public int available() {
+ @Override
+ public int available() {
return Math.min(250, data.length - pos);
}
}
@@ -465,8 +482,8 @@ public class ByteStringTest extends TestCase {
String testString = "I love unicode \u1234\u5678 characters";
byte[] testBytes = testString.getBytes(Internal.UTF_8);
ByteString byteString = ByteString.copyFrom(testBytes);
- assertEquals("copyToStringUtf8 must respect the charset",
- testString, byteString.toStringUtf8());
+ assertEquals(
+ "copyToStringUtf8 must respect the charset", testString, byteString.toStringUtf8());
}
public void testNewOutput_InitialCapacity() throws IOException {
@@ -484,8 +501,9 @@ public class ByteStringTest extends TestCase {
public void testNewOutput_ArrayWrite() {
byte[] bytes = getTestBytes();
int length = bytes.length;
- int[] bufferSizes = {128, 256, length / 2, length - 1, length, length + 1,
- 2 * length, 3 * length};
+ int[] bufferSizes = {
+ 128, 256, length / 2, length - 1, length, length + 1, 2 * length, 3 * length
+ };
int[] writeSizes = {1, 4, 5, 7, 23, bytes.length};
for (int bufferSize : bufferSizes) {
@@ -496,7 +514,8 @@ public class ByteStringTest extends TestCase {
output.write(bytes, i, Math.min(writeSize, length - i));
}
ByteString byteString = output.toByteString();
- assertTrue("String built from newOutput() must contain the expected bytes",
+ assertTrue(
+ "String built from newOutput() must contain the expected bytes",
isArrayRange(bytes, byteString.toByteArray(), 0, bytes.length));
}
}
@@ -507,16 +526,17 @@ public class ByteStringTest extends TestCase {
public void testNewOutput_WriteChar() {
byte[] bytes = getTestBytes();
int length = bytes.length;
- int[] bufferSizes = {0, 1, 128, 256, length / 2,
- length - 1, length, length + 1,
- 2 * length, 3 * length};
+ int[] bufferSizes = {
+ 0, 1, 128, 256, length / 2, length - 1, length, length + 1, 2 * length, 3 * length
+ };
for (int bufferSize : bufferSizes) {
ByteString.Output output = ByteString.newOutput(bufferSize);
for (byte byteValue : bytes) {
output.write(byteValue);
}
ByteString byteString = output.toByteString();
- assertTrue("String built from newOutput() must contain the expected bytes",
+ assertTrue(
+ "String built from newOutput() must contain the expected bytes",
isArrayRange(bytes, byteString.toByteArray(), 0, bytes.length));
}
}
@@ -527,9 +547,9 @@ public class ByteStringTest extends TestCase {
Random rng = new Random(1);
byte[] bytes = getTestBytes();
int length = bytes.length;
- int[] bufferSizes = {0, 1, 128, 256, length / 2,
- length - 1, length, length + 1,
- 2 * length, 3 * length};
+ int[] bufferSizes = {
+ 0, 1, 128, 256, length / 2, length - 1, length, length + 1, 2 * length, 3 * length
+ };
for (int bufferSize : bufferSizes) {
// Test writing the entire output using a mixture of write sizes and
@@ -546,12 +566,13 @@ public class ByteStringTest extends TestCase {
position++;
}
assertEquals("size() returns the right value", position, output.size());
- assertTrue("newOutput() substring must have correct bytes",
- isArrayRange(output.toByteString().toByteArray(),
- bytes, 0, position));
+ assertTrue(
+ "newOutput() substring must have correct bytes",
+ isArrayRange(output.toByteString().toByteArray(), bytes, 0, position));
}
ByteString byteString = output.toByteString();
- assertTrue("String built from newOutput() must contain the expected bytes",
+ assertTrue(
+ "String built from newOutput() must contain the expected bytes",
isArrayRange(bytes, byteString.toByteArray(), 0, bytes.length));
}
}
@@ -572,7 +593,8 @@ public class ByteStringTest extends TestCase {
byte[] oldValue = byteString.toByteArray();
Arrays.fill(capturedArray, (byte) 0);
byte[] newValue = byteString.toByteArray();
- assertTrue("Output must not provide access to the underlying byte array",
+ assertTrue(
+ "Output must not provide access to the underlying byte array",
Arrays.equals(oldValue, newValue));
}
@@ -581,14 +603,15 @@ public class ByteStringTest extends TestCase {
ByteString.CodedBuilder builder = ByteString.newCodedBuilder(bytes.length);
builder.getCodedOutput().writeRawBytes(bytes);
ByteString byteString = builder.build();
- assertTrue("String built from newCodedBuilder() must contain the expected bytes",
+ assertTrue(
+ "String built from newCodedBuilder() must contain the expected bytes",
isArrayRange(bytes, byteString.toByteArray(), 0, bytes.length));
}
public void testSubstringParity() {
byte[] bigBytes = getTestBytes(2048 * 1024, 113344L);
int start = 512 * 1024 - 3333;
- int end = 512 * 1024 + 7777;
+ int end = 512 * 1024 + 7777;
ByteString concreteSubstring = ByteString.copyFrom(bigBytes).substring(start, end);
boolean ok = true;
for (int i = start; ok && i < end; ++i) {
@@ -597,10 +620,11 @@ public class ByteStringTest extends TestCase {
assertTrue("Concrete substring didn't capture the right bytes", ok);
ByteString literalString = ByteString.copyFrom(bigBytes, start, end - start);
- assertTrue("Substring must be equal to literal string",
- concreteSubstring.equals(literalString));
- assertEquals("Substring must have same hashcode as literal string",
- literalString.hashCode(), concreteSubstring.hashCode());
+ assertEquals("Substring must be equal to literal string", literalString, concreteSubstring);
+ assertEquals(
+ "Substring must have same hashcode as literal string",
+ literalString.hashCode(),
+ concreteSubstring.hashCode());
}
public void testCompositeSubstring() {
@@ -626,15 +650,22 @@ public class ByteStringTest extends TestCase {
assertTrue("Substring must support byteAt() correctly", stillEqual);
ByteString literalSubstring = ByteString.copyFrom(referenceBytes, from, to - from);
- assertTrue("Composite substring must equal a literal substring over the same bytes",
- compositeSubstring.equals(literalSubstring));
- assertTrue("Literal substring must equal a composite substring over the same bytes",
- literalSubstring.equals(compositeSubstring));
+ assertEquals(
+ "Composite substring must equal a literal substring over the same bytes",
+ literalSubstring,
+ compositeSubstring);
+ assertEquals(
+ "Literal substring must equal a composite substring over the same bytes",
+ compositeSubstring,
+ literalSubstring);
- assertEquals("We must get the same hashcodes for composite and literal substrings",
- literalSubstring.hashCode(), compositeSubstring.hashCode());
+ assertEquals(
+ "We must get the same hashcodes for composite and literal substrings",
+ literalSubstring.hashCode(),
+ compositeSubstring.hashCode());
- assertFalse("We can't be equal to a proper substring",
+ assertFalse(
+ "We can't be equal to a proper substring",
compositeSubstring.equals(literalSubstring.substring(0, literalSubstring.size() - 1)));
}
@@ -645,10 +676,11 @@ public class ByteStringTest extends TestCase {
List<ByteString> pieces = makeConcretePieces(referenceBytes);
ByteString listString = ByteString.copyFrom(pieces);
- assertTrue("Composite string must be equal to literal string",
- listString.equals(literalString));
- assertEquals("Composite string must have same hashcode as literal string",
- literalString.hashCode(), listString.hashCode());
+ assertEquals("Composite string must be equal to literal string", literalString, listString);
+ assertEquals(
+ "Composite string must have same hashcode as literal string",
+ literalString.hashCode(),
+ listString.hashCode());
}
public void testConcat() {
@@ -663,30 +695,34 @@ public class ByteStringTest extends TestCase {
concatenatedString = concatenatedString.concat(iter.next());
}
- assertTrue("Concatenated string must be equal to literal string",
- concatenatedString.equals(literalString));
- assertEquals("Concatenated string must have same hashcode as literal string",
- literalString.hashCode(), concatenatedString.hashCode());
+ assertEquals(
+ "Concatenated string must be equal to literal string", literalString, concatenatedString);
+ assertEquals(
+ "Concatenated string must have same hashcode as literal string",
+ literalString.hashCode(),
+ concatenatedString.hashCode());
}
/**
- * Test the Rope implementation can deal with Empty nodes, even though we
- * guard against them. See also {@link LiteralByteStringTest#testConcat_empty()}.
+ * Test the Rope implementation can deal with Empty nodes, even though we guard against them. See
+ * also {@link LiteralByteStringTest#testConcat_empty()}.
*/
public void testConcat_empty() {
byte[] referenceBytes = getTestBytes(7748, 113344L);
ByteString literalString = ByteString.copyFrom(referenceBytes);
ByteString duo = RopeByteString.newInstanceForTest(literalString, literalString);
- ByteString temp = RopeByteString.newInstanceForTest(
- RopeByteString.newInstanceForTest(literalString, ByteString.EMPTY),
- RopeByteString.newInstanceForTest(ByteString.EMPTY, literalString));
+ ByteString temp =
+ RopeByteString.newInstanceForTest(
+ RopeByteString.newInstanceForTest(literalString, ByteString.EMPTY),
+ RopeByteString.newInstanceForTest(ByteString.EMPTY, literalString));
ByteString quintet = RopeByteString.newInstanceForTest(temp, ByteString.EMPTY);
- assertTrue("String with concatenated nulls must equal simple concatenate",
- duo.equals(quintet));
- assertEquals("String with concatenated nulls have same hashcode as simple concatenate",
- duo.hashCode(), quintet.hashCode());
+ assertEquals("String with concatenated nulls must equal simple concatenate", quintet, duo);
+ assertEquals(
+ "String with concatenated nulls have same hashcode as simple concatenate",
+ duo.hashCode(),
+ quintet.hashCode());
ByteString.ByteIterator duoIter = duo.iterator();
ByteString.ByteIterator quintetIter = quintet.iterator();
@@ -716,11 +752,13 @@ public class ByteStringTest extends TestCase {
// It is possible, using the testing factory method to create deeply nested
// trees of empty leaves, to make a string that will fail this test.
for (int i = 1; i < duo.size(); ++i) {
- assertTrue("Substrings of size() < 2 must not be RopeByteStrings",
+ assertTrue(
+ "Substrings of size() < 2 must not be RopeByteStrings",
duo.substring(i - 1, i) instanceof ByteString.LeafByteString);
}
for (int i = 1; i < quintet.size(); ++i) {
- assertTrue("Substrings of size() < 2 must not be RopeByteStrings",
+ assertTrue(
+ "Substrings of size() < 2 must not be RopeByteStrings",
quintet.substring(i - 1, i) instanceof ByteString.LeafByteString);
}
}
@@ -769,8 +807,7 @@ public class ByteStringTest extends TestCase {
return pieces;
}
- private byte[] substringUsingWriteTo(
- ByteString data, int offset, int length) throws IOException {
+ private byte[] substringUsingWriteTo(ByteString data, int offset, int length) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
data.writeTo(output, offset, length);
return output.toByteArray();
@@ -781,9 +818,7 @@ public class ByteStringTest extends TestCase {
// won't be merged into one byte array due to some optimizations.
final int dataSize = ByteString.CONCATENATE_BY_COPY_SIZE + 1;
byte[] data1 = new byte[dataSize];
- for (int i = 0; i < data1.length; i++) {
- data1[i] = (byte) 1;
- }
+ Arrays.fill(data1, (byte) 1);
data1[1] = (byte) 11;
// Test LiteralByteString.writeTo(OutputStream,int,int)
ByteString left = ByteString.wrap(data1);
@@ -792,9 +827,7 @@ public class ByteStringTest extends TestCase {
assertEquals((byte) 11, result[0]);
byte[] data2 = new byte[dataSize];
- for (int i = 0; i < data1.length; i++) {
- data2[i] = (byte) 2;
- }
+ Arrays.fill(data2, 0, data1.length, (byte) 2);
ByteString right = ByteString.wrap(data2);
// Concatenate two ByteStrings to create a RopeByteString.
ByteString root = left.concat(right);
@@ -819,10 +852,8 @@ public class ByteStringTest extends TestCase {
assertEquals((byte) 2, result[dataSize - dataSize / 2]);
assertEquals((byte) 2, result[dataSize - 1]);
}
-
- /**
- * Tests ByteString uses Arrays based byte copier when running under Hotstop VM.
- */
+
+ /** Tests ByteString uses Arrays based byte copier when running under Hotstop VM. */
public void testByteArrayCopier() throws Exception {
if (Android.isOnAndroidDevice()) {
return;
diff --git a/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java b/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java
index 50b87ae3..e276225e 100644
--- a/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java
+++ b/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java
@@ -38,22 +38,21 @@ import java.io.ByteArrayInputStream;
import junit.framework.TestCase;
/**
- * Test that protos generated with file option java_string_check_utf8 do in
- * fact perform appropriate UTF-8 checks.
+ * Test that protos generated with file option java_string_check_utf8 do in fact perform appropriate
+ * UTF-8 checks.
*
* @author jbaum@google.com (Jacob Butcher)
*/
public class CheckUtf8Test extends TestCase {
private static final String UTF8_BYTE_STRING_TEXT = "some text";
- private static final ByteString UTF8_BYTE_STRING =
- ByteString.copyFromUtf8(UTF8_BYTE_STRING_TEXT);
+ private static final ByteString UTF8_BYTE_STRING = ByteString.copyFromUtf8(UTF8_BYTE_STRING_TEXT);
private static final ByteString NON_UTF8_BYTE_STRING =
- ByteString.copyFrom(new byte[]{(byte) 0x80}); // A lone continuation byte.
+ ByteString.copyFrom(new byte[] {(byte) 0x80}); // A lone continuation byte.
public void testBuildRequiredStringWithGoodUtf8() throws Exception {
- assertEquals(UTF8_BYTE_STRING_TEXT,
- StringWrapper.newBuilder().setReqBytes(UTF8_BYTE_STRING).getReq());
+ assertEquals(
+ UTF8_BYTE_STRING_TEXT, StringWrapper.newBuilder().setReqBytes(UTF8_BYTE_STRING).getReq());
}
public void testParseRequiredStringWithGoodUtf8() throws Exception {
diff --git a/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java b/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java
index 5ea6b79c..f64df334 100644
--- a/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java
+++ b/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java
@@ -699,7 +699,7 @@ public class CodedInputStreamTest extends TestCase {
}
assertEquals(true, input.isAtEnd());
} catch (Exception e) {
- fail("Catch exception in the testIsAtEnd");
+ throw new AssertionError("Catch exception in the testIsAtEnd", e);
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java b/java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java
index dca69cd5..8dc3e4ce 100644
--- a/java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java
+++ b/java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java
@@ -257,13 +257,27 @@ public class CodedOutputStreamTest extends TestCase {
// 41256202580718336
assertWriteVarint(
bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
- (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | (0x43L << 28) | (0x49L << 35)
- | (0x24L << 42) | (0x49L << 49));
+ (0x00 << 0)
+ | (0x66 << 7)
+ | (0x6b << 14)
+ | (0x1c << 21)
+ | (0x43L << 28)
+ | (0x49L << 35)
+ | (0x24L << 42)
+ | (0x49L << 49));
// 11964378330978735131
assertWriteVarint(
bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
- (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | (0x3bL << 28) | (0x56L << 35)
- | (0x00L << 42) | (0x05L << 49) | (0x26L << 56) | (0x01L << 63));
+ (0x1b << 0)
+ | (0x28 << 7)
+ | (0x79 << 14)
+ | (0x42 << 21)
+ | (0x3bL << 28)
+ | (0x56L << 35)
+ | (0x00L << 42)
+ | (0x05L << 49)
+ | (0x26L << 56)
+ | (0x01L << 63));
}
/** Tests writeRawLittleEndian32() and writeRawLittleEndian64(). */
@@ -344,8 +358,8 @@ public class CodedOutputStreamTest extends TestCase {
}
/**
- * Tests writing a whole message with every packed field type. Ensures the
- * wire format of packed fields is compatible with C++.
+ * Tests writing a whole message with every packed field type. Ensures the wire format of packed
+ * fields is compatible with C++.
*/
public void testWriteWholePackedFieldsMessage() throws Exception {
byte[] expectedBytes = TestUtil.getGoldenPackedFieldsMessage().toByteArray();
@@ -361,8 +375,8 @@ public class CodedOutputStreamTest extends TestCase {
}
/**
- * Test writing a message containing a negative enum value. This used to
- * fail because the size was not properly computed as a sign-extended varint.
+ * Test writing a message containing a negative enum value. This used to fail because the size was
+ * not properly computed as a sign-extended varint.
*/
public void testWriteMessageWithNegativeEnumValue() throws Exception {
SparseEnumMessage message =
@@ -394,8 +408,9 @@ public class CodedOutputStreamTest extends TestCase {
String string =
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
// Ensure we take the slower fast path.
- assertTrue(CodedOutputStream.computeUInt32SizeNoTag(string.length())
- != CodedOutputStream.computeUInt32SizeNoTag(string.length() * Utf8.MAX_BYTES_PER_CHAR));
+ assertTrue(
+ CodedOutputStream.computeUInt32SizeNoTag(string.length())
+ != CodedOutputStream.computeUInt32SizeNoTag(string.length() * Utf8.MAX_BYTES_PER_CHAR));
coder.stream().writeStringNoTag(string);
coder.stream().flush();
@@ -438,9 +453,7 @@ public class CodedOutputStreamTest extends TestCase {
}
final int length2 = 8 * 1024;
byte[] data = new byte[length2];
- for (int i = 0; i < length2; i++) {
- data[i] = (byte) 2;
- }
+ Arrays.fill(data, 0, length2, (byte) 2);
codedStream.writeRawBytes(data);
final int length3 = bufferSize - length1 - length2;
for (int i = 0; i < length3; i++) {
@@ -521,10 +534,14 @@ public class CodedOutputStreamTest extends TestCase {
}
public void testSerializeInvalidUtf8() throws Exception {
- String[] invalidStrings = new String[] {newString(Character.MIN_HIGH_SURROGATE),
- "foobar" + newString(Character.MIN_HIGH_SURROGATE), newString(Character.MIN_LOW_SURROGATE),
- "foobar" + newString(Character.MIN_LOW_SURROGATE),
- newString(Character.MIN_HIGH_SURROGATE, Character.MIN_HIGH_SURROGATE)};
+ String[] invalidStrings =
+ new String[] {
+ newString(Character.MIN_HIGH_SURROGATE),
+ "foobar" + newString(Character.MIN_HIGH_SURROGATE),
+ newString(Character.MIN_LOW_SURROGATE),
+ "foobar" + newString(Character.MIN_LOW_SURROGATE),
+ newString(Character.MIN_HIGH_SURROGATE, Character.MIN_HIGH_SURROGATE)
+ };
CodedOutputStream outputWithStream = CodedOutputStream.newInstance(new ByteArrayOutputStream());
CodedOutputStream outputWithArray = CodedOutputStream.newInstance(new byte[10000]);
@@ -594,16 +611,17 @@ public class CodedOutputStreamTest extends TestCase {
// with ASCII and Unicode characters requiring different UTF-8 byte counts per
// char, hence causing the length delimiter varint to sometimes require more
// bytes for the Unicode strings than the ASCII string of the same length.
- int[] lengths = new int[] {
- 0,
- 1,
- (1 << 4) - 1, // 1 byte for ASCII and Unicode
- (1 << 7) - 1, // 1 byte for ASCII, 2 bytes for Unicode
- (1 << 11) - 1, // 2 bytes for ASCII and Unicode
- (1 << 14) - 1, // 2 bytes for ASCII, 3 bytes for Unicode
- (1 << 17) - 1,
- // 3 bytes for ASCII and Unicode
- };
+ int[] lengths =
+ new int[] {
+ 0,
+ 1,
+ (1 << 4) - 1, // 1 byte for ASCII and Unicode
+ (1 << 7) - 1, // 1 byte for ASCII, 2 bytes for Unicode
+ (1 << 11) - 1, // 2 bytes for ASCII and Unicode
+ (1 << 14) - 1, // 2 bytes for ASCII, 3 bytes for Unicode
+ (1 << 17) - 1,
+ // 3 bytes for ASCII and Unicode
+ };
for (OutputType outputType : OutputType.values()) {
for (int i : lengths) {
testEncodingOfString(outputType, 'q', i); // 1 byte per char
@@ -626,8 +644,8 @@ public class CodedOutputStreamTest extends TestCase {
}
/**
- * Parses the given bytes using writeRawLittleEndian32() and checks
- * that the result matches the given value.
+ * Parses the given bytes using writeRawLittleEndian32() and checks that the result matches the
+ * given value.
*/
private static void assertWriteLittleEndian32(byte[] data, int value) throws Exception {
for (OutputType outputType : OutputType.values()) {
@@ -647,8 +665,8 @@ public class CodedOutputStreamTest extends TestCase {
}
/**
- * Parses the given bytes using writeRawLittleEndian64() and checks
- * that the result matches the given value.
+ * Parses the given bytes using writeRawLittleEndian64() and checks that the result matches the
+ * given value.
*/
private static void assertWriteLittleEndian64(byte[] data, long value) throws Exception {
for (OutputType outputType : OutputType.values()) {
@@ -691,9 +709,8 @@ public class CodedOutputStreamTest extends TestCase {
}
/**
- * Helper to construct a byte array from a bunch of bytes. The inputs are
- * actually ints so that I can use hex notation and not get stupid errors
- * about precision.
+ * Helper to construct a byte array from a bunch of bytes. The inputs are actually ints so that I
+ * can use hex notation and not get stupid errors about precision.
*/
private static byte[] bytes(int... bytesAsInts) {
byte[] bytes = new byte[bytesAsInts.length];
@@ -703,7 +720,7 @@ public class CodedOutputStreamTest extends TestCase {
return bytes;
}
- /** Arrays.asList() does not work with arrays of primitives. :( */
+ /** Arrays.asList() does not work with arrays of primitives. :( */
private static List<Byte> toList(byte[] bytes) {
List<Byte> result = new ArrayList<Byte>();
for (byte b : bytes) {
@@ -717,8 +734,8 @@ public class CodedOutputStreamTest extends TestCase {
}
/**
- * Writes the given value using writeRawVarint32() and writeRawVarint64() and
- * checks that the result matches the given bytes.
+ * Writes the given value using writeRawVarint32() and writeRawVarint64() and checks that the
+ * result matches the given bytes.
*/
private static void assertWriteVarint(byte[] data, long value) throws Exception {
for (OutputType outputType : OutputType.values()) {
diff --git a/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java b/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java
index 9c0997c4..2addde84 100644
--- a/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java
+++ b/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java
@@ -41,35 +41,28 @@ import junit.framework.TestCase;
* @author birdo@google.com (Roberto Scaramuzzi)
*/
public class DeprecatedFieldTest extends TestCase {
- private String[] deprecatedGetterNames = {
- "hasDeprecatedInt32",
- "getDeprecatedInt32"};
+ private String[] deprecatedGetterNames = {"hasDeprecatedInt32", "getDeprecatedInt32"};
private String[] deprecatedBuilderGetterNames = {
- "hasDeprecatedInt32",
- "getDeprecatedInt32",
- "clearDeprecatedInt32"};
+ "hasDeprecatedInt32", "getDeprecatedInt32", "clearDeprecatedInt32"
+ };
- private String[] deprecatedBuilderSetterNames = {
- "setDeprecatedInt32"};
+ private String[] deprecatedBuilderSetterNames = {"setDeprecatedInt32"};
public void testDeprecatedField() throws Exception {
Class<?> deprecatedFields = TestDeprecatedFields.class;
Class<?> deprecatedFieldsBuilder = TestDeprecatedFields.Builder.class;
for (String name : deprecatedGetterNames) {
Method method = deprecatedFields.getMethod(name);
- assertTrue("Method " + name + " should be deprecated",
- isDeprecated(method));
+ assertTrue("Method " + name + " should be deprecated", isDeprecated(method));
}
for (String name : deprecatedBuilderGetterNames) {
Method method = deprecatedFieldsBuilder.getMethod(name);
- assertTrue("Method " + name + " should be deprecated",
- isDeprecated(method));
+ assertTrue("Method " + name + " should be deprecated", isDeprecated(method));
}
for (String name : deprecatedBuilderSetterNames) {
Method method = deprecatedFieldsBuilder.getMethod(name, int.class);
- assertTrue("Method " + name + " should be deprecated",
- isDeprecated(method));
+ assertTrue("Method " + name + " should be deprecated", isDeprecated(method));
}
}
@@ -77,8 +70,7 @@ public class DeprecatedFieldTest extends TestCase {
Class<?> oneofCase = TestDeprecatedFields.OneofFieldsCase.class;
String name = "DEPRECATED_INT32_IN_ONEOF";
java.lang.reflect.Field enumValue = oneofCase.getField(name);
- assertTrue("Enum value " + name + " should be deprecated.",
- isDeprecated(enumValue));
+ assertTrue("Enum value " + name + " should be deprecated.", isDeprecated(enumValue));
}
private boolean isDeprecated(AnnotatedElement annotated) {
diff --git a/java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java b/java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java
index 36c4611f..01a96ba5 100644
--- a/java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java
+++ b/java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java
@@ -43,15 +43,13 @@ import org.junit.runners.JUnit4;
public class DiscardUnknownFieldsTest {
@Test
public void testProto2() throws Exception {
+ testProto2Message(UnittestProto.TestEmptyMessage.getDefaultInstance());
+ testProto2Message(UnittestProto.TestEmptyMessageWithExtensions.getDefaultInstance());
testProto2Message(
- UnittestProto.TestEmptyMessage.getDefaultInstance());
+ DynamicMessage.getDefaultInstance(UnittestProto.TestEmptyMessage.getDescriptor()));
testProto2Message(
- UnittestProto.TestEmptyMessageWithExtensions.getDefaultInstance());
- testProto2Message(
- DynamicMessage.getDefaultInstance(UnittestProto.TestEmptyMessage.getDescriptor()));
- testProto2Message(
- DynamicMessage.getDefaultInstance(
- UnittestProto.TestEmptyMessageWithExtensions.getDescriptor()));
+ DynamicMessage.getDefaultInstance(
+ UnittestProto.TestEmptyMessageWithExtensions.getDescriptor()));
}
@Test
@@ -81,18 +79,16 @@ public class DiscardUnknownFieldsTest {
payload.copyTo(copied, 0);
payload.copyTo(copied, messageSize);
CodedInputStream input = CodedInputStream.newInstance(copied);
- {
- // Use DiscardUnknownFieldsParser to parse the first payload.
- int oldLimit = input.pushLimit(messageSize);
- Message parsed = DiscardUnknownFieldsParser.wrap(message.getParserForType()).parseFrom(input);
- assertEquals(message.getClass().getName(), 0, parsed.getSerializedSize());
- input.popLimit(oldLimit);
- }
- {
- // Use the normal parser to parse the remaining payload should have unknown fields preserved.
- Message parsed = message.getParserForType().parseFrom(input);
- assertEquals(message.getClass().getName(), payload, parsed.toByteString());
- }
+
+ // Use DiscardUnknownFieldsParser to parse the first payload.
+ int oldLimit = input.pushLimit(messageSize);
+ Message parsed = DiscardUnknownFieldsParser.wrap(message.getParserForType()).parseFrom(input);
+ assertEquals(message.getClass().getName(), 0, parsed.getSerializedSize());
+ input.popLimit(oldLimit);
+
+ // Use the normal parser to parse the remaining payload should have unknown fields preserved.
+ parsed = message.getParserForType().parseFrom(input);
+ assertEquals(message.getClass().getName(), payload, parsed.toByteString());
}
/**
@@ -104,34 +100,18 @@ public class DiscardUnknownFieldsTest {
UnknownFieldSet unknownFields = UnknownFieldSet.newBuilder().mergeFrom(payload).build();
Message built = message.newBuilderForType().setUnknownFields(unknownFields).build();
assertEquals(message.getClass().getName(), payload, built.toByteString());
-
- }
- /**
- * {@link Message.Builder#setUnknownFields(UnknownFieldSet)} and {@link
- * Message.Builder#mergeUnknownFields(UnknownFieldSet)} should discard the unknown fields.
- */
- private static void assertUnknownFieldsInUnknownFieldSetAreDiscarded(Message message)
- throws Exception {
- UnknownFieldSet unknownFields = UnknownFieldSet.newBuilder().mergeFrom(payload).build();
- Message built = message.newBuilderForType().setUnknownFields(unknownFields).build();
- assertEquals(message.getClass().getName(), 0, built.getSerializedSize());
}
private static void assertUnknownFieldsPreserved(MessageLite message) throws Exception {
- {
- MessageLite parsed = message.getParserForType().parseFrom(payload);
- assertEquals(message.getClass().getName(), payload, parsed.toByteString());
- }
+ MessageLite parsed = message.getParserForType().parseFrom(payload);
+ assertEquals(message.getClass().getName(), payload, parsed.toByteString());
- {
- MessageLite parsed = message.newBuilderForType().mergeFrom(payload).build();
- assertEquals(message.getClass().getName(), payload, parsed.toByteString());
- }
+ parsed = message.newBuilderForType().mergeFrom(payload).build();
+ assertEquals(message.getClass().getName(), payload, parsed.toByteString());
}
private static void assertUnknownFieldsExplicitlyDiscarded(Message message) throws Exception {
- Message parsed =
- DiscardUnknownFieldsParser.wrap(message.getParserForType()).parseFrom(payload);
+ Message parsed = DiscardUnknownFieldsParser.wrap(message.getParserForType()).parseFrom(payload);
assertEquals(message.getClass().getName(), 0, parsed.getSerializedSize());
}
diff --git a/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java b/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java
index a4c2f5aa..6a942121 100644
--- a/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java
@@ -45,10 +45,8 @@ import junit.framework.TestCase;
*/
public class DoubleArrayListTest extends TestCase {
- private static final DoubleArrayList UNARY_LIST =
- newImmutableDoubleArrayList(1);
- private static final DoubleArrayList TERTIARY_LIST =
- newImmutableDoubleArrayList(1, 2, 3);
+ private static final DoubleArrayList UNARY_LIST = newImmutableDoubleArrayList(1);
+ private static final DoubleArrayList TERTIARY_LIST = newImmutableDoubleArrayList(1, 2, 3);
private DoubleArrayList list;
@@ -225,9 +223,7 @@ public class DoubleArrayListTest extends TestCase {
for (int i = 0; i < 6; i++) {
list.add(Double.valueOf(5 + i));
}
- assertEquals(
- asList(0D, 1D, 4D, 2D, 3D, 5D, 6D, 7D, 8D, 9D, 10D),
- list);
+ assertEquals(asList(0D, 1D, 4D, 2D, 3D, 5D, 6D, 7D, 8D, 9D, 10D), list);
try {
list.add(-1, 5D);
@@ -299,16 +295,14 @@ public class DoubleArrayListTest extends TestCase {
}
public void testRemoveEndOfCapacity() {
- DoubleList toRemove =
- DoubleArrayList.emptyList().mutableCopyWithCapacity(1);
+ DoubleList toRemove = DoubleArrayList.emptyList().mutableCopyWithCapacity(1);
toRemove.addDouble(3);
toRemove.remove(0);
assertEquals(0, toRemove.size());
}
public void testSublistRemoveEndOfCapacity() {
- DoubleList toRemove =
- DoubleArrayList.emptyList().mutableCopyWithCapacity(1);
+ DoubleList toRemove = DoubleArrayList.emptyList().mutableCopyWithCapacity(1);
toRemove.addDouble(3);
toRemove.subList(0, 1).clear();
assertEquals(0, toRemove.size());
diff --git a/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java b/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java
index 346c1e6a..0514241a 100644
--- a/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java
+++ b/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java
@@ -41,32 +41,30 @@ import java.util.Arrays;
import junit.framework.TestCase;
/**
- * Unit test for {@link DynamicMessage}. See also {@link MessageTest}, which
- * tests some {@link DynamicMessage} functionality.
+ * Unit test for {@link DynamicMessage}. See also {@link MessageTest}, which tests some {@link
+ * DynamicMessage} functionality.
*
* @author kenton@google.com Kenton Varda
*/
public class DynamicMessageTest extends TestCase {
TestUtil.ReflectionTester reflectionTester =
- new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);
+ new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);
TestUtil.ReflectionTester extensionsReflectionTester =
new TestUtil.ReflectionTester(
TestAllExtensions.getDescriptor(), TestUtil.getFullExtensionRegistry());
TestUtil.ReflectionTester packedReflectionTester =
- new TestUtil.ReflectionTester(TestPackedTypes.getDescriptor(), null);
+ new TestUtil.ReflectionTester(TestPackedTypes.getDescriptor(), null);
public void testDynamicMessageAccessors() throws Exception {
- Message.Builder builder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.setAllFieldsViaReflection(builder);
Message message = builder.build();
reflectionTester.assertAllFieldsSetViaReflection(message);
}
public void testSettersAfterBuild() throws Exception {
- Message.Builder builder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
Message firstMessage = builder.build();
// double build()
builder.build();
@@ -85,12 +83,12 @@ public class DynamicMessageTest extends TestCase {
}
public void testUnknownFields() throws Exception {
- Message.Builder builder =
- DynamicMessage.newBuilder(TestEmptyMessage.getDescriptor());
- builder.setUnknownFields(UnknownFieldSet.newBuilder()
- .addField(1, UnknownFieldSet.Field.newBuilder().addVarint(1).build())
- .addField(2, UnknownFieldSet.Field.newBuilder().addFixed32(1).build())
- .build());
+ Message.Builder builder = DynamicMessage.newBuilder(TestEmptyMessage.getDescriptor());
+ builder.setUnknownFields(
+ UnknownFieldSet.newBuilder()
+ .addField(1, UnknownFieldSet.Field.newBuilder().addVarint(1).build())
+ .addField(2, UnknownFieldSet.Field.newBuilder().addFixed32(1).build())
+ .build());
Message message = builder.build();
assertEquals(2, message.getUnknownFields().asMap().size());
// clone() with unknown fields
@@ -105,8 +103,7 @@ public class DynamicMessageTest extends TestCase {
}
public void testDynamicMessageSettersRejectNull() throws Exception {
- Message.Builder builder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.assertReflectionSettersRejectNull(builder);
}
@@ -114,22 +111,19 @@ public class DynamicMessageTest extends TestCase {
// We don't need to extensively test DynamicMessage's handling of
// extensions because, frankly, it doesn't do anything special with them.
// It treats them just like any other fields.
- Message.Builder builder =
- DynamicMessage.newBuilder(TestAllExtensions.getDescriptor());
+ Message.Builder builder = DynamicMessage.newBuilder(TestAllExtensions.getDescriptor());
extensionsReflectionTester.setAllFieldsViaReflection(builder);
Message message = builder.build();
extensionsReflectionTester.assertAllFieldsSetViaReflection(message);
}
public void testDynamicMessageExtensionSettersRejectNull() throws Exception {
- Message.Builder builder =
- DynamicMessage.newBuilder(TestAllExtensions.getDescriptor());
+ Message.Builder builder = DynamicMessage.newBuilder(TestAllExtensions.getDescriptor());
extensionsReflectionTester.assertReflectionSettersRejectNull(builder);
}
public void testDynamicMessageRepeatedSetters() throws Exception {
- Message.Builder builder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.setAllFieldsViaReflection(builder);
reflectionTester.modifyRepeatedFieldsViaReflection(builder);
Message message = builder.build();
@@ -137,33 +131,29 @@ public class DynamicMessageTest extends TestCase {
}
public void testDynamicMessageRepeatedSettersRejectNull() throws Exception {
- Message.Builder builder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.assertReflectionRepeatedSettersRejectNull(builder);
}
public void testDynamicMessageDefaults() throws Exception {
reflectionTester.assertClearViaReflection(
- DynamicMessage.getDefaultInstance(TestAllTypes.getDescriptor()));
+ DynamicMessage.getDefaultInstance(TestAllTypes.getDescriptor()));
reflectionTester.assertClearViaReflection(
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor()).build());
+ DynamicMessage.newBuilder(TestAllTypes.getDescriptor()).build());
}
public void testDynamicMessageSerializedSize() throws Exception {
TestAllTypes message = TestUtil.getAllSet();
- Message.Builder dynamicBuilder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ Message.Builder dynamicBuilder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.setAllFieldsViaReflection(dynamicBuilder);
Message dynamicMessage = dynamicBuilder.build();
- assertEquals(message.getSerializedSize(),
- dynamicMessage.getSerializedSize());
+ assertEquals(message.getSerializedSize(), dynamicMessage.getSerializedSize());
}
public void testDynamicMessageSerialization() throws Exception {
- Message.Builder builder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.setAllFieldsViaReflection(builder);
Message message = builder.build();
@@ -183,8 +173,7 @@ public class DynamicMessageTest extends TestCase {
ByteString rawBytes = message.toByteString();
- Message message2 =
- DynamicMessage.parseFrom(TestAllTypes.getDescriptor(), rawBytes);
+ Message message2 = DynamicMessage.parseFrom(TestAllTypes.getDescriptor(), rawBytes);
reflectionTester.assertAllFieldsSetViaReflection(message2);
// Test Parser interface.
@@ -200,14 +189,13 @@ public class DynamicMessageTest extends TestCase {
extensionsReflectionTester.assertAllFieldsSetViaReflection(message);
// Test Parser interface.
- Message message2 = message.getParserForType().parseFrom(
- rawBytes, TestUtil.getExtensionRegistry());
+ Message message2 =
+ message.getParserForType().parseFrom(rawBytes, TestUtil.getExtensionRegistry());
extensionsReflectionTester.assertAllFieldsSetViaReflection(message2);
}
public void testDynamicMessagePackedSerialization() throws Exception {
- Message.Builder builder =
- DynamicMessage.newBuilder(TestPackedTypes.getDescriptor());
+ Message.Builder builder = DynamicMessage.newBuilder(TestPackedTypes.getDescriptor());
packedReflectionTester.setPackedFieldsViaReflection(builder);
Message message = builder.build();
@@ -227,8 +215,7 @@ public class DynamicMessageTest extends TestCase {
ByteString rawBytes = message.toByteString();
- Message message2 =
- DynamicMessage.parseFrom(TestPackedTypes.getDescriptor(), rawBytes);
+ Message message2 = DynamicMessage.parseFrom(TestPackedTypes.getDescriptor(), rawBytes);
packedReflectionTester.assertPackedFieldsSetViaReflection(message2);
// Test Parser interface.
@@ -245,41 +232,38 @@ public class DynamicMessageTest extends TestCase {
reflectionTester.assertAllFieldsSetViaReflection(copy);
// Test oneof behavior
- FieldDescriptor bytesField =
- TestAllTypes.getDescriptor().findFieldByName("oneof_bytes");
- FieldDescriptor uint32Field =
- TestAllTypes.getDescriptor().findFieldByName("oneof_uint32");
+ FieldDescriptor bytesField = TestAllTypes.getDescriptor().findFieldByName("oneof_bytes");
+ FieldDescriptor uint32Field = TestAllTypes.getDescriptor().findFieldByName("oneof_uint32");
assertTrue(copy.hasField(bytesField));
assertFalse(copy.hasField(uint32Field));
- DynamicMessage copy2 =
- DynamicMessage.newBuilder(message).setField(uint32Field, 123).build();
+ DynamicMessage copy2 = DynamicMessage.newBuilder(message).setField(uint32Field, 123).build();
assertFalse(copy2.hasField(bytesField));
assertTrue(copy2.hasField(uint32Field));
assertEquals(123, copy2.getField(uint32Field));
}
public void testToBuilder() throws Exception {
- DynamicMessage.Builder builder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ DynamicMessage.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.setAllFieldsViaReflection(builder);
int unknownFieldNum = 9;
long unknownFieldVal = 90;
- builder.setUnknownFields(UnknownFieldSet.newBuilder()
- .addField(unknownFieldNum,
- UnknownFieldSet.Field.newBuilder()
- .addVarint(unknownFieldVal).build())
- .build());
+ builder.setUnknownFields(
+ UnknownFieldSet.newBuilder()
+ .addField(
+ unknownFieldNum,
+ UnknownFieldSet.Field.newBuilder().addVarint(unknownFieldVal).build())
+ .build());
DynamicMessage message = builder.build();
DynamicMessage derived = message.toBuilder().build();
reflectionTester.assertAllFieldsSetViaReflection(derived);
- assertEquals(Arrays.asList(unknownFieldVal),
+ assertEquals(
+ Arrays.asList(unknownFieldVal),
derived.getUnknownFields().getField(unknownFieldNum).getVarintList());
}
public void testDynamicOneofMessage() throws Exception {
- DynamicMessage.Builder builder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ DynamicMessage.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
OneofDescriptor oneof = TestAllTypes.getDescriptor().getOneofs().get(0);
assertFalse(builder.hasOneof(oneof));
assertSame(null, builder.getOneofFieldDescriptor(oneof));
@@ -292,8 +276,7 @@ public class DynamicMessageTest extends TestCase {
DynamicMessage message = builder.buildPartial();
assertTrue(message.hasOneof(oneof));
- DynamicMessage.Builder mergedBuilder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ DynamicMessage.Builder mergedBuilder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
FieldDescriptor mergedField = oneof.getField(0);
mergedBuilder.setField(mergedField, 123);
assertTrue(mergedBuilder.hasField(mergedField));
@@ -310,15 +293,12 @@ public class DynamicMessageTest extends TestCase {
// Regression test for a bug that makes setField() not work for repeated
// enum fields.
public void testSettersForRepeatedEnumField() throws Exception {
- DynamicMessage.Builder builder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ DynamicMessage.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
FieldDescriptor repeatedEnumField =
- TestAllTypes.getDescriptor().findFieldByName(
- "repeated_nested_enum");
+ TestAllTypes.getDescriptor().findFieldByName("repeated_nested_enum");
EnumDescriptor enumDescriptor = TestAllTypes.NestedEnum.getDescriptor();
builder.setField(repeatedEnumField, enumDescriptor.getValues());
DynamicMessage message = builder.build();
- assertEquals(
- enumDescriptor.getValues(), message.getField(repeatedEnumField));
+ assertEquals(enumDescriptor.getValues(), message.getField(repeatedEnumField));
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/EnumTest.java b/java/core/src/test/java/com/google/protobuf/EnumTest.java
index 14c7406b..80c176a7 100644
--- a/java/core/src/test/java/com/google/protobuf/EnumTest.java
+++ b/java/core/src/test/java/com/google/protobuf/EnumTest.java
@@ -34,43 +34,43 @@ import com.google.protobuf.UnittestLite.ForeignEnumLite;
import com.google.protobuf.UnittestLite.TestAllTypesLite;
import protobuf_unittest.UnittestProto.ForeignEnum;
import protobuf_unittest.UnittestProto.TestAllTypes;
-
import junit.framework.TestCase;
public class EnumTest extends TestCase {
-
+
public void testForNumber() {
ForeignEnum e = ForeignEnum.forNumber(ForeignEnum.FOREIGN_BAR.getNumber());
assertEquals(ForeignEnum.FOREIGN_BAR, e);
e = ForeignEnum.forNumber(1000);
- assertEquals(null, e);
+ assertNull(e);
}
-
+
public void testForNumber_oneof() {
- TestAllTypes.OneofFieldCase e = TestAllTypes.OneofFieldCase.forNumber(
- TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber());
+ TestAllTypes.OneofFieldCase e =
+ TestAllTypes.OneofFieldCase.forNumber(
+ TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber());
assertEquals(TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE, e);
e = TestAllTypes.OneofFieldCase.forNumber(1000);
- assertEquals(null, e);
+ assertNull(e);
}
-
+
public void testForNumberLite() {
ForeignEnumLite e = ForeignEnumLite.forNumber(ForeignEnumLite.FOREIGN_LITE_BAR.getNumber());
assertEquals(ForeignEnumLite.FOREIGN_LITE_BAR, e);
e = ForeignEnumLite.forNumber(1000);
- assertEquals(null, e);
+ assertNull(e);
}
-
+
public void testForNumberLite_oneof() {
- TestAllTypesLite.OneofFieldCase e = TestAllTypesLite.OneofFieldCase.forNumber(
- TestAllTypesLite.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber());
+ TestAllTypesLite.OneofFieldCase e =
+ TestAllTypesLite.OneofFieldCase.forNumber(
+ TestAllTypesLite.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber());
assertEquals(TestAllTypesLite.OneofFieldCase.ONEOF_NESTED_MESSAGE, e);
e = TestAllTypesLite.OneofFieldCase.forNumber(1000);
- assertEquals(null, e);
+ assertNull(e);
}
}
-
diff --git a/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java b/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java
index 6157e589..a0e91375 100644
--- a/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java
@@ -47,31 +47,31 @@ import junit.framework.TestSuite;
* creates.
*
* <p>This test simulates the runtime behaviour of the ExtensionRegistryFactory by delegating test
- * definitions to two inner classes {@link InnerTest} and {@link InnerLiteTest}, the latter of
- * which is executed using a custom ClassLoader, simulating the ProtoLite environment.
+ * definitions to two inner classes {@link InnerTest} and {@link InnerLiteTest}, the latter of which
+ * is executed using a custom ClassLoader, simulating the ProtoLite environment.
*
- * <p>The test mechanism employed here is based on the pattern in
- * {@code com.google.common.util.concurrent.AbstractFutureFallbackAtomicHelperTest}
+ * <p>The test mechanism employed here is based on the pattern in {@code
+ * com.google.common.util.concurrent.AbstractFutureFallbackAtomicHelperTest}
*/
public class ExtensionRegistryFactoryTest extends TestCase {
// A classloader which blacklists some non-Lite classes.
private static final ClassLoader LITE_CLASS_LOADER = getLiteOnlyClassLoader();
- /**
- * Defines the set of test methods which will be run.
- */
+ /** Defines the set of test methods which will be run. */
static interface RegistryTests {
void testCreate();
+
void testEmpty();
+
void testIsFullRegistry();
+
void testAdd();
+
void testAdd_immutable();
}
- /**
- * Test implementations for the non-Lite usage of ExtensionRegistryFactory.
- */
+ /** Test implementations for the non-Lite usage of ExtensionRegistryFactory. */
public static class InnerTest implements RegistryTests {
@Override
@@ -108,20 +108,25 @@ public class ExtensionRegistryFactoryTest extends TestCase {
ExtensionRegistry fullRegistry1 = (ExtensionRegistry) registry1;
ExtensionRegistry fullRegistry2 = (ExtensionRegistry) registry2;
- assertTrue("Test is using a non-lite extension",
+ assertTrue(
+ "Test is using a non-lite extension",
GeneratedMessageLite.GeneratedExtension.class.isAssignableFrom(
NonNestedExtensionLite.nonNestedExtensionLite.getClass()));
- assertNull("Extension is not registered in masqueraded full registry",
+ assertNull(
+ "Extension is not registered in masqueraded full registry",
fullRegistry1.findImmutableExtensionByName("protobuf_unittest.nonNestedExtension"));
GeneratedMessageLite.GeneratedExtension<NonNestedExtensionLite.MessageLiteToBeExtended, ?>
- extension = registry1.findLiteExtensionByNumber(
- NonNestedExtensionLite.MessageLiteToBeExtended.getDefaultInstance(), 1);
+ extension =
+ registry1.findLiteExtensionByNumber(
+ NonNestedExtensionLite.MessageLiteToBeExtended.getDefaultInstance(), 1);
assertNotNull("Extension registered in lite registry", extension);
- assertTrue("Test is using a non-lite extension",
+ assertTrue(
+ "Test is using a non-lite extension",
GeneratedMessage.GeneratedExtension.class.isAssignableFrom(
- NonNestedExtension.nonNestedExtension.getClass()));
- assertNotNull("Extension is registered in masqueraded full registry",
+ NonNestedExtension.nonNestedExtension.getClass()));
+ assertNotNull(
+ "Extension is registered in masqueraded full registry",
fullRegistry2.findImmutableExtensionByName("protobuf_unittest.nonNestedExtension"));
}
@@ -131,27 +136,29 @@ public class ExtensionRegistryFactoryTest extends TestCase {
try {
NonNestedExtensionLite.registerAllExtensions(registry1);
fail();
- } catch (UnsupportedOperationException expected) {}
+ } catch (UnsupportedOperationException expected) {
+ }
try {
registry1.add(NonNestedExtensionLite.nonNestedExtensionLite);
fail();
- } catch (UnsupportedOperationException expected) {}
+ } catch (UnsupportedOperationException expected) {
+ }
ExtensionRegistryLite registry2 = ExtensionRegistryLite.newInstance().getUnmodifiable();
try {
NonNestedExtension.registerAllExtensions((ExtensionRegistry) registry2);
fail();
- } catch (IllegalArgumentException expected) {}
+ } catch (IllegalArgumentException expected) {
+ }
try {
registry2.add(NonNestedExtension.nonNestedExtension);
fail();
- } catch (IllegalArgumentException expected) {}
+ } catch (IllegalArgumentException expected) {
+ }
}
}
- /**
- * Test implementations for the Lite usage of ExtensionRegistryFactory.
- */
+ /** Test implementations for the Lite usage of ExtensionRegistryFactory. */
public static final class InnerLiteTest implements RegistryTests {
@Override
@@ -180,8 +187,9 @@ public class ExtensionRegistryFactoryTest extends TestCase {
ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance();
NonNestedExtensionLite.registerAllExtensions(registry);
GeneratedMessageLite.GeneratedExtension<NonNestedExtensionLite.MessageLiteToBeExtended, ?>
- extension = registry.findLiteExtensionByNumber(
- NonNestedExtensionLite.MessageLiteToBeExtended.getDefaultInstance(), 1);
+ extension =
+ registry.findLiteExtensionByNumber(
+ NonNestedExtensionLite.MessageLiteToBeExtended.getDefaultInstance(), 1);
assertNotNull("Extension is registered in Lite registry", extension);
}
@@ -191,13 +199,12 @@ public class ExtensionRegistryFactoryTest extends TestCase {
try {
NonNestedExtensionLite.registerAllExtensions(registry);
fail();
- } catch (UnsupportedOperationException expected) {}
+ } catch (UnsupportedOperationException expected) {
+ }
}
}
- /**
- * Defines a suite of tests which the JUnit3 runner retrieves by reflection.
- */
+ /** Defines a suite of tests which the JUnit3 runner retrieves by reflection. */
public static Test suite() {
TestSuite suite = new TestSuite();
for (Method method : RegistryTests.class.getMethods()) {
@@ -235,8 +242,8 @@ public class ExtensionRegistryFactoryTest extends TestCase {
}
/**
- * Constructs a custom ClassLoader blacklisting the classes which are inspected in the SUT
- * to determine the Lite/non-Lite runtime.
+ * Constructs a custom ClassLoader blacklisting the classes which are inspected in the SUT to
+ * determine the Lite/non-Lite runtime.
*/
private static ClassLoader getLiteOnlyClassLoader() {
ClassLoader testClassLoader = ExtensionRegistryFactoryTest.class.getClassLoader();
@@ -250,8 +257,8 @@ public class ExtensionRegistryFactoryTest extends TestCase {
// Construct a URLClassLoader delegating to the system ClassLoader, and looking up classes
// in jar files based on the URLs already configured for this test's UrlClassLoader.
// Certain classes throw a ClassNotFoundException by design.
- return new URLClassLoader(((URLClassLoader) testClassLoader).getURLs(),
- ClassLoader.getSystemClassLoader()) {
+ return new URLClassLoader(
+ ((URLClassLoader) testClassLoader).getURLs(), ClassLoader.getSystemClassLoader()) {
@Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
if (classNamesNotInLite.contains(name)) {
diff --git a/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java b/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java
index 42da5bb3..85a2fe08 100644
--- a/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java
+++ b/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java
@@ -38,12 +38,10 @@ import com.google.protobuf.FieldPresenceTestProto.TestAllTypes;
import com.google.protobuf.FieldPresenceTestProto.TestOptionalFieldsOnly;
import com.google.protobuf.FieldPresenceTestProto.TestRepeatedFieldsOnly;
import protobuf_unittest.UnittestProto;
-
import junit.framework.TestCase;
/**
- * Unit tests for protos that doesn't support field presence test for optional
- * non-message fields.
+ * Unit tests for protos that doesn't support field presence test for optional non-message fields.
*/
public class FieldPresenceTest extends TestCase {
private static boolean hasMethod(Class<?> clazz, String name) {
@@ -59,9 +57,7 @@ public class FieldPresenceTest extends TestCase {
}
private static void assertHasMethodRemoved(
- Class<?> classWithFieldPresence,
- Class<?> classWithoutFieldPresence,
- String camelName) {
+ Class<?> classWithFieldPresence, Class<?> classWithoutFieldPresence, String camelName) {
assertTrue(hasMethod(classWithFieldPresence, "get" + camelName));
assertTrue(hasMethod(classWithFieldPresence, "has" + camelName));
assertTrue(hasMethod(classWithoutFieldPresence, "get" + camelName));
@@ -70,72 +66,38 @@ public class FieldPresenceTest extends TestCase {
public void testHasMethod() {
// Optional non-message fields don't have a hasFoo() method generated.
+ assertHasMethodRemoved(UnittestProto.TestAllTypes.class, TestAllTypes.class, "OptionalInt32");
+ assertHasMethodRemoved(UnittestProto.TestAllTypes.class, TestAllTypes.class, "OptionalString");
+ assertHasMethodRemoved(UnittestProto.TestAllTypes.class, TestAllTypes.class, "OptionalBytes");
assertHasMethodRemoved(
- UnittestProto.TestAllTypes.class,
- TestAllTypes.class,
- "OptionalInt32");
- assertHasMethodRemoved(
- UnittestProto.TestAllTypes.class,
- TestAllTypes.class,
- "OptionalString");
- assertHasMethodRemoved(
- UnittestProto.TestAllTypes.class,
- TestAllTypes.class,
- "OptionalBytes");
- assertHasMethodRemoved(
- UnittestProto.TestAllTypes.class,
- TestAllTypes.class,
- "OptionalNestedEnum");
+ UnittestProto.TestAllTypes.class, TestAllTypes.class, "OptionalNestedEnum");
assertHasMethodRemoved(
- UnittestProto.TestAllTypes.Builder.class,
- TestAllTypes.Builder.class,
- "OptionalInt32");
+ UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OptionalInt32");
assertHasMethodRemoved(
- UnittestProto.TestAllTypes.Builder.class,
- TestAllTypes.Builder.class,
- "OptionalString");
+ UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OptionalString");
assertHasMethodRemoved(
- UnittestProto.TestAllTypes.Builder.class,
- TestAllTypes.Builder.class,
- "OptionalBytes");
+ UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OptionalBytes");
assertHasMethodRemoved(
- UnittestProto.TestAllTypes.Builder.class,
- TestAllTypes.Builder.class,
- "OptionalNestedEnum");
+ UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OptionalNestedEnum");
// message fields still have the hasFoo() method generated.
- assertFalse(TestAllTypes.newBuilder().build().hasOptionalNestedMessage());
+ assertFalse(TestAllTypes.getDefaultInstance().hasOptionalNestedMessage());
assertFalse(TestAllTypes.newBuilder().hasOptionalNestedMessage());
// oneof fields don't have hasFoo() methods for non-message types.
- assertHasMethodRemoved(
- UnittestProto.TestAllTypes.class,
- TestAllTypes.class,
- "OneofUint32");
- assertHasMethodRemoved(
- UnittestProto.TestAllTypes.class,
- TestAllTypes.class,
- "OneofString");
- assertHasMethodRemoved(
- UnittestProto.TestAllTypes.class,
- TestAllTypes.class,
- "OneofBytes");
- assertFalse(TestAllTypes.newBuilder().build().hasOneofNestedMessage());
+ assertHasMethodRemoved(UnittestProto.TestAllTypes.class, TestAllTypes.class, "OneofUint32");
+ assertHasMethodRemoved(UnittestProto.TestAllTypes.class, TestAllTypes.class, "OneofString");
+ assertHasMethodRemoved(UnittestProto.TestAllTypes.class, TestAllTypes.class, "OneofBytes");
+ assertFalse(TestAllTypes.getDefaultInstance().hasOneofNestedMessage());
assertFalse(TestAllTypes.newBuilder().hasOneofNestedMessage());
assertHasMethodRemoved(
- UnittestProto.TestAllTypes.Builder.class,
- TestAllTypes.Builder.class,
- "OneofUint32");
+ UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OneofUint32");
assertHasMethodRemoved(
- UnittestProto.TestAllTypes.Builder.class,
- TestAllTypes.Builder.class,
- "OneofString");
+ UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OneofString");
assertHasMethodRemoved(
- UnittestProto.TestAllTypes.Builder.class,
- TestAllTypes.Builder.class,
- "OneofBytes");
+ UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OneofBytes");
}
public void testOneofEquals() throws Exception {
@@ -200,10 +162,10 @@ public class FieldPresenceTest extends TestCase {
assertEquals(TestAllTypes.NestedEnum.BAR, message.getOptionalNestedEnum());
// equals()/hashCode() should produce the same results.
- TestAllTypes empty = TestAllTypes.newBuilder().build();
+ TestAllTypes empty = TestAllTypes.getDefaultInstance();
message = builder.build();
- assertTrue(empty.equals(message));
- assertTrue(message.equals(empty));
+ assertEquals(message, empty);
+ assertEquals(empty, message);
assertEquals(empty.hashCode(), message.hashCode());
}
@@ -215,7 +177,7 @@ public class FieldPresenceTest extends TestCase {
FieldDescriptor optionalNestedEnumField = descriptor.findFieldByName("optional_nested_enum");
// Field not present.
- TestAllTypes message = TestAllTypes.newBuilder().build();
+ TestAllTypes message = TestAllTypes.getDefaultInstance();
assertFalse(message.hasField(optionalInt32Field));
assertFalse(message.hasField(optionalStringField));
assertFalse(message.hasField(optionalBytesField));
@@ -223,12 +185,13 @@ public class FieldPresenceTest extends TestCase {
assertEquals(0, message.getAllFields().size());
// Field set to default value is seen as not present.
- message = TestAllTypes.newBuilder()
- .setOptionalInt32(0)
- .setOptionalString("")
- .setOptionalBytes(ByteString.EMPTY)
- .setOptionalNestedEnum(TestAllTypes.NestedEnum.FOO)
- .build();
+ message =
+ TestAllTypes.newBuilder()
+ .setOptionalInt32(0)
+ .setOptionalString("")
+ .setOptionalBytes(ByteString.EMPTY)
+ .setOptionalNestedEnum(TestAllTypes.NestedEnum.FOO)
+ .build();
assertFalse(message.hasField(optionalInt32Field));
assertFalse(message.hasField(optionalStringField));
assertFalse(message.hasField(optionalBytesField));
@@ -236,12 +199,13 @@ public class FieldPresenceTest extends TestCase {
assertEquals(0, message.getAllFields().size());
// Field set to non-default value is seen as present.
- message = TestAllTypes.newBuilder()
- .setOptionalInt32(1)
- .setOptionalString("x")
- .setOptionalBytes(ByteString.copyFromUtf8("y"))
- .setOptionalNestedEnum(TestAllTypes.NestedEnum.BAR)
- .build();
+ message =
+ TestAllTypes.newBuilder()
+ .setOptionalInt32(1)
+ .setOptionalString("x")
+ .setOptionalBytes(ByteString.copyFromUtf8("y"))
+ .setOptionalNestedEnum(TestAllTypes.NestedEnum.BAR)
+ .build();
assertTrue(message.hasField(optionalInt32Field));
assertTrue(message.hasField(optionalStringField));
assertTrue(message.hasField(optionalBytesField));
@@ -284,7 +248,9 @@ public class FieldPresenceTest extends TestCase {
assertEquals(4, message.getAllFields().size());
// Field set to default value is seen as not present.
- message = message.toBuilder()
+ message =
+ message
+ .toBuilder()
.setField(optionalInt32Field, 0)
.setField(optionalStringField, "")
.setField(optionalBytesField, ByteString.EMPTY)
@@ -302,8 +268,7 @@ public class FieldPresenceTest extends TestCase {
assertFalse(builder.hasOptionalNestedMessage());
assertFalse(builder.build().hasOptionalNestedMessage());
- TestAllTypes.NestedMessage.Builder nestedBuilder =
- builder.getOptionalNestedMessageBuilder();
+ TestAllTypes.NestedMessage.Builder nestedBuilder = builder.getOptionalNestedMessageBuilder();
assertTrue(builder.hasOptionalNestedMessage());
assertTrue(builder.build().hasOptionalNestedMessage());
@@ -341,8 +306,7 @@ public class FieldPresenceTest extends TestCase {
assertTrue(message.hasOptionalNestedMessage());
assertEquals(0, message.getOptionalNestedMessage().getValue());
// The oneof field set to its default value is also present.
- assertEquals(
- TestAllTypes.OneofFieldCase.ONEOF_INT32, message.getOneofFieldCase());
+ assertEquals(TestAllTypes.OneofFieldCase.ONEOF_INT32, message.getOneofFieldCase());
}
// Regression test for b/16173397
@@ -376,8 +340,7 @@ public class FieldPresenceTest extends TestCase {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
// Test optional proto2 message fields.
- UnittestProto.TestRequired.Builder proto2Builder =
- builder.getOptionalProto2MessageBuilder();
+ UnittestProto.TestRequired.Builder proto2Builder = builder.getOptionalProto2MessageBuilder();
assertFalse(builder.isInitialized());
assertFalse(builder.buildPartial().isInitialized());
diff --git a/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java b/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java
index 38eccc93..7ed61340 100644
--- a/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java
@@ -45,10 +45,8 @@ import junit.framework.TestCase;
*/
public class FloatArrayListTest extends TestCase {
- private static final FloatArrayList UNARY_LIST =
- newImmutableFloatArrayList(1);
- private static final FloatArrayList TERTIARY_LIST =
- newImmutableFloatArrayList(1, 2, 3);
+ private static final FloatArrayList UNARY_LIST = newImmutableFloatArrayList(1);
+ private static final FloatArrayList TERTIARY_LIST = newImmutableFloatArrayList(1, 2, 3);
private FloatArrayList list;
@@ -225,9 +223,7 @@ public class FloatArrayListTest extends TestCase {
for (int i = 0; i < 6; i++) {
list.add(Float.valueOf(5 + i));
}
- assertEquals(
- asList(0F, 1F, 4F, 2F, 3F, 5F, 6F, 7F, 8F, 9F, 10F),
- list);
+ assertEquals(asList(0F, 1F, 4F, 2F, 3F, 5F, 6F, 7F, 8F, 9F, 10F), list);
try {
list.add(-1, 5F);
@@ -299,16 +295,14 @@ public class FloatArrayListTest extends TestCase {
}
public void testRemoveEndOfCapacity() {
- FloatList toRemove =
- FloatArrayList.emptyList().mutableCopyWithCapacity(1);
+ FloatList toRemove = FloatArrayList.emptyList().mutableCopyWithCapacity(1);
toRemove.addFloat(3);
toRemove.remove(0);
assertEquals(0, toRemove.size());
}
public void testSublistRemoveEndOfCapacity() {
- FloatList toRemove =
- FloatArrayList.emptyList().mutableCopyWithCapacity(1);
+ FloatList toRemove = FloatArrayList.emptyList().mutableCopyWithCapacity(1);
toRemove.addFloat(3);
toRemove.subList(0, 1).clear();
assertEquals(0, toRemove.size());
diff --git a/java/core/src/test/java/com/google/protobuf/ForceFieldBuildersPreRun.java b/java/core/src/test/java/com/google/protobuf/ForceFieldBuildersPreRun.java
index b7eaebf5..baa6d086 100644
--- a/java/core/src/test/java/com/google/protobuf/ForceFieldBuildersPreRun.java
+++ b/java/core/src/test/java/com/google/protobuf/ForceFieldBuildersPreRun.java
@@ -31,11 +31,10 @@
package com.google.protobuf;
/**
- * A prerun for a test suite that allows running the full protocol buffer
- * tests in a mode that disables the optimization for not using
- * {@link RepeatedFieldBuilder} and {@link SingleFieldBuilder} until they are
- * requested. This allows us to run all the tests through both code paths
- * and ensures that both code paths produce identical results.
+ * A prerun for a test suite that allows running the full protocol buffer tests in a mode that
+ * disables the optimization for not using {@link RepeatedFieldBuilder} and {@link
+ * SingleFieldBuilder} until they are requested. This allows us to run all the tests through both
+ * code paths and ensures that both code paths produce identical results.
*
* @author jonp@google.com (Jon Perlow)
*/
diff --git a/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java b/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java
index 4489dace..13457bc0 100644
--- a/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java
+++ b/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java
@@ -32,7 +32,6 @@ package com.google.protobuf;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
-import com.google.protobuf.Int32Value;
import com.google.protobuf.test.UnittestImport;
import protobuf_unittest.EnumWithNoOuter;
import protobuf_unittest.MessageWithNoOuter;
@@ -72,20 +71,21 @@ import java.util.List;
import junit.framework.TestCase;
/**
- * Unit test for generated messages and generated code. See also
- * {@link MessageTest}, which tests some generated message functionality.
+ * Unit test for generated messages and generated code. See also {@link MessageTest}, which tests
+ * some generated message functionality.
*
* @author kenton@google.com Kenton Varda
*/
public class GeneratedMessageTest extends TestCase {
TestUtil.ReflectionTester reflectionTester =
- new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);
+ new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);
public void testDefaultInstance() throws Exception {
- assertSame(TestAllTypes.getDefaultInstance(),
- TestAllTypes.getDefaultInstance().getDefaultInstanceForType());
- assertSame(TestAllTypes.getDefaultInstance(),
- TestAllTypes.newBuilder().getDefaultInstanceForType());
+ assertSame(
+ TestAllTypes.getDefaultInstance(),
+ TestAllTypes.getDefaultInstance().getDefaultInstanceForType());
+ assertSame(
+ TestAllTypes.getDefaultInstance(), TestAllTypes.newBuilder().getDefaultInstanceForType());
}
public void testMessageOrBuilder() throws Exception {
@@ -111,10 +111,8 @@ public class GeneratedMessageTest extends TestCase {
assertEquals(100, value1.getOptionalSfixed64());
assertEquals(100, value1.getRepeatedInt32(0));
- assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
- value1.getOptionalImportEnum());
- assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
- value1.getRepeatedImportEnum(0));
+ assertEquals(UnittestImport.ImportEnum.IMPORT_BAR, value1.getOptionalImportEnum());
+ assertEquals(UnittestImport.ImportEnum.IMPORT_BAR, value1.getRepeatedImportEnum(0));
assertEquals(1, value1.getOptionalForeignMessage().getC());
assertEquals(1, value1.getRepeatedForeignMessage(0).getC());
@@ -131,20 +129,16 @@ public class GeneratedMessageTest extends TestCase {
// Make sure value1 didn't change.
assertEquals(100, value1.getOptionalSfixed64());
assertEquals(100, value1.getRepeatedInt32(0));
- assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
- value1.getOptionalImportEnum());
- assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
- value1.getRepeatedImportEnum(0));
+ assertEquals(UnittestImport.ImportEnum.IMPORT_BAR, value1.getOptionalImportEnum());
+ assertEquals(UnittestImport.ImportEnum.IMPORT_BAR, value1.getRepeatedImportEnum(0));
assertEquals(1, value1.getOptionalForeignMessage().getC());
assertEquals(1, value1.getRepeatedForeignMessage(0).getC());
// Make sure value2 is correct
assertEquals(200, value2.getOptionalSfixed64());
assertEquals(200, value2.getRepeatedInt32(0));
- assertEquals(UnittestImport.ImportEnum.IMPORT_FOO,
- value2.getOptionalImportEnum());
- assertEquals(UnittestImport.ImportEnum.IMPORT_FOO,
- value2.getRepeatedImportEnum(0));
+ assertEquals(UnittestImport.ImportEnum.IMPORT_FOO, value2.getOptionalImportEnum());
+ assertEquals(UnittestImport.ImportEnum.IMPORT_FOO, value2.getRepeatedImportEnum(0));
assertEquals(2, value2.getOptionalForeignMessage().getC());
assertEquals(2, value2.getRepeatedForeignMessage(0).getC());
}
@@ -158,8 +152,7 @@ public class GeneratedMessageTest extends TestCase {
TestAllTypes value2 = value1.toBuilder().build();
assertSame(value1.getRepeatedInt32List(), value2.getRepeatedInt32List());
- assertSame(value1.getRepeatedForeignMessageList(),
- value2.getRepeatedForeignMessageList());
+ assertSame(value1.getRepeatedForeignMessageList(), value2.getRepeatedForeignMessageList());
}
public void testRepeatedArraysAreImmutable() throws Exception {
@@ -172,7 +165,6 @@ public class GeneratedMessageTest extends TestCase {
assertIsUnmodifiable(builder.getRepeatedForeignMessageList());
assertIsUnmodifiable(builder.getRepeatedFloatList());
-
TestAllTypes value = builder.build();
assertIsUnmodifiable(value.getRepeatedInt32List());
assertIsUnmodifiable(value.getRepeatedImportEnumList());
@@ -240,8 +232,7 @@ public class GeneratedMessageTest extends TestCase {
// We expect this exception.
}
try {
- builder.setOptionalNestedMessage(
- (TestAllTypes.NestedMessage.Builder) null);
+ builder.setOptionalNestedMessage((TestAllTypes.NestedMessage.Builder) null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
@@ -271,8 +262,7 @@ public class GeneratedMessageTest extends TestCase {
// We expect this exception.
}
try {
- builder.addRepeatedNestedMessage(
- (TestAllTypes.NestedMessage.Builder) null);
+ builder.addRepeatedNestedMessage((TestAllTypes.NestedMessage.Builder) null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
@@ -314,10 +304,8 @@ public class GeneratedMessageTest extends TestCase {
// We expect this exception.
}
- builder.addRepeatedNestedMessage(
- TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
- builder.addRepeatedNestedMessage(
- TestAllTypes.NestedMessage.newBuilder().setBb(456).build());
+ builder.addRepeatedNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
+ builder.addRepeatedNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(456).build());
try {
builder.setRepeatedNestedMessage(1, (TestAllTypes.NestedMessage) null);
fail("Exception was not thrown");
@@ -325,8 +313,7 @@ public class GeneratedMessageTest extends TestCase {
// We expect this exception.
}
try {
- builder.setRepeatedNestedMessage(
- 1, (TestAllTypes.NestedMessage.Builder) null);
+ builder.setRepeatedNestedMessage(1, (TestAllTypes.NestedMessage.Builder) null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
@@ -348,14 +335,12 @@ public class GeneratedMessageTest extends TestCase {
builder.addAllRepeatedInt32(Arrays.asList(1, 2, 3, 4));
builder.addAllRepeatedForeignEnum(Arrays.asList(ForeignEnum.FOREIGN_BAZ));
- ForeignMessage foreignMessage =
- ForeignMessage.newBuilder().setC(12).build();
+ ForeignMessage foreignMessage = ForeignMessage.newBuilder().setC(12).build();
builder.addAllRepeatedForeignMessage(Arrays.asList(foreignMessage));
TestAllTypes message = builder.build();
assertEquals(message.getRepeatedInt32List(), Arrays.asList(1, 2, 3, 4));
- assertEquals(message.getRepeatedForeignEnumList(),
- Arrays.asList(ForeignEnum.FOREIGN_BAZ));
+ assertEquals(message.getRepeatedForeignEnumList(), Arrays.asList(ForeignEnum.FOREIGN_BAZ));
assertEquals(1, message.getRepeatedForeignMessageCount());
assertEquals(12, message.getRepeatedForeignMessage(0).getC());
}
@@ -363,19 +348,16 @@ public class GeneratedMessageTest extends TestCase {
public void testRepeatedAppendRejectsNull() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
- ForeignMessage foreignMessage =
- ForeignMessage.newBuilder().setC(12).build();
+ ForeignMessage foreignMessage = ForeignMessage.newBuilder().setC(12).build();
try {
- builder.addAllRepeatedForeignMessage(
- Arrays.asList(foreignMessage, (ForeignMessage) null));
+ builder.addAllRepeatedForeignMessage(Arrays.asList(foreignMessage, (ForeignMessage) null));
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
try {
- builder.addAllRepeatedForeignEnum(
- Arrays.asList(ForeignEnum.FOREIGN_BAZ, null));
+ builder.addAllRepeatedForeignEnum(Arrays.asList(ForeignEnum.FOREIGN_BAZ, null));
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
@@ -395,20 +377,22 @@ public class GeneratedMessageTest extends TestCase {
// We expect this exception.
}
}
-
+
public void testRepeatedAppendIterateOnlyOnce() throws Exception {
// Create a Iterable that can only be iterated once.
- Iterable<String> stringIterable = new Iterable<String>() {
- private boolean called = false;
- @Override
- public Iterator<String> iterator() {
- if (called) {
- throw new IllegalStateException();
- }
- called = true;
- return Arrays.asList("one", "two", "three").iterator();
- }
- };
+ Iterable<String> stringIterable =
+ new Iterable<String>() {
+ private boolean called = false;
+
+ @Override
+ public Iterator<String> iterator() {
+ if (called) {
+ throw new IllegalStateException();
+ }
+ called = true;
+ return Arrays.asList("one", "two", "three").iterator();
+ }
+ };
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
builder.addAllRepeatedString(stringIterable);
assertEquals(3, builder.getRepeatedStringCount());
@@ -435,29 +419,31 @@ public class GeneratedMessageTest extends TestCase {
}
public void testSettingForeignMessageUsingBuilder() throws Exception {
- TestAllTypes message = TestAllTypes.newBuilder()
- // Pass builder for foreign message instance.
- .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(123))
- .build();
- TestAllTypes expectedMessage = TestAllTypes.newBuilder()
- // Create expected version passing foreign message instance explicitly.
- .setOptionalForeignMessage(
- ForeignMessage.newBuilder().setC(123).build())
- .build();
+ TestAllTypes message =
+ TestAllTypes.newBuilder()
+ // Pass builder for foreign message instance.
+ .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(123))
+ .build();
+ TestAllTypes expectedMessage =
+ TestAllTypes.newBuilder()
+ // Create expected version passing foreign message instance explicitly.
+ .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(123).build())
+ .build();
// TODO(ngd): Upgrade to using real #equals method once implemented
assertEquals(expectedMessage.toString(), message.toString());
}
public void testSettingRepeatedForeignMessageUsingBuilder() throws Exception {
- TestAllTypes message = TestAllTypes.newBuilder()
- // Pass builder for foreign message instance.
- .addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(456))
- .build();
- TestAllTypes expectedMessage = TestAllTypes.newBuilder()
- // Create expected version passing foreign message instance explicitly.
- .addRepeatedForeignMessage(
- ForeignMessage.newBuilder().setC(456).build())
- .build();
+ TestAllTypes message =
+ TestAllTypes.newBuilder()
+ // Pass builder for foreign message instance.
+ .addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(456))
+ .build();
+ TestAllTypes expectedMessage =
+ TestAllTypes.newBuilder()
+ // Create expected version passing foreign message instance explicitly.
+ .addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(456).build())
+ .build();
assertEquals(expectedMessage.toString(), message.toString());
}
@@ -465,14 +451,13 @@ public class GeneratedMessageTest extends TestCase {
TestUtil.assertClear(TestAllTypes.getDefaultInstance());
TestUtil.assertClear(TestAllTypes.newBuilder().build());
- TestExtremeDefaultValues message =
- TestExtremeDefaultValues.getDefaultInstance();
+ TestExtremeDefaultValues message = TestExtremeDefaultValues.getDefaultInstance();
assertEquals("\u1234", message.getUtf8String());
- assertEquals(Double.POSITIVE_INFINITY, message.getInfDouble());
- assertEquals(Double.NEGATIVE_INFINITY, message.getNegInfDouble());
+ assertEquals(Double.POSITIVE_INFINITY, message.getInfDouble(), 0.0);
+ assertEquals(Double.NEGATIVE_INFINITY, message.getNegInfDouble(), 0.0);
assertTrue(Double.isNaN(message.getNanDouble()));
- assertEquals(Float.POSITIVE_INFINITY, message.getInfFloat());
- assertEquals(Float.NEGATIVE_INFINITY, message.getNegInfFloat());
+ assertEquals(Float.POSITIVE_INFINITY, message.getInfFloat(), 0.0f);
+ assertEquals(Float.NEGATIVE_INFINITY, message.getNegInfFloat(), 0.0f);
assertTrue(Float.isNaN(message.getNanFloat()));
assertEquals("? ? ?? ?? ??? ??/ ??-", message.getCppTrigraph());
}
@@ -524,19 +509,15 @@ public class GeneratedMessageTest extends TestCase {
}
public void testReflectionDefaults() throws Exception {
- reflectionTester.assertClearViaReflection(
- TestAllTypes.getDefaultInstance());
- reflectionTester.assertClearViaReflection(
- TestAllTypes.newBuilder().build());
+ reflectionTester.assertClearViaReflection(TestAllTypes.getDefaultInstance());
+ reflectionTester.assertClearViaReflection(TestAllTypes.newBuilder().build());
}
public void testReflectionGetOneof() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
reflectionTester.setAllFieldsViaReflection(builder);
- Descriptors.OneofDescriptor oneof =
- TestAllTypes.getDescriptor().getOneofs().get(0);
- Descriptors.FieldDescriptor field =
- TestAllTypes.getDescriptor().findFieldByName("oneof_bytes");
+ Descriptors.OneofDescriptor oneof = TestAllTypes.getDescriptor().getOneofs().get(0);
+ Descriptors.FieldDescriptor field = TestAllTypes.getDescriptor().findFieldByName("oneof_bytes");
assertSame(field, builder.getOneofFieldDescriptor(oneof));
TestAllTypes message = builder.build();
@@ -546,10 +527,8 @@ public class GeneratedMessageTest extends TestCase {
public void testReflectionClearOneof() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
reflectionTester.setAllFieldsViaReflection(builder);
- Descriptors.OneofDescriptor oneof =
- TestAllTypes.getDescriptor().getOneofs().get(0);
- Descriptors.FieldDescriptor field =
- TestAllTypes.getDescriptor().findFieldByName("oneof_bytes");
+ Descriptors.OneofDescriptor oneof = TestAllTypes.getDescriptor().getOneofs().get(0);
+ Descriptors.FieldDescriptor field = TestAllTypes.getDescriptor().findFieldByName("oneof_bytes");
assertTrue(builder.hasOneof(oneof));
assertTrue(builder.hasField(field));
@@ -559,8 +538,8 @@ public class GeneratedMessageTest extends TestCase {
}
public void testEnumInterface() throws Exception {
- assertTrue(TestAllTypes.getDefaultInstance().getDefaultNestedEnum()
- instanceof ProtocolMessageEnum);
+ assertTrue(
+ TestAllTypes.getDefaultInstance().getDefaultNestedEnum() instanceof ProtocolMessageEnum);
}
public void testEnumMap() throws Exception {
@@ -575,15 +554,13 @@ public class GeneratedMessageTest extends TestCase {
public void testParsePackedToUnpacked() throws Exception {
TestUnpackedTypes.Builder builder = TestUnpackedTypes.newBuilder();
- TestUnpackedTypes message =
- builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
+ TestUnpackedTypes message = builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
TestUtil.assertUnpackedFieldsSet(message);
}
public void testParseUnpackedToPacked() throws Exception {
TestPackedTypes.Builder builder = TestPackedTypes.newBuilder();
- TestPackedTypes message =
- builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
+ TestPackedTypes message = builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
TestUtil.assertPackedFieldsSet(message);
}
@@ -662,32 +639,29 @@ public class GeneratedMessageTest extends TestCase {
TestUtil.assertRepeatedExtensionsModified(message);
}
- public void testExtensionReflectionRepeatedSettersRejectNull()
- throws Exception {
+ public void testExtensionReflectionRepeatedSettersRejectNull() throws Exception {
TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
- extensionsReflectionTester.assertReflectionRepeatedSettersRejectNull(
- builder);
+ extensionsReflectionTester.assertReflectionRepeatedSettersRejectNull(builder);
}
public void testExtensionReflectionDefaults() throws Exception {
- extensionsReflectionTester.assertClearViaReflection(
- TestAllExtensions.getDefaultInstance());
- extensionsReflectionTester.assertClearViaReflection(
- TestAllExtensions.newBuilder().build());
+ extensionsReflectionTester.assertClearViaReflection(TestAllExtensions.getDefaultInstance());
+ extensionsReflectionTester.assertClearViaReflection(TestAllExtensions.newBuilder().build());
}
public void testClearExtension() throws Exception {
// clearExtension() is not actually used in TestUtil, so try it manually.
assertFalse(
- TestAllExtensions.newBuilder()
- .setExtension(UnittestProto.optionalInt32Extension, 1)
- .clearExtension(UnittestProto.optionalInt32Extension)
- .hasExtension(UnittestProto.optionalInt32Extension));
- assertEquals(0,
- TestAllExtensions.newBuilder()
- .addExtension(UnittestProto.repeatedInt32Extension, 1)
- .clearExtension(UnittestProto.repeatedInt32Extension)
- .getExtensionCount(UnittestProto.repeatedInt32Extension));
+ TestAllExtensions.newBuilder()
+ .setExtension(UnittestProto.optionalInt32Extension, 1)
+ .clearExtension(UnittestProto.optionalInt32Extension)
+ .hasExtension(UnittestProto.optionalInt32Extension));
+ assertEquals(
+ 0,
+ TestAllExtensions.newBuilder()
+ .addExtension(UnittestProto.repeatedInt32Extension, 1)
+ .clearExtension(UnittestProto.repeatedInt32Extension)
+ .getExtensionCount(UnittestProto.repeatedInt32Extension));
}
public void testExtensionCopy() throws Exception {
@@ -698,13 +672,12 @@ public class GeneratedMessageTest extends TestCase {
public void testExtensionMergeFrom() throws Exception {
TestAllExtensions original =
- TestAllExtensions.newBuilder()
- .setExtension(UnittestProto.optionalInt32Extension, 1).build();
- TestAllExtensions merged =
- TestAllExtensions.newBuilder().mergeFrom(original).build();
+ TestAllExtensions.newBuilder()
+ .setExtension(UnittestProto.optionalInt32Extension, 1)
+ .build();
+ TestAllExtensions merged = TestAllExtensions.newBuilder().mergeFrom(original).build();
assertTrue(merged.hasExtension(UnittestProto.optionalInt32Extension));
- assertEquals(
- 1, (int) merged.getExtension(UnittestProto.optionalInt32Extension));
+ assertEquals(1, (int) merged.getExtension(UnittestProto.optionalInt32Extension));
}
// =================================================================
@@ -715,64 +688,69 @@ public class GeneratedMessageTest extends TestCase {
// or messages defined in multiple_files_test.proto because the class loading
// order affects initialization process of custom options.
public void testEnumValueOptionsInMultipleFilesMode() throws Exception {
- assertEquals(12345, EnumWithNoOuter.FOO.getValueDescriptor().getOptions()
- .getExtension(MultipleFilesTestProto.enumValueOption).intValue());
+ assertEquals(
+ 12345,
+ EnumWithNoOuter.FOO
+ .getValueDescriptor()
+ .getOptions()
+ .getExtension(MultipleFilesTestProto.enumValueOption)
+ .intValue());
}
public void testMultipleFilesOption() throws Exception {
// We mostly just want to check that things compile.
MessageWithNoOuter message =
- MessageWithNoOuter.newBuilder()
- .setNested(MessageWithNoOuter.NestedMessage.newBuilder().setI(1))
- .addForeign(TestAllTypes.newBuilder().setOptionalInt32(1))
- .setNestedEnum(MessageWithNoOuter.NestedEnum.BAZ)
- .setForeignEnum(EnumWithNoOuter.BAR)
- .build();
+ MessageWithNoOuter.newBuilder()
+ .setNested(MessageWithNoOuter.NestedMessage.newBuilder().setI(1))
+ .addForeign(TestAllTypes.newBuilder().setOptionalInt32(1))
+ .setNestedEnum(MessageWithNoOuter.NestedEnum.BAZ)
+ .setForeignEnum(EnumWithNoOuter.BAR)
+ .build();
assertEquals(message, MessageWithNoOuter.parseFrom(message.toByteString()));
- assertEquals(MultipleFilesTestProto.getDescriptor(),
- MessageWithNoOuter.getDescriptor().getFile());
+ assertEquals(
+ MultipleFilesTestProto.getDescriptor(), MessageWithNoOuter.getDescriptor().getFile());
Descriptors.FieldDescriptor field =
- MessageWithNoOuter.getDescriptor().findFieldByName("foreign_enum");
- assertEquals(EnumWithNoOuter.BAR.getValueDescriptor(),
- message.getField(field));
+ MessageWithNoOuter.getDescriptor().findFieldByName("foreign_enum");
+ assertEquals(EnumWithNoOuter.BAR.getValueDescriptor(), message.getField(field));
- assertEquals(MultipleFilesTestProto.getDescriptor(),
- ServiceWithNoOuter.getDescriptor().getFile());
+ assertEquals(
+ MultipleFilesTestProto.getDescriptor(), ServiceWithNoOuter.getDescriptor().getFile());
assertFalse(
- TestAllExtensions.getDefaultInstance().hasExtension(
- MultipleFilesTestProto.extensionWithOuter));
+ TestAllExtensions.getDefaultInstance()
+ .hasExtension(MultipleFilesTestProto.extensionWithOuter));
}
- public void testOptionalFieldWithRequiredSubfieldsOptimizedForSize()
- throws Exception {
- TestOptionalOptimizedForSize message =
- TestOptionalOptimizedForSize.getDefaultInstance();
+ public void testOptionalFieldWithRequiredSubfieldsOptimizedForSize() throws Exception {
+ TestOptionalOptimizedForSize message = TestOptionalOptimizedForSize.getDefaultInstance();
assertTrue(message.isInitialized());
- message = TestOptionalOptimizedForSize.newBuilder().setO(
- TestRequiredOptimizedForSize.newBuilder().buildPartial()
- ).buildPartial();
+ message =
+ TestOptionalOptimizedForSize.newBuilder()
+ .setO(TestRequiredOptimizedForSize.newBuilder().buildPartial())
+ .buildPartial();
assertFalse(message.isInitialized());
- message = TestOptionalOptimizedForSize.newBuilder().setO(
- TestRequiredOptimizedForSize.newBuilder().setX(5).buildPartial()
- ).buildPartial();
+ message =
+ TestOptionalOptimizedForSize.newBuilder()
+ .setO(TestRequiredOptimizedForSize.newBuilder().setX(5).buildPartial())
+ .buildPartial();
assertTrue(message.isInitialized());
}
- public void testUninitializedExtensionInOptimizedForSize()
- throws Exception {
+ public void testUninitializedExtensionInOptimizedForSize() throws Exception {
TestOptimizedForSize.Builder builder = TestOptimizedForSize.newBuilder();
- builder.setExtension(TestOptimizedForSize.testExtension2,
+ builder.setExtension(
+ TestOptimizedForSize.testExtension2,
TestRequiredOptimizedForSize.newBuilder().buildPartial());
assertFalse(builder.isInitialized());
assertFalse(builder.buildPartial().isInitialized());
builder = TestOptimizedForSize.newBuilder();
- builder.setExtension(TestOptimizedForSize.testExtension2,
+ builder.setExtension(
+ TestOptimizedForSize.testExtension2,
TestRequiredOptimizedForSize.newBuilder().setX(10).buildPartial());
assertTrue(builder.isInitialized());
assertTrue(builder.buildPartial().isInitialized());
@@ -803,13 +781,11 @@ public class GeneratedMessageTest extends TestCase {
assertEquals(UnittestProto.TestRequired.MULTI_FIELD_NUMBER, 1001);
assertEquals(UnittestProto.OPTIONAL_INT32_EXTENSION_FIELD_NUMBER, 1);
assertEquals(UnittestProto.OPTIONALGROUP_EXTENSION_FIELD_NUMBER, 16);
- assertEquals(
- UnittestProto.OPTIONAL_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 18);
+ assertEquals(UnittestProto.OPTIONAL_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 18);
assertEquals(UnittestProto.OPTIONAL_NESTED_ENUM_EXTENSION_FIELD_NUMBER, 21);
assertEquals(UnittestProto.REPEATED_INT32_EXTENSION_FIELD_NUMBER, 31);
assertEquals(UnittestProto.REPEATEDGROUP_EXTENSION_FIELD_NUMBER, 46);
- assertEquals(
- UnittestProto.REPEATED_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 48);
+ assertEquals(UnittestProto.REPEATED_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 48);
assertEquals(UnittestProto.REPEATED_NESTED_ENUM_EXTENSION_FIELD_NUMBER, 51);
}
@@ -818,7 +794,7 @@ public class GeneratedMessageTest extends TestCase {
UnittestProto.TestRecursiveMessage.getDefaultInstance();
assertTrue(message != null);
assertNotNull(message.getA());
- assertTrue(message.getA() == message);
+ assertTrue(message.getA().equals(message));
}
public void testSerialize() throws Exception {
@@ -859,21 +835,19 @@ public class GeneratedMessageTest extends TestCase {
// just includes messageClassName and asBytes
// Int32Value.newBuilder().setValue(123).build()
- byte[] int32ValueBytes = new byte[]{
- -84, -19, 0, 5, 115, 114, 0, 55, 99, 111, 109, 46, 103, 111, 111,
- 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 71,
- 101, 110, 101, 114, 97, 116, 101, 100, 77, 101, 115, 115, 97, 103,
- 101, 76, 105, 116, 101, 36, 83, 101, 114, 105, 97, 108, 105, 122,
- 101, 100, 70, 111, 114, 109, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 91,
- 0, 7, 97, 115, 66, 121, 116, 101, 115, 116, 0, 2, 91, 66, 76, 0,
- 16, 109, 101, 115, 115, 97, 103, 101, 67, 108, 97, 115, 115, 78,
- 97, 109, 101, 116, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110,
- 103, 47, 83, 116, 114, 105, 110, 103, 59, 120, 112, 117, 114, 0,
- 2, 91, 66, -84, -13, 23, -8, 6, 8, 84, -32, 2, 0, 0, 120, 112, 0,
- 0, 0, 2, 8, 123, 116, 0, 30, 99, 111, 109, 46, 103, 111, 111, 103,
- 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 73, 110,
- 116, 51, 50, 86, 97, 108, 117, 101
- };
+ byte[] int32ValueBytes =
+ new byte[] {
+ -84, -19, 0, 5, 115, 114, 0, 55, 99, 111, 109, 46, 103, 111, 111, 103, 108, 101, 46, 112,
+ 114, 111, 116, 111, 98, 117, 102, 46, 71, 101, 110, 101, 114, 97, 116, 101, 100, 77, 101,
+ 115, 115, 97, 103, 101, 76, 105, 116, 101, 36, 83, 101, 114, 105, 97, 108, 105, 122, 101,
+ 100, 70, 111, 114, 109, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 91, 0, 7, 97, 115, 66, 121, 116,
+ 101, 115, 116, 0, 2, 91, 66, 76, 0, 16, 109, 101, 115, 115, 97, 103, 101, 67, 108, 97,
+ 115, 115, 78, 97, 109, 101, 116, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47,
+ 83, 116, 114, 105, 110, 103, 59, 120, 112, 117, 114, 0, 2, 91, 66, -84, -13, 23, -8, 6, 8,
+ 84, -32, 2, 0, 0, 120, 112, 0, 0, 0, 2, 8, 123, 116, 0, 30, 99, 111, 109, 46, 103, 111,
+ 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 73, 110, 116, 51, 50,
+ 86, 97, 108, 117, 101
+ };
ByteArrayInputStream bais = new ByteArrayInputStream(int32ValueBytes);
ObjectInputStream in = new ObjectInputStream(bais);
@@ -886,36 +860,30 @@ public class GeneratedMessageTest extends TestCase {
// includes messageClass, messageClassName (for compatibility), and asBytes
// Int32Value.newBuilder().setValue(123).build()
- byte[] int32ValueBytes = new byte[]{
- -84, -19, 0, 5, 115, 114, 0, 55, 99, 111, 109, 46, 103, 111, 111,
- 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 71,
- 101, 110, 101, 114, 97, 116, 101, 100, 77, 101, 115, 115, 97, 103,
- 101, 76, 105, 116, 101, 36, 83, 101, 114, 105, 97, 108, 105, 122,
- 101, 100, 70, 111, 114, 109, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 91,
- 0, 7, 97, 115, 66, 121, 116, 101, 115, 116, 0, 2, 91, 66, 76, 0,
- 12, 109, 101, 115, 115, 97, 103, 101, 67, 108, 97, 115, 115, 116,
- 0, 17, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 67, 108,
- 97, 115, 115, 59, 76, 0, 16, 109, 101, 115, 115, 97, 103, 101, 67,
- 108, 97, 115, 115, 78, 97, 109, 101, 116, 0, 18, 76, 106, 97, 118,
- 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59,
- 120, 112, 117, 114, 0, 2, 91, 66, -84, -13, 23, -8, 6, 8, 84, -32,
- 2, 0, 0, 120, 112, 0, 0, 0, 2, 8, 123, 118, 114, 0, 30, 99, 111,
- 109, 46, 103, 111, 111, 103, 108, 101, 46, 112, 114, 111, 116, 111,
- 98, 117, 102, 46, 73, 110, 116, 51, 50, 86, 97, 108, 117, 101, 0, 0,
- 0, 0, 0, 0, 0, 0, 2, 0, 2, 66, 0, 21, 109, 101, 109, 111, 105, 122,
- 101, 100, 73, 115, 73, 110, 105, 116, 105, 97, 108, 105, 122, 101,
- 100, 73, 0, 6, 118, 97, 108, 117, 101, 95, 120, 114, 0, 38, 99, 111,
- 109, 46, 103, 111, 111, 103, 108, 101, 46, 112, 114, 111, 116, 111,
- 98, 117, 102, 46, 71, 101, 110, 101, 114, 97, 116, 101, 100, 77,
- 101, 115, 115, 97, 103, 101, 86, 51, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0,
- 1, 76, 0, 13, 117, 110, 107, 110, 111, 119, 110, 70, 105, 101, 108,
- 100, 115, 116, 0, 37, 76, 99, 111, 109, 47, 103, 111, 111, 103, 108,
- 101, 47, 112, 114, 111, 116, 111, 98, 117, 102, 47, 85, 110, 107,
- 110, 111, 119, 110, 70, 105, 101, 108, 100, 83, 101, 116, 59, 120,
- 112, 116, 0, 30, 99, 111, 109, 46, 103, 111, 111, 103, 108, 101, 46,
- 112, 114, 111, 116, 111, 98, 117, 102, 46, 73, 110, 116, 51, 50, 86,
- 97, 108, 117, 101
- };
+ byte[] int32ValueBytes =
+ new byte[] {
+ -84, -19, 0, 5, 115, 114, 0, 55, 99, 111, 109, 46, 103, 111, 111, 103, 108, 101, 46, 112,
+ 114, 111, 116, 111, 98, 117, 102, 46, 71, 101, 110, 101, 114, 97, 116, 101, 100, 77, 101,
+ 115, 115, 97, 103, 101, 76, 105, 116, 101, 36, 83, 101, 114, 105, 97, 108, 105, 122, 101,
+ 100, 70, 111, 114, 109, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 91, 0, 7, 97, 115, 66, 121, 116,
+ 101, 115, 116, 0, 2, 91, 66, 76, 0, 12, 109, 101, 115, 115, 97, 103, 101, 67, 108, 97,
+ 115, 115, 116, 0, 17, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 67, 108, 97, 115,
+ 115, 59, 76, 0, 16, 109, 101, 115, 115, 97, 103, 101, 67, 108, 97, 115, 115, 78, 97, 109,
+ 101, 116, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110,
+ 103, 59, 120, 112, 117, 114, 0, 2, 91, 66, -84, -13, 23, -8, 6, 8, 84, -32, 2, 0, 0, 120,
+ 112, 0, 0, 0, 2, 8, 123, 118, 114, 0, 30, 99, 111, 109, 46, 103, 111, 111, 103, 108, 101,
+ 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 73, 110, 116, 51, 50, 86, 97, 108, 117,
+ 101, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 66, 0, 21, 109, 101, 109, 111, 105, 122, 101, 100,
+ 73, 115, 73, 110, 105, 116, 105, 97, 108, 105, 122, 101, 100, 73, 0, 6, 118, 97, 108, 117,
+ 101, 95, 120, 114, 0, 38, 99, 111, 109, 46, 103, 111, 111, 103, 108, 101, 46, 112, 114,
+ 111, 116, 111, 98, 117, 102, 46, 71, 101, 110, 101, 114, 97, 116, 101, 100, 77, 101, 115,
+ 115, 97, 103, 101, 86, 51, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 1, 76, 0, 13, 117, 110, 107, 110,
+ 111, 119, 110, 70, 105, 101, 108, 100, 115, 116, 0, 37, 76, 99, 111, 109, 47, 103, 111,
+ 111, 103, 108, 101, 47, 112, 114, 111, 116, 111, 98, 117, 102, 47, 85, 110, 107, 110, 111,
+ 119, 110, 70, 105, 101, 108, 100, 83, 101, 116, 59, 120, 112, 116, 0, 30, 99, 111, 109,
+ 46, 103, 111, 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 73, 110,
+ 116, 51, 50, 86, 97, 108, 117, 101
+ };
ByteArrayInputStream bais = new ByteArrayInputStream(int32ValueBytes);
ObjectInputStream in = new ObjectInputStream(bais);
@@ -930,33 +898,33 @@ public class GeneratedMessageTest extends TestCase {
}
public void testNonNestedExtensionInitialization() {
- assertTrue(NonNestedExtension.nonNestedExtension
- .getMessageDefaultInstance() instanceof MyNonNestedExtension);
- assertEquals("nonNestedExtension",
- NonNestedExtension.nonNestedExtension.getDescriptor().getName());
+ assertTrue(
+ NonNestedExtension.nonNestedExtension.getMessageDefaultInstance()
+ instanceof MyNonNestedExtension);
+ assertEquals(
+ "nonNestedExtension", NonNestedExtension.nonNestedExtension.getDescriptor().getName());
}
public void testNestedExtensionInitialization() {
- assertTrue(MyNestedExtension.recursiveExtension.getMessageDefaultInstance()
- instanceof MessageToBeExtended);
- assertEquals("recursiveExtension",
- MyNestedExtension.recursiveExtension.getDescriptor().getName());
+ assertTrue(
+ MyNestedExtension.recursiveExtension.getMessageDefaultInstance()
+ instanceof MessageToBeExtended);
+ assertEquals(
+ "recursiveExtension", MyNestedExtension.recursiveExtension.getDescriptor().getName());
}
public void testInvalidations() throws Exception {
GeneratedMessage.enableAlwaysUseFieldBuildersForTesting();
- TestAllTypes.NestedMessage nestedMessage1 =
- TestAllTypes.NestedMessage.newBuilder().build();
- TestAllTypes.NestedMessage nestedMessage2 =
- TestAllTypes.NestedMessage.newBuilder().build();
+ TestAllTypes.NestedMessage nestedMessage1 = TestAllTypes.NestedMessage.newBuilder().build();
+ TestAllTypes.NestedMessage nestedMessage2 = TestAllTypes.NestedMessage.newBuilder().build();
// Set all three flavors (enum, primitive, message and singular/repeated)
// and verify no invalidations fired
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- TestAllTypes.Builder builder = (TestAllTypes.Builder)
- ((AbstractMessage) TestAllTypes.getDefaultInstance()).
- newBuilderForType(mockParent);
+ TestAllTypes.Builder builder =
+ (TestAllTypes.Builder)
+ ((AbstractMessage) TestAllTypes.getDefaultInstance()).newBuilderForType(mockParent);
builder.setOptionalInt32(1);
builder.setOptionalNestedEnum(TestAllTypes.NestedEnum.BAR);
builder.setOptionalNestedMessage(nestedMessage1);
@@ -1003,15 +971,15 @@ public class GeneratedMessageTest extends TestCase {
builder.addRepeatedNestedMessage(nestedMessage2);
builder.addRepeatedNestedMessage(nestedMessage1);
assertEquals(6, mockParent.getInvalidationCount());
-
}
public void testInvalidations_Extensions() throws Exception {
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- TestAllExtensions.Builder builder = (TestAllExtensions.Builder)
- ((AbstractMessage) TestAllExtensions.getDefaultInstance()).
- newBuilderForType(mockParent);
+ TestAllExtensions.Builder builder =
+ (TestAllExtensions.Builder)
+ ((AbstractMessage) TestAllExtensions.getDefaultInstance())
+ .newBuilderForType(mockParent);
builder.addExtension(UnittestProto.repeatedInt32Extension, 1);
builder.setExtension(UnittestProto.repeatedInt32Extension, 0, 2);
@@ -1039,25 +1007,19 @@ public class GeneratedMessageTest extends TestCase {
// Mostly just makes sure the base interface exists and has some methods.
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TestAllTypes message = builder.buildPartial();
- TestAllTypesOrBuilder builderAsInterface = (TestAllTypesOrBuilder) builder;
TestAllTypesOrBuilder messageAsInterface = (TestAllTypesOrBuilder) message;
+ assertEquals(messageAsInterface.getDefaultBool(), messageAsInterface.getDefaultBool());
assertEquals(
- messageAsInterface.getDefaultBool(),
- messageAsInterface.getDefaultBool());
- assertEquals(
- messageAsInterface.getOptionalDouble(),
- messageAsInterface.getOptionalDouble());
+ messageAsInterface.getOptionalDouble(), messageAsInterface.getOptionalDouble(), 0.0);
}
public void testMessageOrBuilderGetters() {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
// single fields
- assertSame(ForeignMessage.getDefaultInstance(),
- builder.getOptionalForeignMessageOrBuilder());
- ForeignMessage.Builder subBuilder =
- builder.getOptionalForeignMessageBuilder();
+ assertSame(ForeignMessage.getDefaultInstance(), builder.getOptionalForeignMessageOrBuilder());
+ ForeignMessage.Builder subBuilder = builder.getOptionalForeignMessageBuilder();
assertSame(subBuilder, builder.getOptionalForeignMessageOrBuilder());
// repeated fields
@@ -1086,36 +1048,37 @@ public class GeneratedMessageTest extends TestCase {
public void testGetFieldBuilder() {
Descriptor descriptor = TestAllTypes.getDescriptor();
- FieldDescriptor fieldDescriptor =
- descriptor.findFieldByName("optional_nested_message");
- FieldDescriptor foreignFieldDescriptor =
- descriptor.findFieldByName("optional_foreign_message");
- FieldDescriptor importFieldDescriptor =
- descriptor.findFieldByName("optional_import_message");
+ FieldDescriptor fieldDescriptor = descriptor.findFieldByName("optional_nested_message");
+ FieldDescriptor foreignFieldDescriptor = descriptor.findFieldByName("optional_foreign_message");
+ FieldDescriptor importFieldDescriptor = descriptor.findFieldByName("optional_import_message");
// Mutate the message with new field builder
// Mutate nested message
TestAllTypes.Builder builder1 = TestAllTypes.newBuilder();
- Message.Builder fieldBuilder1 = builder1.newBuilderForField(fieldDescriptor)
- .mergeFrom((Message) builder1.getField(fieldDescriptor));
+ Message.Builder fieldBuilder1 =
+ builder1
+ .newBuilderForField(fieldDescriptor)
+ .mergeFrom((Message) builder1.getField(fieldDescriptor));
FieldDescriptor subFieldDescriptor1 =
fieldBuilder1.getDescriptorForType().findFieldByName("bb");
fieldBuilder1.setField(subFieldDescriptor1, 1);
builder1.setField(fieldDescriptor, fieldBuilder1.build());
// Mutate foreign message
- Message.Builder foreignFieldBuilder1 = builder1.newBuilderForField(
- foreignFieldDescriptor)
- .mergeFrom((Message) builder1.getField(foreignFieldDescriptor));
+ Message.Builder foreignFieldBuilder1 =
+ builder1
+ .newBuilderForField(foreignFieldDescriptor)
+ .mergeFrom((Message) builder1.getField(foreignFieldDescriptor));
FieldDescriptor subForeignFieldDescriptor1 =
foreignFieldBuilder1.getDescriptorForType().findFieldByName("c");
foreignFieldBuilder1.setField(subForeignFieldDescriptor1, 2);
builder1.setField(foreignFieldDescriptor, foreignFieldBuilder1.build());
// Mutate import message
- Message.Builder importFieldBuilder1 = builder1.newBuilderForField(
- importFieldDescriptor)
- .mergeFrom((Message) builder1.getField(importFieldDescriptor));
+ Message.Builder importFieldBuilder1 =
+ builder1
+ .newBuilderForField(importFieldDescriptor)
+ .mergeFrom((Message) builder1.getField(importFieldDescriptor));
FieldDescriptor subImportFieldDescriptor1 =
importFieldBuilder1.getDescriptorForType().findFieldByName("d");
importFieldBuilder1.setField(subImportFieldDescriptor1, 3);
@@ -1133,18 +1096,20 @@ public class GeneratedMessageTest extends TestCase {
builder2.setField(fieldDescriptor, fieldBuilder2.build());
// Mutate foreign message
- Message.Builder foreignFieldBuilder2 = builder2.newBuilderForField(
- foreignFieldDescriptor)
- .mergeFrom((Message) builder2.getField(foreignFieldDescriptor));
+ Message.Builder foreignFieldBuilder2 =
+ builder2
+ .newBuilderForField(foreignFieldDescriptor)
+ .mergeFrom((Message) builder2.getField(foreignFieldDescriptor));
FieldDescriptor subForeignFieldDescriptor2 =
foreignFieldBuilder2.getDescriptorForType().findFieldByName("c");
foreignFieldBuilder2.setField(subForeignFieldDescriptor2, 2);
builder2.setField(foreignFieldDescriptor, foreignFieldBuilder2.build());
// Mutate import message
- Message.Builder importFieldBuilder2 = builder2.newBuilderForField(
- importFieldDescriptor)
- .mergeFrom((Message) builder2.getField(importFieldDescriptor));
+ Message.Builder importFieldBuilder2 =
+ builder2
+ .newBuilderForField(importFieldDescriptor)
+ .mergeFrom((Message) builder2.getField(importFieldDescriptor));
FieldDescriptor subImportFieldDescriptor2 =
importFieldBuilder2.getDescriptorForType().findFieldByName("d");
importFieldBuilder2.setField(subImportFieldDescriptor2, 3);
@@ -1158,10 +1123,9 @@ public class GeneratedMessageTest extends TestCase {
public void testGetFieldBuilderWithInitializedValue() {
Descriptor descriptor = TestAllTypes.getDescriptor();
- FieldDescriptor fieldDescriptor =
- descriptor.findFieldByName("optional_nested_message");
+ FieldDescriptor fieldDescriptor = descriptor.findFieldByName("optional_nested_message");
- // Before setting field, builder is initialized by default value.
+ // Before setting field, builder is initialized by default value.
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
NestedMessage.Builder fieldBuilder =
(NestedMessage.Builder) builder.getFieldBuilder(fieldDescriptor);
@@ -1169,12 +1133,10 @@ public class GeneratedMessageTest extends TestCase {
// Setting field value with new field builder instance.
builder = TestAllTypes.newBuilder();
- NestedMessage.Builder newFieldBuilder =
- builder.getOptionalNestedMessageBuilder();
+ NestedMessage.Builder newFieldBuilder = builder.getOptionalNestedMessageBuilder();
newFieldBuilder.setBb(2);
// Then get the field builder instance by getFieldBuilder().
- fieldBuilder =
- (NestedMessage.Builder) builder.getFieldBuilder(fieldDescriptor);
+ fieldBuilder = (NestedMessage.Builder) builder.getFieldBuilder(fieldDescriptor);
// It should contain new value.
assertEquals(2, fieldBuilder.getBb());
// These two builder should be equal.
@@ -1191,8 +1153,7 @@ public class GeneratedMessageTest extends TestCase {
// We expect this exception.
}
try {
- builder.getFieldBuilder(
- descriptor.findFieldByName("optional_nested_enum"));
+ builder.getFieldBuilder(descriptor.findFieldByName("optional_nested_enum"));
fail("Exception was not thrown");
} catch (UnsupportedOperationException e) {
// We expect this exception.
@@ -1204,15 +1165,13 @@ public class GeneratedMessageTest extends TestCase {
// We expect this exception.
}
try {
- builder.getFieldBuilder(
- descriptor.findFieldByName("repeated_nested_enum"));
+ builder.getFieldBuilder(descriptor.findFieldByName("repeated_nested_enum"));
fail("Exception was not thrown");
} catch (UnsupportedOperationException e) {
// We expect this exception.
}
try {
- builder.getFieldBuilder(
- descriptor.findFieldByName("repeated_nested_message"));
+ builder.getFieldBuilder(descriptor.findFieldByName("repeated_nested_message"));
fail("Exception was not thrown");
} catch (UnsupportedOperationException e) {
// We expect this exception.
@@ -1227,25 +1186,25 @@ public class GeneratedMessageTest extends TestCase {
// expected name. There is nothing else to test.
OuterClassNameTestOuterClass.OuterClassNameTest message =
OuterClassNameTestOuterClass.OuterClassNameTest.newBuilder().build();
- assertTrue(message.getDescriptorForType() ==
- OuterClassNameTestOuterClass.OuterClassNameTest.getDescriptor());
+ assertTrue(
+ message.getDescriptorForType()
+ == OuterClassNameTestOuterClass.OuterClassNameTest.getDescriptor());
- OuterClassNameTest2OuterClass.TestMessage2.NestedMessage.OuterClassNameTest2
- message2 = OuterClassNameTest2OuterClass.TestMessage2.NestedMessage
- .OuterClassNameTest2.newBuilder().build();
+ OuterClassNameTest2OuterClass.TestMessage2.NestedMessage.OuterClassNameTest2 message2 =
+ OuterClassNameTest2OuterClass.TestMessage2.NestedMessage.OuterClassNameTest2.newBuilder()
+ .build();
assertEquals(0, message2.getSerializedSize());
- OuterClassNameTest3OuterClass.TestMessage3.NestedMessage.OuterClassNameTest3
- enumValue = OuterClassNameTest3OuterClass.TestMessage3.NestedMessage
- .OuterClassNameTest3.DUMMY_VALUE;
+ OuterClassNameTest3OuterClass.TestMessage3.NestedMessage.OuterClassNameTest3 enumValue =
+ OuterClassNameTest3OuterClass.TestMessage3.NestedMessage.OuterClassNameTest3.DUMMY_VALUE;
assertEquals(1, enumValue.getNumber());
}
// =================================================================
// oneof generated code test
public void testOneofEnumCase() throws Exception {
- TestOneof2 message = TestOneof2.newBuilder()
- .setFooInt(123).setFooString("foo").setFooCord("bar").build();
+ TestOneof2 message =
+ TestOneof2.newBuilder().setFooInt(123).setFooString("foo").setFooCord("bar").build();
TestUtil.assertAtMostOneFieldSetOneof(message);
}
@@ -1258,8 +1217,7 @@ public class GeneratedMessageTest extends TestCase {
public void testSetOneofClearsOthers() throws Exception {
TestOneof2.Builder builder = TestOneof2.newBuilder();
- TestOneof2 message =
- builder.setFooInt(123).setFooString("foo").buildPartial();
+ TestOneof2 message = builder.setFooInt(123).setFooString("foo").buildPartial();
assertTrue(message.hasFooString());
TestUtil.assertAtMostOneFieldSetOneof(message);
@@ -1279,8 +1237,10 @@ public class GeneratedMessageTest extends TestCase {
assertTrue(message.hasFooEnum());
TestUtil.assertAtMostOneFieldSetOneof(message);
- message = builder.setFooMessage(
- TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()).buildPartial();
+ message =
+ builder
+ .setFooMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build())
+ .buildPartial();
assertTrue(message.hasFooMessage());
TestUtil.assertAtMostOneFieldSetOneof(message);
@@ -1396,8 +1356,7 @@ public class GeneratedMessageTest extends TestCase {
// set
TestOneof2.Builder builder = TestOneof2.newBuilder();
assertEquals(0, builder.getFooMessage().getQuxInt());
- builder.setFooMessage(
- TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build());
+ builder.setFooMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build());
assertTrue(builder.hasFooMessage());
assertEquals(234, builder.getFooMessage().getQuxInt());
TestOneof2 message = builder.buildPartial();
@@ -1412,8 +1371,7 @@ public class GeneratedMessageTest extends TestCase {
// nested builder
builder = TestOneof2.newBuilder();
- assertSame(builder.getFooMessageOrBuilder(),
- TestOneof2.NestedMessage.getDefaultInstance());
+ assertSame(builder.getFooMessageOrBuilder(), TestOneof2.NestedMessage.getDefaultInstance());
assertFalse(builder.hasFooMessage());
builder.getFooMessageBuilder().setQuxInt(123);
assertTrue(builder.hasFooMessage());
@@ -1457,8 +1415,10 @@ public class GeneratedMessageTest extends TestCase {
// Message
{
TestOneof2.Builder builder = TestOneof2.newBuilder();
- TestOneof2 message = builder.setFooMessage(
- TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()).build();
+ TestOneof2 message =
+ builder
+ .setFooMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build())
+ .build();
TestOneof2 message2 = TestOneof2.newBuilder().mergeFrom(message).build();
assertTrue(message2.hasFooMessage());
assertEquals(234, message2.getFooMessage().getQuxInt());
@@ -1499,8 +1459,10 @@ public class GeneratedMessageTest extends TestCase {
// Message
{
TestOneof2.Builder builder = TestOneof2.newBuilder();
- TestOneof2 message = builder.setFooMessage(
- TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()).build();
+ TestOneof2 message =
+ builder
+ .setFooMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build())
+ .build();
ByteString serialized = message.toByteString();
TestOneof2 message2 = TestOneof2.parseFrom(serialized);
assertTrue(message2.hasFooMessage());
@@ -1522,40 +1484,32 @@ public class GeneratedMessageTest extends TestCase {
public void testGetRepeatedFieldBuilder() {
Descriptor descriptor = TestAllTypes.getDescriptor();
- FieldDescriptor fieldDescriptor =
- descriptor.findFieldByName("repeated_nested_message");
- FieldDescriptor foreignFieldDescriptor =
- descriptor.findFieldByName("repeated_foreign_message");
- FieldDescriptor importFieldDescriptor =
- descriptor.findFieldByName("repeated_import_message");
+ FieldDescriptor fieldDescriptor = descriptor.findFieldByName("repeated_nested_message");
+ FieldDescriptor foreignFieldDescriptor = descriptor.findFieldByName("repeated_foreign_message");
+ FieldDescriptor importFieldDescriptor = descriptor.findFieldByName("repeated_import_message");
// Mutate the message with new field builder
// Mutate nested message
TestAllTypes.Builder builder1 = TestAllTypes.newBuilder();
- Message.Builder fieldBuilder1 = builder1.newBuilderForField(
- fieldDescriptor);
+ Message.Builder fieldBuilder1 = builder1.newBuilderForField(fieldDescriptor);
FieldDescriptor subFieldDescriptor1 =
fieldBuilder1.getDescriptorForType().findFieldByName("bb");
fieldBuilder1.setField(subFieldDescriptor1, 1);
builder1.addRepeatedField(fieldDescriptor, fieldBuilder1.build());
// Mutate foreign message
- Message.Builder foreignFieldBuilder1 = builder1.newBuilderForField(
- foreignFieldDescriptor);
+ Message.Builder foreignFieldBuilder1 = builder1.newBuilderForField(foreignFieldDescriptor);
FieldDescriptor subForeignFieldDescriptor1 =
foreignFieldBuilder1.getDescriptorForType().findFieldByName("c");
foreignFieldBuilder1.setField(subForeignFieldDescriptor1, 2);
- builder1.addRepeatedField(foreignFieldDescriptor,
- foreignFieldBuilder1.build());
+ builder1.addRepeatedField(foreignFieldDescriptor, foreignFieldBuilder1.build());
// Mutate import message
- Message.Builder importFieldBuilder1 = builder1.newBuilderForField(
- importFieldDescriptor);
+ Message.Builder importFieldBuilder1 = builder1.newBuilderForField(importFieldDescriptor);
FieldDescriptor subImportFieldDescriptor1 =
importFieldBuilder1.getDescriptorForType().findFieldByName("d");
importFieldBuilder1.setField(subImportFieldDescriptor1, 3);
- builder1.addRepeatedField(importFieldDescriptor,
- importFieldBuilder1.build());
+ builder1.addRepeatedField(importFieldDescriptor, importFieldBuilder1.build());
Message newMessage1 = builder1.build();
@@ -1563,29 +1517,24 @@ public class GeneratedMessageTest extends TestCase {
// Mutate nested message
TestAllTypes.Builder builder2 = TestAllTypes.newBuilder();
builder2.addRepeatedNestedMessageBuilder();
- Message.Builder fieldBuilder2 = builder2.getRepeatedFieldBuilder(
- fieldDescriptor, 0);
+ Message.Builder fieldBuilder2 = builder2.getRepeatedFieldBuilder(fieldDescriptor, 0);
FieldDescriptor subFieldDescriptor2 =
fieldBuilder2.getDescriptorForType().findFieldByName("bb");
fieldBuilder2.setField(subFieldDescriptor2, 1);
// Mutate foreign message
- Message.Builder foreignFieldBuilder2 = builder2.newBuilderForField(
- foreignFieldDescriptor);
+ Message.Builder foreignFieldBuilder2 = builder2.newBuilderForField(foreignFieldDescriptor);
FieldDescriptor subForeignFieldDescriptor2 =
foreignFieldBuilder2.getDescriptorForType().findFieldByName("c");
foreignFieldBuilder2.setField(subForeignFieldDescriptor2, 2);
- builder2.addRepeatedField(foreignFieldDescriptor,
- foreignFieldBuilder2.build());
+ builder2.addRepeatedField(foreignFieldDescriptor, foreignFieldBuilder2.build());
// Mutate import message
- Message.Builder importFieldBuilder2 = builder2.newBuilderForField(
- importFieldDescriptor);
+ Message.Builder importFieldBuilder2 = builder2.newBuilderForField(importFieldDescriptor);
FieldDescriptor subImportFieldDescriptor2 =
importFieldBuilder2.getDescriptorForType().findFieldByName("d");
importFieldBuilder2.setField(subImportFieldDescriptor2, 3);
- builder2.addRepeatedField(importFieldDescriptor,
- importFieldBuilder2.build());
+ builder2.addRepeatedField(importFieldDescriptor, importFieldBuilder2.build());
Message newMessage2 = builder2.build();
@@ -1595,10 +1544,9 @@ public class GeneratedMessageTest extends TestCase {
public void testGetRepeatedFieldBuilderWithInitializedValue() {
Descriptor descriptor = TestAllTypes.getDescriptor();
- FieldDescriptor fieldDescriptor =
- descriptor.findFieldByName("repeated_nested_message");
+ FieldDescriptor fieldDescriptor = descriptor.findFieldByName("repeated_nested_message");
- // Before setting field, builder is initialized by default value.
+ // Before setting field, builder is initialized by default value.
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
builder.addRepeatedNestedMessageBuilder();
NestedMessage.Builder fieldBuilder =
@@ -1607,12 +1555,10 @@ public class GeneratedMessageTest extends TestCase {
// Setting field value with new field builder instance.
builder = TestAllTypes.newBuilder();
- NestedMessage.Builder newFieldBuilder =
- builder.addRepeatedNestedMessageBuilder();
+ NestedMessage.Builder newFieldBuilder = builder.addRepeatedNestedMessageBuilder();
newFieldBuilder.setBb(2);
// Then get the field builder instance by getRepeatedFieldBuilder().
- fieldBuilder =
- (NestedMessage.Builder) builder.getRepeatedFieldBuilder(fieldDescriptor, 0);
+ fieldBuilder = (NestedMessage.Builder) builder.getRepeatedFieldBuilder(fieldDescriptor, 0);
// It should contain new value.
assertEquals(2, fieldBuilder.getBb());
// These two builder should be equal.
@@ -1629,8 +1575,7 @@ public class GeneratedMessageTest extends TestCase {
// We expect this exception.
}
try {
- builder.getRepeatedFieldBuilder(
- descriptor.findFieldByName("repeated_nested_enum"), 0);
+ builder.getRepeatedFieldBuilder(descriptor.findFieldByName("repeated_nested_enum"), 0);
fail("Exception was not thrown");
} catch (UnsupportedOperationException e) {
// We expect this exception.
@@ -1642,15 +1587,13 @@ public class GeneratedMessageTest extends TestCase {
// We expect this exception.
}
try {
- builder.getRepeatedFieldBuilder(
- descriptor.findFieldByName("optional_nested_enum"), 0);
+ builder.getRepeatedFieldBuilder(descriptor.findFieldByName("optional_nested_enum"), 0);
fail("Exception was not thrown");
} catch (UnsupportedOperationException e) {
// We expect this exception.
}
try {
- builder.getRepeatedFieldBuilder(
- descriptor.findFieldByName("optional_nested_message"), 0);
+ builder.getRepeatedFieldBuilder(descriptor.findFieldByName("optional_nested_message"), 0);
fail("Exception was not thrown");
} catch (UnsupportedOperationException e) {
// We expect this exception.
diff --git a/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java b/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java
index 9edc4344..d6943e02 100644
--- a/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java
@@ -45,10 +45,8 @@ import junit.framework.TestCase;
*/
public class IntArrayListTest extends TestCase {
- private static final IntArrayList UNARY_LIST =
- newImmutableIntArrayList(1);
- private static final IntArrayList TERTIARY_LIST =
- newImmutableIntArrayList(1, 2, 3);
+ private static final IntArrayList UNARY_LIST = newImmutableIntArrayList(1);
+ private static final IntArrayList TERTIARY_LIST = newImmutableIntArrayList(1, 2, 3);
private IntArrayList list;
@@ -225,9 +223,7 @@ public class IntArrayListTest extends TestCase {
for (int i = 0; i < 6; i++) {
list.add(Integer.valueOf(5 + i));
}
- assertEquals(
- asList(0, 1, 4, 2, 3, 5, 6, 7, 8, 9, 10),
- list);
+ assertEquals(asList(0, 1, 4, 2, 3, 5, 6, 7, 8, 9, 10), list);
try {
list.add(-1, 5);
@@ -299,16 +295,14 @@ public class IntArrayListTest extends TestCase {
}
public void testRemoveEndOfCapacity() {
- IntList toRemove =
- IntArrayList.emptyList().mutableCopyWithCapacity(1);
+ IntList toRemove = IntArrayList.emptyList().mutableCopyWithCapacity(1);
toRemove.addInt(3);
toRemove.remove(0);
assertEquals(0, toRemove.size());
}
public void testSublistRemoveEndOfCapacity() {
- IntList toRemove =
- IntArrayList.emptyList().mutableCopyWithCapacity(1);
+ IntList toRemove = IntArrayList.emptyList().mutableCopyWithCapacity(1);
toRemove.addInt(3);
toRemove.subList(0, 1).clear();
assertEquals(0, toRemove.size());
diff --git a/java/core/src/test/java/com/google/protobuf/IsValidUtf8Test.java b/java/core/src/test/java/com/google/protobuf/IsValidUtf8Test.java
index 756049b4..2518f20d 100644
--- a/java/core/src/test/java/com/google/protobuf/IsValidUtf8Test.java
+++ b/java/core/src/test/java/com/google/protobuf/IsValidUtf8Test.java
@@ -39,45 +39,36 @@ import static com.google.protobuf.IsValidUtf8TestUtil.testBytes;
import com.google.protobuf.IsValidUtf8TestUtil.ByteStringFactory;
import com.google.protobuf.IsValidUtf8TestUtil.Shard;
-
import junit.framework.TestCase;
/**
- * Tests cases for {@link ByteString#isValidUtf8()}. This includes three
- * brute force tests that actually test every permutation of one byte, two byte,
- * and three byte sequences to ensure that the method produces the right result
- * for every possible byte encoding where "right" means it's consistent with
- * java's UTF-8 string encoding/decoding such that the method returns true for
- * any sequence that will round trip when converted to a String and then back to
- * bytes and will return false for any sequence that will not round trip.
- * See also {@link IsValidUtf8FourByteTest}. It also includes some
- * other more targeted tests.
+ * Tests cases for {@link ByteString#isValidUtf8()}. This includes three brute force tests that
+ * actually test every permutation of one byte, two byte, and three byte sequences to ensure that
+ * the method produces the right result for every possible byte encoding where "right" means it's
+ * consistent with java's UTF-8 string encoding/decoding such that the method returns true for any
+ * sequence that will round trip when converted to a String and then back to bytes and will return
+ * false for any sequence that will not round trip. See also {@link IsValidUtf8FourByteTest}. It
+ * also includes some other more targeted tests.
*
* @author jonp@google.com (Jon Perlow)
* @author martinrb@google.com (Martin Buchholz)
*/
public class IsValidUtf8Test extends TestCase {
- /**
- * Tests that round tripping of all two byte permutations work.
- */
+ /** Tests that round tripping of all two byte permutations work. */
public void testIsValidUtf8_1Byte() {
testBytes(LITERAL_FACTORY, 1, EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT);
testBytes(HEAP_NIO_FACTORY, 1, EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT);
testBytes(DIRECT_NIO_FACTORY, 1, EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT);
}
- /**
- * Tests that round tripping of all two byte permutations work.
- */
+ /** Tests that round tripping of all two byte permutations work. */
public void testIsValidUtf8_2Bytes() {
testBytes(LITERAL_FACTORY, 2, IsValidUtf8TestUtil.EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT);
testBytes(HEAP_NIO_FACTORY, 2, IsValidUtf8TestUtil.EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT);
testBytes(DIRECT_NIO_FACTORY, 2, IsValidUtf8TestUtil.EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT);
}
- /**
- * Tests that round tripping of all three byte permutations work.
- */
+ /** Tests that round tripping of all three byte permutations work. */
public void testIsValidUtf8_3Bytes() {
// Travis' OOM killer doesn't like this test
if (System.getenv("TRAVIS") == null) {
@@ -88,10 +79,9 @@ public class IsValidUtf8Test extends TestCase {
}
/**
- * Tests that round tripping of a sample of four byte permutations work.
- * All permutations are prohibitively expensive to test for automated runs;
- * {@link IsValidUtf8FourByteTest} is used for full coverage. This method
- * tests specific four-byte cases.
+ * Tests that round tripping of a sample of four byte permutations work. All permutations are
+ * prohibitively expensive to test for automated runs; {@link IsValidUtf8FourByteTest} is used for
+ * full coverage. This method tests specific four-byte cases.
*/
public void testIsValidUtf8_4BytesSamples() {
// Valid 4 byte.
@@ -106,9 +96,7 @@ public class IsValidUtf8Test extends TestCase {
assertInvalidUtf8(0xF4, 0x90, 0xAD, 0xA2);
}
- /**
- * Tests some hard-coded test cases.
- */
+ /** Tests some hard-coded test cases. */
public void testSomeSequences() {
// Empty
assertTrue(asBytes("").isValidUtf8());
@@ -149,11 +137,12 @@ public class IsValidUtf8Test extends TestCase {
assertTrue(not ^ leaf.isValidUtf8());
assertTrue(not ^ sub.isValidUtf8());
ByteString[] ropes = {
- RopeByteString.newInstanceForTest(ByteString.EMPTY, leaf),
- RopeByteString.newInstanceForTest(ByteString.EMPTY, sub),
- RopeByteString.newInstanceForTest(leaf, ByteString.EMPTY),
- RopeByteString.newInstanceForTest(sub, ByteString.EMPTY),
- RopeByteString.newInstanceForTest(sub, leaf)};
+ RopeByteString.newInstanceForTest(ByteString.EMPTY, leaf),
+ RopeByteString.newInstanceForTest(ByteString.EMPTY, sub),
+ RopeByteString.newInstanceForTest(leaf, ByteString.EMPTY),
+ RopeByteString.newInstanceForTest(sub, ByteString.EMPTY),
+ RopeByteString.newInstanceForTest(sub, leaf)
+ };
for (ByteString rope : ropes) {
assertTrue(not ^ rope.isValidUtf8());
}
diff --git a/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java b/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java
index 1bcf63e7..2c086e11 100644
--- a/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java
+++ b/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java
@@ -50,8 +50,7 @@ import java.util.Random;
import java.util.logging.Logger;
/**
- * Shared testing code for {@link IsValidUtf8Test} and
- * {@link IsValidUtf8FourByteTest}.
+ * Shared testing code for {@link IsValidUtf8Test} and {@link IsValidUtf8FourByteTest}.
*
* @author jonp@google.com (Jon Perlow)
* @author martinrb@google.com (Martin Buchholz)
@@ -65,44 +64,47 @@ final class IsValidUtf8TestUtil {
ByteString newByteString(byte[] bytes);
}
- static final ByteStringFactory LITERAL_FACTORY = new ByteStringFactory() {
- @Override
- public ByteString newByteString(byte[] bytes) {
- return ByteString.wrap(bytes);
- }
- };
+ static final ByteStringFactory LITERAL_FACTORY =
+ new ByteStringFactory() {
+ @Override
+ public ByteString newByteString(byte[] bytes) {
+ return ByteString.wrap(bytes);
+ }
+ };
- static final ByteStringFactory HEAP_NIO_FACTORY = new ByteStringFactory() {
- @Override
- public ByteString newByteString(byte[] bytes) {
- return new NioByteString(ByteBuffer.wrap(bytes));
- }
- };
+ static final ByteStringFactory HEAP_NIO_FACTORY =
+ new ByteStringFactory() {
+ @Override
+ public ByteString newByteString(byte[] bytes) {
+ return new NioByteString(ByteBuffer.wrap(bytes));
+ }
+ };
private static ThreadLocal<SoftReference<ByteBuffer>> directBuffer =
new ThreadLocal<SoftReference<ByteBuffer>>();
/**
- * Factory for direct {@link ByteBuffer} instances. To reduce direct memory usage, this
- * uses a thread local direct buffer. This means that each call will overwrite the buffer's
- * contents from the previous call, so the calling code must be careful not to continue using
- * a buffer returned from a previous invocation.
+ * Factory for direct {@link ByteBuffer} instances. To reduce direct memory usage, this uses a
+ * thread local direct buffer. This means that each call will overwrite the buffer's contents from
+ * the previous call, so the calling code must be careful not to continue using a buffer returned
+ * from a previous invocation.
*/
- static final ByteStringFactory DIRECT_NIO_FACTORY = new ByteStringFactory() {
- @Override
- public ByteString newByteString(byte[] bytes) {
- SoftReference<ByteBuffer> ref = directBuffer.get();
- ByteBuffer buffer = ref == null ? null : ref.get();
- if (buffer == null || buffer.capacity() < bytes.length) {
- buffer = ByteBuffer.allocateDirect(bytes.length);
- directBuffer.set(new SoftReference<ByteBuffer>(buffer));
- }
- buffer.clear();
- buffer.put(bytes);
- buffer.flip();
- return new NioByteString(buffer);
- }
- };
+ static final ByteStringFactory DIRECT_NIO_FACTORY =
+ new ByteStringFactory() {
+ @Override
+ public ByteString newByteString(byte[] bytes) {
+ SoftReference<ByteBuffer> ref = directBuffer.get();
+ ByteBuffer buffer = ref == null ? null : ref.get();
+ if (buffer == null || buffer.capacity() < bytes.length) {
+ buffer = ByteBuffer.allocateDirect(bytes.length);
+ directBuffer.set(new SoftReference<ByteBuffer>(buffer));
+ }
+ buffer.clear();
+ buffer.put(bytes);
+ buffer.flip();
+ return new NioByteString(buffer);
+ }
+ };
// 128 - [chars 0x0000 to 0x007f]
static final long ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS = 0x007f - 0x0000 + 1;
@@ -116,9 +118,10 @@ final class IsValidUtf8TestUtil {
// 18,304
static final long EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT =
// Both bytes are one byte characters
- (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 2) +
- // The possible number of two byte characters
- TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS;
+ (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 2)
+ +
+ // The possible number of two byte characters
+ TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS;
// 2048
static final long THREE_BYTE_SURROGATES = 2 * 1024;
@@ -130,11 +133,13 @@ final class IsValidUtf8TestUtil {
// 2,650,112
static final long EXPECTED_THREE_BYTE_ROUNDTRIPPABLE_COUNT =
// All one byte characters
- (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 3) +
- // One two byte character and a one byte character
- 2 * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS +
- // Three byte characters
- THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS;
+ (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 3)
+ +
+ // One two byte character and a one byte character
+ 2 * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS
+ +
+ // Three byte characters
+ THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS;
// 1,048,576 [chars 0x10000L to 0x10FFFF]
static final long FOUR_BYTE_ROUNDTRIPPABLE_CHARACTERS = 0x10FFFF - 0x10000L + 1;
@@ -142,17 +147,22 @@ final class IsValidUtf8TestUtil {
// 289,571,839
static final long EXPECTED_FOUR_BYTE_ROUNDTRIPPABLE_COUNT =
// All one byte characters
- (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 4) +
- // One and three byte characters
- 2 * THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS +
- // Two two byte characters
- TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS +
- // Permutations of one and two byte characters
- 3 * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS
- * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS
- +
- // Four byte characters
- FOUR_BYTE_ROUNDTRIPPABLE_CHARACTERS;
+ (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 4)
+ +
+ // One and three byte characters
+ 2 * THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS
+ +
+ // Two two byte characters
+ TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS
+ +
+ // Permutations of one and two byte characters
+ 3
+ * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS
+ * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS
+ * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS
+ +
+ // Four byte characters
+ FOUR_BYTE_ROUNDTRIPPABLE_CHARACTERS;
static final class Shard {
final long index;
@@ -160,7 +170,6 @@ final class IsValidUtf8TestUtil {
final long lim;
final long expected;
-
public Shard(long index, long start, long lim, long expected) {
assertTrue(start < lim);
this.index = index;
@@ -206,7 +215,6 @@ final class IsValidUtf8TestUtil {
static final List<Shard> FOUR_BYTE_SHARDS =
generateFourByteShards(128, FOUR_BYTE_SHARDS_EXPECTED_ROUNTRIPPABLES);
-
private static List<Shard> generateFourByteShards(int numShards, long[] expected) {
assertEquals(numShards, expected.length);
List<Shard> shards = new ArrayList<Shard>(numShards);
@@ -220,8 +228,7 @@ final class IsValidUtf8TestUtil {
}
/**
- * Helper to run the loop to test all the permutations for the number of bytes
- * specified.
+ * Helper to run the loop to test all the permutations for the number of bytes specified.
*
* @param factory the factory for {@link ByteString} instances.
* @param numBytes the number of bytes in the byte array
@@ -232,16 +239,15 @@ final class IsValidUtf8TestUtil {
}
/**
- * Helper to run the loop to test all the permutations for the number of bytes
- * specified. This overload is useful for debugging to get the loop to start
- * at a certain character.
+ * Helper to run the loop to test all the permutations for the number of bytes specified. This
+ * overload is useful for debugging to get the loop to start at a certain character.
*
* @param factory the factory for {@link ByteString} instances.
* @param numBytes the number of bytes in the byte array
* @param expectedCount the expected number of roundtrippable permutations
* @param start the starting bytes encoded as a long as big-endian
- * @param lim the limit of bytes to process encoded as a long as big-endian,
- * or -1 to mean the max limit for numBytes
+ * @param lim the limit of bytes to process encoded as a long as big-endian, or -1 to mean the max
+ * limit for numBytes
*/
static void testBytes(
ByteStringFactory factory, int numBytes, long expectedCount, long start, long lim) {
@@ -301,9 +307,10 @@ final class IsValidUtf8TestUtil {
assertEquals(isRoundTrippable, (state3 == Utf8.COMPLETE));
// Test ropes built out of small partial sequences
- ByteString rope = RopeByteString.newInstanceForTest(
- bs.substring(0, i),
- RopeByteString.newInstanceForTest(bs.substring(i, j), bs.substring(j, numBytes)));
+ ByteString rope =
+ RopeByteString.newInstanceForTest(
+ bs.substring(0, i),
+ RopeByteString.newInstanceForTest(bs.substring(i, j), bs.substring(j, numBytes)));
assertSame(RopeByteString.class, rope.getClass());
ByteString[] byteStrings = {bs, bs.substring(0, numBytes), rope};
@@ -336,27 +343,28 @@ final class IsValidUtf8TestUtil {
}
/**
- * Variation of {@link #testBytes} that does less allocation using the
- * low-level encoders/decoders directly. Checked in because it's useful for
- * debugging when trying to process bytes faster, but since it doesn't use the
- * actual String class, it's possible for incompatibilities to develop
+ * Variation of {@link #testBytes} that does less allocation using the low-level encoders/decoders
+ * directly. Checked in because it's useful for debugging when trying to process bytes faster, but
+ * since it doesn't use the actual String class, it's possible for incompatibilities to develop
* (although unlikely).
*
* @param factory the factory for {@link ByteString} instances.
* @param numBytes the number of bytes in the byte array
* @param expectedCount the expected number of roundtrippable permutations
* @param start the starting bytes encoded as a long as big-endian
- * @param lim the limit of bytes to process encoded as a long as big-endian,
- * or -1 to mean the max limit for numBytes
+ * @param lim the limit of bytes to process encoded as a long as big-endian, or -1 to mean the max
+ * limit for numBytes
*/
static void testBytesUsingByteBuffers(
ByteStringFactory factory, int numBytes, long expectedCount, long start, long lim) {
CharsetDecoder decoder =
- Internal.UTF_8.newDecoder()
+ Internal.UTF_8
+ .newDecoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE);
CharsetEncoder encoder =
- Internal.UTF_8.newEncoder()
+ Internal.UTF_8
+ .newEncoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE);
byte[] bytes = new byte[numBytes];
@@ -434,8 +442,10 @@ final class IsValidUtf8TestUtil {
}
private static void outputFailure(long byteChar, byte[] bytes, byte[] after, int len) {
- fail("Failure: (" + Long.toHexString(byteChar) + ") " + toHexString(bytes) + " => "
- + toHexString(after, len));
+ fail(
+ String.format(
+ "Failure: (%s) %s => %s",
+ Long.toHexString(byteChar), toHexString(bytes), toHexString(after, len)));
}
private static String toHexString(byte[] b) {
diff --git a/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java b/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java
index f27e8e51..a3901e91 100644
--- a/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java
@@ -42,8 +42,7 @@ import junit.framework.TestCase;
public class LazyFieldTest extends TestCase {
public void testHashCode() {
MessageLite message = TestUtil.getAllSet();
- LazyField lazyField =
- createLazyFieldFromMessage(message);
+ LazyField lazyField = createLazyFieldFromMessage(message);
assertEquals(message.hashCode(), lazyField.hashCode());
lazyField.getValue();
assertEquals(message.hashCode(), lazyField.hashCode());
@@ -102,8 +101,8 @@ public class LazyFieldTest extends TestCase {
private LazyField createLazyFieldFromMessage(MessageLite message) {
ByteString bytes = message.toByteString();
- return new LazyField(message.getDefaultInstanceForType(),
- TestUtil.getExtensionRegistry(), bytes);
+ return new LazyField(
+ message.getDefaultInstanceForType(), TestUtil.getExtensionRegistry(), bytes);
}
private void changeValue(LazyField lazyField) {
@@ -114,7 +113,6 @@ public class LazyFieldTest extends TestCase {
}
private void assertNotEqual(Object unexpected, Object actual) {
- assertFalse(unexpected == actual
- || (unexpected != null && unexpected.equals(actual)));
+ assertFalse(unexpected == actual || (unexpected != null && unexpected.equals(actual)));
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java b/java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java
index 968ca206..c5880d50 100644
--- a/java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java
@@ -44,8 +44,6 @@ import junit.framework.TestCase;
*/
public class LazyMessageLiteTest extends TestCase {
- private Parser<LazyInnerMessageLite> originalLazyInnerMessageLiteParser;
-
@Override
protected void setUp() throws Exception {
super.setUp();
@@ -57,19 +55,16 @@ public class LazyMessageLiteTest extends TestCase {
}
public void testSetValues() {
- LazyNestedInnerMessageLite nested = LazyNestedInnerMessageLite.newBuilder()
- .setNum(3)
- .build();
- LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder()
- .setNum(2)
- .setNested(nested)
- .build();
- LazyMessageLite outer = LazyMessageLite.newBuilder()
- .setNum(1)
- .setInner(inner)
- .setOneofNum(123)
- .setOneofInner(inner)
- .build();
+ LazyNestedInnerMessageLite nested = LazyNestedInnerMessageLite.newBuilder().setNum(3).build();
+ LazyInnerMessageLite inner =
+ LazyInnerMessageLite.newBuilder().setNum(2).setNested(nested).build();
+ LazyMessageLite outer =
+ LazyMessageLite.newBuilder()
+ .setNum(1)
+ .setInner(inner)
+ .setOneofNum(123)
+ .setOneofInner(inner)
+ .build();
assertEquals(1, outer.getNum());
assertEquals(421, outer.getNumWithDefault());
@@ -90,44 +85,43 @@ public class LazyMessageLiteTest extends TestCase {
}
public void testSetRepeatedValues() {
- LazyMessageLite outer = LazyMessageLite.newBuilder()
- .setNum(1)
- .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(119))
- .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(122))
- .build();
+ LazyMessageLite outer =
+ LazyMessageLite.newBuilder()
+ .setNum(1)
+ .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(119))
+ .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(122))
+ .build();
assertEquals(1, outer.getNum());
assertEquals(2, outer.getRepeatedInnerCount());
assertEquals(119, outer.getRepeatedInner(0).getNum());
assertEquals(122, outer.getRepeatedInner(1).getNum());
}
-
+
public void testRepeatedMutability() throws Exception {
- LazyMessageLite outer = LazyMessageLite.newBuilder()
- .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(119))
- .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(122))
- .build();
-
+ LazyMessageLite outer =
+ LazyMessageLite.newBuilder()
+ .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(119))
+ .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(122))
+ .build();
+
outer = LazyMessageLite.parseFrom(outer.toByteArray());
try {
outer.getRepeatedInnerList().set(1, null);
fail();
- } catch (UnsupportedOperationException expected) {}
+ } catch (UnsupportedOperationException expected) {
+ }
}
public void testAddAll() {
- ArrayList<LazyInnerMessageLite> inners = new ArrayList<LazyInnerMessageLite>();
+ ArrayList<LazyInnerMessageLite> inners = new ArrayList<>();
int count = 4;
for (int i = 0; i < count; i++) {
- LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder()
- .setNum(i)
- .build();
+ LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder().setNum(i).build();
inners.add(inner);
}
- LazyMessageLite outer = LazyMessageLite.newBuilder()
- .addAllRepeatedInner(inners)
- .build();
+ LazyMessageLite outer = LazyMessageLite.newBuilder().addAllRepeatedInner(inners).build();
assertEquals(count, outer.getRepeatedInnerCount());
for (int i = 0; i < count; i++) {
assertEquals(i, outer.getRepeatedInner(i).getNum());
@@ -135,8 +129,7 @@ public class LazyMessageLiteTest extends TestCase {
}
public void testGetDefaultValues() {
- LazyMessageLite outer = LazyMessageLite.newBuilder()
- .build();
+ LazyMessageLite outer = LazyMessageLite.getDefaultInstance();
assertEquals(0, outer.getNum());
assertEquals(421, outer.getNumWithDefault());
@@ -156,15 +149,12 @@ public class LazyMessageLiteTest extends TestCase {
}
public void testClearValues() {
- LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder()
- .setNum(115)
- .build();
+ LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder().setNum(115).build();
LazyMessageLite.Builder outerBuilder = LazyMessageLite.newBuilder();
assertEquals(0, outerBuilder.build().getNum());
-
// Set/Clear num
outerBuilder.setNum(100);
@@ -178,9 +168,9 @@ public class LazyMessageLiteTest extends TestCase {
assertEquals(421, outerBuilder.build().getNumWithDefault());
assertFalse(outerBuilder.build().hasInner());
-
// Set/Clear all
- outerBuilder.setNum(100)
+ outerBuilder
+ .setNum(100)
.setInner(inner)
.addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(119))
.addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(122))
@@ -210,23 +200,17 @@ public class LazyMessageLiteTest extends TestCase {
}
public void testMergeValues() {
- LazyMessageLite outerBase = LazyMessageLite.newBuilder()
- .setNumWithDefault(122)
- .build();
-
- LazyInnerMessageLite innerMerging = LazyInnerMessageLite.newBuilder()
- .setNum(115)
- .build();
- LazyMessageLite outerMerging = LazyMessageLite.newBuilder()
- .setNum(119)
- .setInner(innerMerging)
- .setOneofInner(innerMerging)
- .build();
-
- LazyMessageLite merged = LazyMessageLite
- .newBuilder(outerBase)
- .mergeFrom(outerMerging)
- .build();
+ LazyMessageLite outerBase = LazyMessageLite.newBuilder().setNumWithDefault(122).build();
+
+ LazyInnerMessageLite innerMerging = LazyInnerMessageLite.newBuilder().setNum(115).build();
+ LazyMessageLite outerMerging =
+ LazyMessageLite.newBuilder()
+ .setNum(119)
+ .setInner(innerMerging)
+ .setOneofInner(innerMerging)
+ .build();
+
+ LazyMessageLite merged = LazyMessageLite.newBuilder(outerBase).mergeFrom(outerMerging).build();
assertEquals(119, merged.getNum());
assertEquals(122, merged.getNumWithDefault());
assertEquals(115, merged.getInner().getNum());
@@ -236,23 +220,18 @@ public class LazyMessageLiteTest extends TestCase {
}
public void testMergeDefaultValues() {
- LazyInnerMessageLite innerBase = LazyInnerMessageLite.newBuilder()
- .setNum(115)
- .build();
- LazyMessageLite outerBase = LazyMessageLite.newBuilder()
- .setNum(119)
- .setNumWithDefault(122)
- .setInner(innerBase)
- .setOneofInner(innerBase)
- .build();
-
- LazyMessageLite outerMerging = LazyMessageLite.newBuilder()
- .build();
-
- LazyMessageLite merged = LazyMessageLite
- .newBuilder(outerBase)
- .mergeFrom(outerMerging)
- .build();
+ LazyInnerMessageLite innerBase = LazyInnerMessageLite.newBuilder().setNum(115).build();
+ LazyMessageLite outerBase =
+ LazyMessageLite.newBuilder()
+ .setNum(119)
+ .setNumWithDefault(122)
+ .setInner(innerBase)
+ .setOneofInner(innerBase)
+ .build();
+
+ LazyMessageLite outerMerging = LazyMessageLite.getDefaultInstance();
+
+ LazyMessageLite merged = LazyMessageLite.newBuilder(outerBase).mergeFrom(outerMerging).build();
// Merging default-instance shouldn't overwrite values in the base message.
assertEquals(119, merged.getNum());
assertEquals(122, merged.getNumWithDefault());
@@ -264,7 +243,7 @@ public class LazyMessageLiteTest extends TestCase {
// Regression test for b/28198805.
public void testMergeOneofMessages() throws Exception {
- LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder().build();
+ LazyInnerMessageLite inner = LazyInnerMessageLite.getDefaultInstance();
LazyMessageLite outer = LazyMessageLite.newBuilder().setOneofInner(inner).build();
ByteString data1 = outer.toByteString();
@@ -280,18 +259,11 @@ public class LazyMessageLiteTest extends TestCase {
}
public void testSerialize() throws InvalidProtocolBufferException {
- LazyNestedInnerMessageLite nested = LazyNestedInnerMessageLite.newBuilder()
- .setNum(3)
- .build();
- LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder()
- .setNum(2)
- .setNested(nested)
- .build();
- LazyMessageLite outer = LazyMessageLite.newBuilder()
- .setNum(1)
- .setInner(inner)
- .setOneofInner(inner)
- .build();
+ LazyNestedInnerMessageLite nested = LazyNestedInnerMessageLite.newBuilder().setNum(3).build();
+ LazyInnerMessageLite inner =
+ LazyInnerMessageLite.newBuilder().setNum(2).setNested(nested).build();
+ LazyMessageLite outer =
+ LazyMessageLite.newBuilder().setNum(1).setInner(inner).setOneofInner(inner).build();
ByteString bytes = outer.toByteString();
assertEquals(bytes.size(), outer.getSerializedSize());
@@ -299,18 +271,18 @@ public class LazyMessageLiteTest extends TestCase {
LazyMessageLite deserialized = LazyMessageLite.parseFrom(bytes);
assertEquals(1, deserialized.getNum());
- assertEquals(421, deserialized.getNumWithDefault());
+ assertEquals(421, deserialized.getNumWithDefault());
- assertEquals(2, deserialized.getInner().getNum());
- assertEquals(42, deserialized.getInner().getNumWithDefault());
+ assertEquals(2, deserialized.getInner().getNum());
+ assertEquals(42, deserialized.getInner().getNumWithDefault());
- assertEquals(3, deserialized.getInner().getNested().getNum());
- assertEquals(4, deserialized.getInner().getNested().getNumWithDefault());
+ assertEquals(3, deserialized.getInner().getNested().getNum());
+ assertEquals(4, deserialized.getInner().getNested().getNumWithDefault());
- assertEquals(2, deserialized.getOneofInner().getNum());
- assertEquals(42, deserialized.getOneofInner().getNumWithDefault());
- assertEquals(3, deserialized.getOneofInner().getNested().getNum());
- assertEquals(4, deserialized.getOneofInner().getNested().getNumWithDefault());
+ assertEquals(2, deserialized.getOneofInner().getNum());
+ assertEquals(42, deserialized.getOneofInner().getNumWithDefault());
+ assertEquals(3, deserialized.getOneofInner().getNested().getNum());
+ assertEquals(4, deserialized.getOneofInner().getNested().getNumWithDefault());
assertEquals(bytes, deserialized.toByteString());
}
@@ -318,8 +290,7 @@ public class LazyMessageLiteTest extends TestCase {
public void testExtensions() throws Exception {
LazyInnerMessageLite.Builder innerBuilder = LazyInnerMessageLite.newBuilder();
innerBuilder.setExtension(
- LazyExtension.extension, LazyExtension.newBuilder()
- .setName("name").build());
+ LazyExtension.extension, LazyExtension.newBuilder().setName("name").build());
assertTrue(innerBuilder.hasExtension(LazyExtension.extension));
assertEquals("name", innerBuilder.getExtension(LazyExtension.extension).getName());
@@ -327,8 +298,7 @@ public class LazyMessageLiteTest extends TestCase {
assertTrue(innerMessage.hasExtension(LazyExtension.extension));
assertEquals("name", innerMessage.getExtension(LazyExtension.extension).getName());
- LazyMessageLite lite = LazyMessageLite.newBuilder()
- .setInner(innerMessage).build();
+ LazyMessageLite lite = LazyMessageLite.newBuilder().setInner(innerMessage).build();
assertTrue(lite.getInner().hasExtension(LazyExtension.extension));
assertEquals("name", lite.getInner().getExtension(LazyExtension.extension).getName());
}
diff --git a/java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java b/java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java
index 2fc3124d..24d0038b 100644
--- a/java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java
@@ -46,13 +46,13 @@ import junit.framework.TestCase;
*/
public class LazyStringArrayListTest extends TestCase {
- private static String STRING_A = "A";
- private static String STRING_B = "B";
- private static String STRING_C = "C";
+ private static final String STRING_A = "A";
+ private static final String STRING_B = "B";
+ private static final String STRING_C = "C";
- private static ByteString BYTE_STRING_A = ByteString.copyFromUtf8("A");
- private static ByteString BYTE_STRING_B = ByteString.copyFromUtf8("B");
- private static ByteString BYTE_STRING_C = ByteString.copyFromUtf8("C");
+ private static final ByteString BYTE_STRING_A = ByteString.copyFromUtf8("A");
+ private static final ByteString BYTE_STRING_B = ByteString.copyFromUtf8("B");
+ private static final ByteString BYTE_STRING_C = ByteString.copyFromUtf8("C");
public void testJustStrings() {
LazyStringArrayList list = new LazyStringArrayList();
@@ -175,7 +175,7 @@ public class LazyStringArrayListTest extends TestCase {
assertSame(BYTE_STRING_B, list2.getByteString(1));
assertSame(BYTE_STRING_C, list2.getByteString(2));
}
-
+
public void testModificationWithIteration() {
LazyStringArrayList list = new LazyStringArrayList();
list.addAll(asList(STRING_A, STRING_B, STRING_C));
@@ -183,12 +183,12 @@ public class LazyStringArrayListTest extends TestCase {
assertEquals(3, list.size());
assertEquals(STRING_A, list.get(0));
assertEquals(STRING_A, iterator.next());
-
+
// Does not structurally modify.
iterator = list.iterator();
list.set(0, STRING_B);
iterator.next();
-
+
list.remove(0);
try {
iterator.next();
@@ -196,7 +196,7 @@ public class LazyStringArrayListTest extends TestCase {
} catch (ConcurrentModificationException e) {
// expected
}
-
+
iterator = list.iterator();
list.add(0, STRING_C);
try {
@@ -206,7 +206,7 @@ public class LazyStringArrayListTest extends TestCase {
// expected
}
}
-
+
public void testMakeImmutable() {
LazyStringArrayList list = new LazyStringArrayList();
list.add(STRING_A);
@@ -214,52 +214,52 @@ public class LazyStringArrayListTest extends TestCase {
list.add(STRING_C);
list.makeImmutable();
assertGenericListImmutable(list, STRING_A);
-
+
// LazyStringArrayList has extra methods not covered in the generic
// assertion.
-
+
try {
list.add(BYTE_STRING_A.toByteArray());
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.add(BYTE_STRING_A);
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.addAllByteArray(Collections.singletonList(BYTE_STRING_A.toByteArray()));
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.addAllByteString(asList(BYTE_STRING_A));
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.mergeFrom(new LazyStringArrayList());
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.set(0, BYTE_STRING_A.toByteArray());
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.set(0, BYTE_STRING_A);
fail();
@@ -267,20 +267,20 @@ public class LazyStringArrayListTest extends TestCase {
// expected
}
}
-
+
public void testImmutabilityPropagation() {
LazyStringArrayList list = new LazyStringArrayList();
list.add(STRING_A);
list.makeImmutable();
assertGenericListImmutable(list.asByteStringList(), BYTE_STRING_A);
-
+
// Arrays use reference equality so need to retrieve the underlying value
// to properly test deep immutability.
List<byte[]> byteArrayList = list.asByteArrayList();
assertGenericListImmutable(byteArrayList, byteArrayList.get(0));
}
-
+
@SuppressWarnings("unchecked")
private static <T> void assertGenericListImmutable(List<T> list, T value) {
try {
@@ -289,21 +289,21 @@ public class LazyStringArrayListTest extends TestCase {
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.add(0, value);
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.addAll(asList(value));
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.addAll(0, asList(value));
fail();
@@ -317,42 +317,42 @@ public class LazyStringArrayListTest extends TestCase {
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.remove(0);
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.remove(value);
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.removeAll(asList(value));
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.retainAll(asList());
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.retainAll(asList());
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.set(0, value);
fail();
diff --git a/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java b/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java
index 006e4933..18c9c74e 100644
--- a/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java
@@ -30,44 +30,42 @@
package com.google.protobuf;
-
import protobuf_unittest.UnittestProto;
import java.io.IOException;
import junit.framework.TestCase;
/**
- * Tests to make sure the lazy conversion of UTF8-encoded byte arrays to
- * strings works correctly.
+ * Tests to make sure the lazy conversion of UTF8-encoded byte arrays to strings works correctly.
*
* @author jonp@google.com (Jon Perlow)
*/
public class LazyStringEndToEndTest extends TestCase {
- private static ByteString TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8 =
- ByteString.copyFrom(new byte[] {
- 114, 4, -1, 0, -1, 0, -30, 2, 4, -1,
- 0, -1, 0, -30, 2, 4, -1, 0, -1, 0, });
+ private static final ByteString TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8 =
+ ByteString.copyFrom(
+ new byte[] {
+ 114, 4, -1, 0, -1, 0, -30, 2, 4, -1,
+ 0, -1, 0, -30, 2, 4, -1, 0, -1, 0,
+ });
private ByteString encodedTestAllTypes;
@Override
protected void setUp() throws Exception {
super.setUp();
- this.encodedTestAllTypes = UnittestProto.TestAllTypes.newBuilder()
- .setOptionalString("foo")
- .addRepeatedString("bar")
- .addRepeatedString("baz")
- .build()
- .toByteString();
+ this.encodedTestAllTypes =
+ UnittestProto.TestAllTypes.newBuilder()
+ .setOptionalString("foo")
+ .addRepeatedString("bar")
+ .addRepeatedString("baz")
+ .build()
+ .toByteString();
}
- /**
- * Tests that an invalid UTF8 string will roundtrip through a parse
- * and serialization.
- */
+ /** Tests that an invalid UTF8 string will roundtrip through a parse and serialization. */
public void testParseAndSerialize() throws InvalidProtocolBufferException {
- UnittestProto.TestAllTypes tV2 = UnittestProto.TestAllTypes.parseFrom(
- TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8);
+ UnittestProto.TestAllTypes tV2 =
+ UnittestProto.TestAllTypes.parseFrom(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8);
ByteString bytes = tV2.toByteString();
assertEquals(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8, bytes);
@@ -77,33 +75,31 @@ public class LazyStringEndToEndTest extends TestCase {
}
public void testParseAndWrite() throws IOException {
- UnittestProto.TestAllTypes tV2 = UnittestProto.TestAllTypes.parseFrom(
- TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8);
+ UnittestProto.TestAllTypes tV2 =
+ UnittestProto.TestAllTypes.parseFrom(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8);
byte[] sink = new byte[TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8.size()];
CodedOutputStream outputStream = CodedOutputStream.newInstance(sink);
tV2.writeTo(outputStream);
outputStream.flush();
- assertEquals(
- TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8,
- ByteString.copyFrom(sink));
+ assertEquals(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8, ByteString.copyFrom(sink));
}
-
+
public void testCaching() {
String a = "a";
String b = "b";
String c = "c";
- UnittestProto.TestAllTypes proto = UnittestProto.TestAllTypes.newBuilder()
- .setOptionalString(a)
- .addRepeatedString(b)
- .addRepeatedString(c)
- .build();
+ UnittestProto.TestAllTypes proto =
+ UnittestProto.TestAllTypes.newBuilder()
+ .setOptionalString(a)
+ .addRepeatedString(b)
+ .addRepeatedString(c)
+ .build();
// String should be the one we passed it.
assertSame(a, proto.getOptionalString());
assertSame(b, proto.getRepeatedString(0));
assertSame(c, proto.getRepeatedString(1));
-
// Ensure serialization keeps strings cached.
proto.toByteString();
@@ -114,8 +110,7 @@ public class LazyStringEndToEndTest extends TestCase {
}
public void testNoStringCachingIfOnlyBytesAccessed() throws Exception {
- UnittestProto.TestAllTypes proto =
- UnittestProto.TestAllTypes.parseFrom(encodedTestAllTypes);
+ UnittestProto.TestAllTypes proto = UnittestProto.TestAllTypes.parseFrom(encodedTestAllTypes);
ByteString optional = proto.getOptionalStringBytes();
assertSame(optional, proto.getOptionalStringBytes());
assertSame(optional, proto.toBuilder().getOptionalStringBytes());
diff --git a/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java b/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java
index eac47448..9e5adb70 100644
--- a/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java
@@ -46,9 +46,9 @@ import java.util.NoSuchElementException;
import junit.framework.TestCase;
/**
- * Test {@code LiteralByteString} by setting up a reference string in {@link #setUp()}.
- * This class is designed to be extended for testing extensions of {@code LiteralByteString}
- * such as {@code BoundedByteString}, see {@link BoundedByteStringTest}.
+ * Test {@code LiteralByteString} by setting up a reference string in {@link #setUp()}. This class
+ * is designed to be extended for testing extensions of {@code LiteralByteString} such as {@code
+ * BoundedByteString}, see {@link BoundedByteStringTest}.
*
* @author carlanton@google.com (Carl Haverl)
*/
@@ -114,7 +114,9 @@ public class LiteralByteStringTest extends TestCase {
}
public void testSize() {
- assertEquals(classUnderTest + " must have the expected size", referenceBytes.length,
+ assertEquals(
+ classUnderTest + " must have the expected size",
+ referenceBytes.length,
stringUnderTest.size());
}
@@ -146,10 +148,9 @@ public class LiteralByteStringTest extends TestCase {
try {
// Copy one too many bytes
- stringUnderTest.copyTo(destination, stringUnderTest.size() + 1 - length,
- destinationOffset, length);
- fail("Should have thrown an exception when copying too many bytes of a "
- + classUnderTest);
+ stringUnderTest.copyTo(
+ destination, stringUnderTest.size() + 1 - length, destinationOffset, length);
+ fail("Should have thrown an exception when copying too many bytes of a " + classUnderTest);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -157,8 +158,9 @@ public class LiteralByteStringTest extends TestCase {
try {
// Copy with illegal negative sourceOffset
stringUnderTest.copyTo(destination, -1, destinationOffset, length);
- fail("Should have thrown an exception when given a negative sourceOffset in "
- + classUnderTest);
+ fail(
+ "Should have thrown an exception when given a negative sourceOffset in "
+ + classUnderTest);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -166,8 +168,9 @@ public class LiteralByteStringTest extends TestCase {
try {
// Copy with illegal negative destinationOffset
stringUnderTest.copyTo(destination, 0, -1, length);
- fail("Should have thrown an exception when given a negative destinationOffset in "
- + classUnderTest);
+ fail(
+ "Should have thrown an exception when given a negative destinationOffset in "
+ + classUnderTest);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -175,8 +178,7 @@ public class LiteralByteStringTest extends TestCase {
try {
// Copy with illegal negative size
stringUnderTest.copyTo(destination, 0, 0, -1);
- fail("Should have thrown an exception when given a negative size in "
- + classUnderTest);
+ fail("Should have thrown an exception when given a negative size in " + classUnderTest);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -184,8 +186,9 @@ public class LiteralByteStringTest extends TestCase {
try {
// Copy with illegal too-large sourceOffset
stringUnderTest.copyTo(destination, 2 * stringUnderTest.size(), 0, length);
- fail("Should have thrown an exception when the destinationOffset is too large in "
- + classUnderTest);
+ fail(
+ "Should have thrown an exception when the destinationOffset is too large in "
+ + classUnderTest);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -193,8 +196,9 @@ public class LiteralByteStringTest extends TestCase {
try {
// Copy with illegal too-large destinationOffset
stringUnderTest.copyTo(destination, 0, 2 * destination.length, length);
- fail("Should have thrown an exception when the destinationOffset is too large in "
- + classUnderTest);
+ fail(
+ "Should have thrown an exception when the destinationOffset is too large in "
+ + classUnderTest);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -203,7 +207,8 @@ public class LiteralByteStringTest extends TestCase {
public void testCopyTo_ByteBuffer() {
ByteBuffer myBuffer = ByteBuffer.allocate(referenceBytes.length);
stringUnderTest.copyTo(myBuffer);
- assertTrue(classUnderTest + ".copyTo(ByteBuffer) must give back the same bytes",
+ assertTrue(
+ classUnderTest + ".copyTo(ByteBuffer) must give back the same bytes",
Arrays.equals(referenceBytes, myBuffer.array()));
}
@@ -233,17 +238,15 @@ public class LiteralByteStringTest extends TestCase {
}
/**
- * Discards {@code n} bytes of data from the input stream. This method
- * will block until the full amount has been skipped. Does not close the
- * stream.
+ * Discards {@code n} bytes of data from the input stream. This method will block until the full
+ * amount has been skipped. Does not close the stream.
+ *
* <p>Copied from com.google.common.io.ByteStreams to avoid adding dependency.
*
* @param in the input stream to read from
* @param n the number of bytes to skip
- * @throws EOFException if this stream reaches the end before skipping all
- * the bytes
- * @throws IOException if an I/O error occurs, or the stream does not
- * support skipping
+ * @throws EOFException if this stream reaches the end before skipping all the bytes
+ * @throws IOException if an I/O error occurs, or the stream does not support skipping
*/
static void skipFully(InputStream in, long n) throws IOException {
long toSkip = n;
@@ -253,8 +256,12 @@ public class LiteralByteStringTest extends TestCase {
// Force a blocking read to avoid infinite loop
if (in.read() == -1) {
long skipped = toSkip - n;
- throw new EOFException("reached end of stream after skipping "
- + skipped + " bytes; " + toSkip + " bytes expected");
+ throw new EOFException(
+ "reached end of stream after skipping "
+ + skipped
+ + " bytes; "
+ + toSkip
+ + " bytes expected");
}
n--;
} else {
@@ -269,7 +276,8 @@ public class LiteralByteStringTest extends TestCase {
assertTrue(byteBuffer.remaining() == referenceBytes.length);
assertTrue(byteBuffer.isReadOnly());
byteBuffer.get(roundTripBytes);
- assertTrue(classUnderTest + ".asReadOnlyByteBuffer() must give back the same bytes",
+ assertTrue(
+ classUnderTest + ".asReadOnlyByteBuffer() must give back the same bytes",
Arrays.equals(referenceBytes, roundTripBytes));
}
@@ -285,13 +293,15 @@ public class LiteralByteStringTest extends TestCase {
bytesSeen += thisLength;
}
assertTrue(bytesSeen == referenceBytes.length);
- assertTrue(classUnderTest + ".asReadOnlyByteBufferTest() must give back the same bytes",
+ assertTrue(
+ classUnderTest + ".asReadOnlyByteBufferTest() must give back the same bytes",
Arrays.equals(referenceBytes, roundTripBytes));
}
public void testToByteArray() {
byte[] roundTripBytes = stringUnderTest.toByteArray();
- assertTrue(classUnderTest + ".toByteArray() must give back the same bytes",
+ assertTrue(
+ classUnderTest + ".toByteArray() must give back the same bytes",
Arrays.equals(referenceBytes, roundTripBytes));
}
@@ -299,78 +309,85 @@ public class LiteralByteStringTest extends TestCase {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
stringUnderTest.writeTo(bos);
byte[] roundTripBytes = bos.toByteArray();
- assertTrue(classUnderTest + ".writeTo() must give back the same bytes",
+ assertTrue(
+ classUnderTest + ".writeTo() must give back the same bytes",
Arrays.equals(referenceBytes, roundTripBytes));
}
public void testWriteToShouldNotExposeInternalBufferToOutputStream() throws IOException {
- OutputStream os = new OutputStream() {
- @Override
- public void write(byte[] b, int off, int len) {
- Arrays.fill(b, off, off + len, (byte) 0);
- }
-
- @Override
- public void write(int b) {
- throw new UnsupportedOperationException();
- }
- };
+ OutputStream os =
+ new OutputStream() {
+ @Override
+ public void write(byte[] b, int off, int len) {
+ Arrays.fill(b, off, off + len, (byte) 0);
+ }
+
+ @Override
+ public void write(int b) {
+ throw new UnsupportedOperationException();
+ }
+ };
stringUnderTest.writeTo(os);
- assertTrue(classUnderTest + ".writeTo() must not grant access to underlying array",
+ assertTrue(
+ classUnderTest + ".writeTo() must not grant access to underlying array",
Arrays.equals(referenceBytes, stringUnderTest.toByteArray()));
}
public void testWriteToInternalShouldExposeInternalBufferToOutputStream() throws IOException {
- OutputStream os = new OutputStream() {
- @Override
- public void write(byte[] b, int off, int len) {
- Arrays.fill(b, off, off + len, (byte) 0);
- }
-
- @Override
- public void write(int b) {
- throw new UnsupportedOperationException();
- }
- };
+ OutputStream os =
+ new OutputStream() {
+ @Override
+ public void write(byte[] b, int off, int len) {
+ Arrays.fill(b, off, off + len, (byte) 0);
+ }
+
+ @Override
+ public void write(int b) {
+ throw new UnsupportedOperationException();
+ }
+ };
stringUnderTest.writeToInternal(os, 0, stringUnderTest.size());
byte[] allZeros = new byte[stringUnderTest.size()];
- assertTrue(classUnderTest + ".writeToInternal() must grant access to underlying array",
+ assertTrue(
+ classUnderTest + ".writeToInternal() must grant access to underlying array",
Arrays.equals(allZeros, stringUnderTest.toByteArray()));
}
public void testWriteToShouldExposeInternalBufferToByteOutput() throws IOException {
- ByteOutput out = new ByteOutput() {
- @Override
- public void write(byte value) throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void write(byte[] value, int offset, int length) throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void writeLazy(byte[] value, int offset, int length) throws IOException {
- Arrays.fill(value, offset, offset + length, (byte) 0);
- }
-
- @Override
- public void write(ByteBuffer value) throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void writeLazy(ByteBuffer value) throws IOException {
- throw new UnsupportedOperationException();
- }
- };
+ ByteOutput out =
+ new ByteOutput() {
+ @Override
+ public void write(byte value) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void write(byte[] value, int offset, int length) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeLazy(byte[] value, int offset, int length) throws IOException {
+ Arrays.fill(value, offset, offset + length, (byte) 0);
+ }
+
+ @Override
+ public void write(ByteBuffer value) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeLazy(ByteBuffer value) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+ };
stringUnderTest.writeTo(out);
byte[] allZeros = new byte[stringUnderTest.size()];
- assertTrue(classUnderTest + ".writeToInternal() must grant access to underlying array",
+ assertTrue(
+ classUnderTest + ".writeToInternal() must grant access to underlying array",
Arrays.equals(allZeros, stringUnderTest.toByteArray()));
}
@@ -378,21 +395,22 @@ public class LiteralByteStringTest extends TestCase {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ByteString.Output output = ByteString.newOutput();
stringUnderTest.writeTo(output);
- assertEquals("Output Size returns correct result",
- output.size(), stringUnderTest.size());
+ assertEquals("Output Size returns correct result", output.size(), stringUnderTest.size());
output.writeTo(bos);
- assertTrue("Output.writeTo() must give back the same bytes",
+ assertTrue(
+ "Output.writeTo() must give back the same bytes",
Arrays.equals(referenceBytes, bos.toByteArray()));
// write the output stream to itself! This should cause it to double
output.writeTo(output);
- assertEquals("Writing an output stream to itself is successful",
- stringUnderTest.concat(stringUnderTest), output.toByteString());
+ assertEquals(
+ "Writing an output stream to itself is successful",
+ stringUnderTest.concat(stringUnderTest),
+ output.toByteString());
output.reset();
assertEquals("Output.reset() resets the output", 0, output.size());
- assertEquals("Output.reset() resets the output",
- ByteString.EMPTY, output.toByteString());
+ assertEquals("Output.reset() resets the output", ByteString.EMPTY, output.toByteString());
}
public void testToString() throws UnsupportedEncodingException {
@@ -410,9 +428,10 @@ public class LiteralByteStringTest extends TestCase {
}
public void testToString_returnsCanonicalEmptyString() {
- assertSame(classUnderTest + " must be the same string references",
+ assertSame(
+ classUnderTest + " must be the same string references",
ByteString.EMPTY.toString(Internal.UTF_8),
- ByteString.wrap(new byte[]{}).toString(Internal.UTF_8));
+ ByteString.wrap(new byte[] {}).toString(Internal.UTF_8));
}
public void testToString_raisesException() {
@@ -434,17 +453,23 @@ public class LiteralByteStringTest extends TestCase {
public void testEquals() {
assertEquals(classUnderTest + " must not equal null", false, stringUnderTest.equals(null));
assertEquals(classUnderTest + " must equal self", stringUnderTest, stringUnderTest);
- assertFalse(classUnderTest + " must not equal the empty string",
+ assertFalse(
+ classUnderTest + " must not equal the empty string",
stringUnderTest.equals(ByteString.EMPTY));
- assertEquals(classUnderTest + " empty strings must be equal",
- ByteString.wrap(new byte[]{}), stringUnderTest.substring(55, 55));
- assertEquals(classUnderTest + " must equal another string with the same value",
- stringUnderTest, ByteString.wrap(referenceBytes));
+ assertEquals(
+ classUnderTest + " empty strings must be equal",
+ ByteString.wrap(new byte[] {}),
+ stringUnderTest.substring(55, 55));
+ assertEquals(
+ classUnderTest + " must equal another string with the same value",
+ stringUnderTest,
+ ByteString.wrap(referenceBytes));
byte[] mungedBytes = new byte[referenceBytes.length];
System.arraycopy(referenceBytes, 0, mungedBytes, 0, referenceBytes.length);
mungedBytes[mungedBytes.length - 5] = (byte) (mungedBytes[mungedBytes.length - 5] ^ 0xFF);
- assertFalse(classUnderTest + " must not equal every string with the same length",
+ assertFalse(
+ classUnderTest + " must not equal every string with the same length",
stringUnderTest.equals(ByteString.wrap(mungedBytes)));
}
@@ -454,32 +479,35 @@ public class LiteralByteStringTest extends TestCase {
}
public void testPeekCachedHashCode() {
- assertEquals(classUnderTest + ".peekCachedHashCode() should return zero at first", 0,
+ assertEquals(
+ classUnderTest + ".peekCachedHashCode() should return zero at first",
+ 0,
stringUnderTest.peekCachedHashCode());
stringUnderTest.hashCode();
- assertEquals(classUnderTest + ".peekCachedHashCode should return zero at first",
- expectedHashCode, stringUnderTest.peekCachedHashCode());
+ assertEquals(
+ classUnderTest + ".peekCachedHashCode should return zero at first",
+ expectedHashCode,
+ stringUnderTest.peekCachedHashCode());
}
public void testPartialHash() {
// partialHash() is more strenuously tested elsewhere by testing hashes of substrings.
// This test would fail if the expected hash were 1. It's not.
int hash = stringUnderTest.partialHash(stringUnderTest.size(), 0, stringUnderTest.size());
- assertEquals(classUnderTest + ".partialHash() must yield expected hashCode",
- expectedHashCode, hash);
+ assertEquals(
+ classUnderTest + ".partialHash() must yield expected hashCode", expectedHashCode, hash);
}
public void testNewInput() throws IOException {
InputStream input = stringUnderTest.newInput();
- assertEquals("InputStream.available() returns correct value",
- stringUnderTest.size(), input.available());
+ assertEquals(
+ "InputStream.available() returns correct value", stringUnderTest.size(), input.available());
boolean stillEqual = true;
for (byte referenceByte : referenceBytes) {
int expectedInt = (referenceByte & 0xFF);
stillEqual = (expectedInt == input.read());
}
- assertEquals("InputStream.available() returns correct value",
- 0, input.available());
+ assertEquals("InputStream.available() returns correct value", 0, input.available());
assertTrue(classUnderTest + " must give the same bytes from the InputStream", stillEqual);
assertEquals(classUnderTest + " InputStream must now be exhausted", -1, input.read());
}
@@ -490,43 +518,44 @@ public class LiteralByteStringTest extends TestCase {
int nearEndIndex = stringSize * 2 / 3;
long skipped1 = input.skip(nearEndIndex);
assertEquals("InputStream.skip()", skipped1, nearEndIndex);
- assertEquals("InputStream.available()",
- stringSize - skipped1, input.available());
+ assertEquals("InputStream.available()", stringSize - skipped1, input.available());
assertTrue("InputStream.mark() is available", input.markSupported());
input.mark(0);
- assertEquals("InputStream.skip(), read()",
- stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read());
- assertEquals("InputStream.available()",
- stringSize - skipped1 - 1, input.available());
+ assertEquals(
+ "InputStream.skip(), read()", stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read());
+ assertEquals("InputStream.available()", stringSize - skipped1 - 1, input.available());
long skipped2 = input.skip(stringSize);
- assertEquals("InputStream.skip() incomplete",
- skipped2, stringSize - skipped1 - 1);
+ assertEquals("InputStream.skip() incomplete", skipped2, stringSize - skipped1 - 1);
assertEquals("InputStream.skip(), no more input", 0, input.available());
assertEquals("InputStream.skip(), no more input", -1, input.read());
input.reset();
- assertEquals("InputStream.reset() succeded",
- stringSize - skipped1, input.available());
- assertEquals("InputStream.reset(), read()",
- stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read());
+ assertEquals("InputStream.reset() succeded", stringSize - skipped1, input.available());
+ assertEquals(
+ "InputStream.reset(), read()", stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read());
}
public void testNewCodedInput() throws IOException {
CodedInputStream cis = stringUnderTest.newCodedInput();
byte[] roundTripBytes = cis.readRawBytes(referenceBytes.length);
- assertTrue(classUnderTest + " must give the same bytes back from the CodedInputStream",
+ assertTrue(
+ classUnderTest + " must give the same bytes back from the CodedInputStream",
Arrays.equals(referenceBytes, roundTripBytes));
assertTrue(classUnderTest + " CodedInputStream must now be exhausted", cis.isAtEnd());
}
/**
- * Make sure we keep things simple when concatenating with empty. See also
- * {@link ByteStringTest#testConcat_empty()}.
+ * Make sure we keep things simple when concatenating with empty. See also {@link
+ * ByteStringTest#testConcat_empty()}.
*/
public void testConcat_empty() {
- assertSame(classUnderTest + " concatenated with empty must give " + classUnderTest,
- stringUnderTest.concat(ByteString.EMPTY), stringUnderTest);
- assertSame("empty concatenated with " + classUnderTest + " must give " + classUnderTest,
- ByteString.EMPTY.concat(stringUnderTest), stringUnderTest);
+ assertSame(
+ classUnderTest + " concatenated with empty must give " + classUnderTest,
+ stringUnderTest.concat(ByteString.EMPTY),
+ stringUnderTest);
+ assertSame(
+ "empty concatenated with " + classUnderTest + " must give " + classUnderTest,
+ ByteString.EMPTY.concat(stringUnderTest),
+ stringUnderTest);
}
public void testJavaSerialization() throws Exception {
diff --git a/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java b/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java
index 14a8e159..4b5e6c78 100644
--- a/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java
@@ -45,10 +45,8 @@ import junit.framework.TestCase;
*/
public class LongArrayListTest extends TestCase {
- private static final LongArrayList UNARY_LIST =
- newImmutableLongArrayList(1);
- private static final LongArrayList TERTIARY_LIST =
- newImmutableLongArrayList(1, 2, 3);
+ private static final LongArrayList UNARY_LIST = newImmutableLongArrayList(1);
+ private static final LongArrayList TERTIARY_LIST = newImmutableLongArrayList(1, 2, 3);
private LongArrayList list;
@@ -225,9 +223,7 @@ public class LongArrayListTest extends TestCase {
for (int i = 0; i < 6; i++) {
list.add(Long.valueOf(5 + i));
}
- assertEquals(
- asList(0L, 1L, 4L, 2L, 3L, 5L, 6L, 7L, 8L, 9L, 10L),
- list);
+ assertEquals(asList(0L, 1L, 4L, 2L, 3L, 5L, 6L, 7L, 8L, 9L, 10L), list);
try {
list.add(-1, 5L);
@@ -299,16 +295,14 @@ public class LongArrayListTest extends TestCase {
}
public void testRemoveEndOfCapacity() {
- LongList toRemove =
- LongArrayList.emptyList().mutableCopyWithCapacity(1);
+ LongList toRemove = LongArrayList.emptyList().mutableCopyWithCapacity(1);
toRemove.addLong(3);
toRemove.remove(0);
assertEquals(0, toRemove.size());
}
public void testSublistRemoveEndOfCapacity() {
- LongList toRemove =
- LongArrayList.emptyList().mutableCopyWithCapacity(1);
+ LongList toRemove = LongArrayList.emptyList().mutableCopyWithCapacity(1);
toRemove.addLong(3);
toRemove.subList(0, 1).clear();
assertEquals(0, toRemove.size());
diff --git a/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java b/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java
index da9195f9..41fef073 100644
--- a/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java
+++ b/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java
@@ -43,9 +43,7 @@ import java.util.HashMap;
import java.util.Map;
import junit.framework.TestCase;
-/**
- * Unit tests for map fields.
- */
+/** Unit tests for map fields. */
public final class MapForProto2LiteTest extends TestCase {
private void setMapValues(TestMap.Builder builder) {
@@ -53,23 +51,18 @@ public final class MapForProto2LiteTest extends TestCase {
.putInt32ToInt32Field(1, 11)
.putInt32ToInt32Field(2, 22)
.putInt32ToInt32Field(3, 33)
-
.putInt32ToStringField(1, "11")
.putInt32ToStringField(2, "22")
.putInt32ToStringField(3, "33")
-
.putInt32ToBytesField(1, TestUtil.toBytes("11"))
.putInt32ToBytesField(2, TestUtil.toBytes("22"))
.putInt32ToBytesField(3, TestUtil.toBytes("33"))
-
.putInt32ToEnumField(1, TestMap.EnumValue.FOO)
.putInt32ToEnumField(2, TestMap.EnumValue.BAR)
.putInt32ToEnumField(3, TestMap.EnumValue.BAZ)
-
.putInt32ToMessageField(1, MessageValue.newBuilder().setValue(11).build())
.putInt32ToMessageField(2, MessageValue.newBuilder().setValue(22).build())
.putInt32ToMessageField(3, MessageValue.newBuilder().setValue(33).build())
-
.putStringToInt32Field("1", 11)
.putStringToInt32Field("2", 22)
.putStringToInt32Field("3", 33);
@@ -129,23 +122,18 @@ public final class MapForProto2LiteTest extends TestCase {
.putInt32ToInt32Field(1, 111)
.removeInt32ToInt32Field(2)
.putInt32ToInt32Field(4, 44)
-
.putInt32ToStringField(1, "111")
.removeInt32ToStringField(2)
.putInt32ToStringField(4, "44")
-
.putInt32ToBytesField(1, TestUtil.toBytes("111"))
.removeInt32ToBytesField(2)
.putInt32ToBytesField(4, TestUtil.toBytes("44"))
-
.putInt32ToEnumField(1, TestMap.EnumValue.BAR)
.removeInt32ToEnumField(2)
.putInt32ToEnumField(4, TestMap.EnumValue.QUX)
-
.putInt32ToMessageField(1, MessageValue.newBuilder().setValue(111).build())
.removeInt32ToMessageField(2)
.putInt32ToMessageField(4, MessageValue.newBuilder().setValue(44).build())
-
.putStringToInt32Field("1", 111)
.removeStringToInt32Field("2")
.putStringToInt32Field("4", 44);
@@ -265,8 +253,7 @@ public final class MapForProto2LiteTest extends TestCase {
}
public void testMutableMapLifecycle() {
- TestMap.Builder builder = TestMap.newBuilder()
- .putInt32ToInt32Field(1, 2);
+ TestMap.Builder builder = TestMap.newBuilder().putInt32ToInt32Field(1, 2);
assertEquals(newMap(1, 2), builder.build().getInt32ToInt32Field());
assertEquals(newMap(1, 2), builder.getInt32ToInt32Field());
builder.putInt32ToInt32Field(2, 3);
@@ -277,8 +264,7 @@ public final class MapForProto2LiteTest extends TestCase {
assertEquals(newMap(1, TestMap.EnumValue.BAR), builder.getInt32ToEnumField());
builder.putInt32ToEnumField(2, TestMap.EnumValue.FOO);
assertEquals(
- newMap(1, TestMap.EnumValue.BAR, 2, TestMap.EnumValue.FOO),
- builder.getInt32ToEnumField());
+ newMap(1, TestMap.EnumValue.BAR, 2, TestMap.EnumValue.FOO), builder.getInt32ToEnumField());
builder.putInt32ToStringField(1, "1");
assertEquals(newMap(1, "1"), builder.build().getInt32ToStringField());
@@ -287,14 +273,18 @@ public final class MapForProto2LiteTest extends TestCase {
assertEquals(newMap(1, "1", 2, "2"), builder.getInt32ToStringField());
builder.putInt32ToMessageField(1, TestMap.MessageValue.getDefaultInstance());
- assertEquals(newMap(1, TestMap.MessageValue.getDefaultInstance()),
+ assertEquals(
+ newMap(1, TestMap.MessageValue.getDefaultInstance()),
builder.build().getInt32ToMessageField());
- assertEquals(newMap(1, TestMap.MessageValue.getDefaultInstance()),
- builder.getInt32ToMessageField());
+ assertEquals(
+ newMap(1, TestMap.MessageValue.getDefaultInstance()), builder.getInt32ToMessageField());
builder.putInt32ToMessageField(2, TestMap.MessageValue.getDefaultInstance());
assertEquals(
- newMap(1, TestMap.MessageValue.getDefaultInstance(),
- 2, TestMap.MessageValue.getDefaultInstance()),
+ newMap(
+ 1,
+ TestMap.MessageValue.getDefaultInstance(),
+ 2,
+ TestMap.MessageValue.getDefaultInstance()),
builder.getInt32ToMessageField());
}
@@ -405,30 +395,22 @@ public final class MapForProto2LiteTest extends TestCase {
ByteString bytes = TestUtil.toBytes("SOME BYTES");
String stringKey = "a string key";
- TestMap map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToInt32Field(5, bytes)
- .build());
+ TestMap map =
+ tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToInt32Field(5, bytes).build());
assertEquals(0, map.getInt32ToInt32FieldOrDefault(5, -1));
- map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToStringField(stringKey, 5)
- .build());
+ map = tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToStringField(stringKey, 5).build());
assertEquals("", map.getInt32ToStringFieldOrDefault(0, null));
- map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToBytesField(stringKey, 5)
- .build());
+ map = tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToBytesField(stringKey, 5).build());
assertEquals(map.getInt32ToBytesFieldOrDefault(0, null), ByteString.EMPTY);
- map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToEnumField(stringKey, bytes)
- .build());
+ map =
+ tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToEnumField(stringKey, bytes).build());
assertEquals(TestMap.EnumValue.FOO, map.getInt32ToEnumFieldOrDefault(0, null));
try {
- tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToMessageField(stringKey, bytes)
- .build());
+ tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToMessageField(stringKey, bytes).build());
fail();
} catch (InvalidProtocolBufferException expected) {
assertTrue(expected.getUnfinishedMessage() instanceof TestMap);
@@ -436,9 +418,9 @@ public final class MapForProto2LiteTest extends TestCase {
assertTrue(map.getInt32ToMessageField().isEmpty());
}
- map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putStringToInt32Field(stringKey, bytes)
- .build());
+ map =
+ tryParseTestMap(
+ BizarroTestMap.newBuilder().putStringToInt32Field(stringKey, bytes).build());
assertEquals(0, map.getStringToInt32FieldOrDefault(stringKey, -1));
}
@@ -458,16 +440,18 @@ public final class MapForProto2LiteTest extends TestCase {
// We can't control the order of elements in a HashMap. The best we can do
// here is to add elements in different order.
- TestMap.Builder b1 = TestMap.newBuilder()
- .putInt32ToInt32Field(1, 2)
- .putInt32ToInt32Field(3, 4)
- .putInt32ToInt32Field(5, 6);
+ TestMap.Builder b1 =
+ TestMap.newBuilder()
+ .putInt32ToInt32Field(1, 2)
+ .putInt32ToInt32Field(3, 4)
+ .putInt32ToInt32Field(5, 6);
TestMap m1 = b1.build();
- TestMap.Builder b2 = TestMap.newBuilder()
- .putInt32ToInt32Field(5, 6)
- .putInt32ToInt32Field(1, 2)
- .putInt32ToInt32Field(3, 4);
+ TestMap.Builder b2 =
+ TestMap.newBuilder()
+ .putInt32ToInt32Field(5, 6)
+ .putInt32ToInt32Field(1, 2)
+ .putInt32ToInt32Field(3, 4);
TestMap m2 = b2.build();
assertEquals(m1, m2);
@@ -482,9 +466,8 @@ public final class MapForProto2LiteTest extends TestCase {
}
public void testUnknownEnumValues() throws Exception {
- TestUnknownEnumValue.Builder builder = TestUnknownEnumValue.newBuilder()
- .putInt32ToInt32Field(1, 1)
- .putInt32ToInt32Field(2, 54321);
+ TestUnknownEnumValue.Builder builder =
+ TestUnknownEnumValue.newBuilder().putInt32ToInt32Field(1, 1).putInt32ToInt32Field(2, 54321);
ByteString data = builder.build().toByteString();
TestMap message = TestMap.parseFrom(data);
@@ -494,8 +477,7 @@ public final class MapForProto2LiteTest extends TestCase {
assertEquals(TestMap.EnumValue.BAR, message.getInt32ToEnumField().get(1));
// Serializing and parsing should preserve the unknown entry.
data = message.toByteString();
- TestUnknownEnumValue messageWithUnknownEnums =
- TestUnknownEnumValue.parseFrom(data);
+ TestUnknownEnumValue messageWithUnknownEnums = TestUnknownEnumValue.parseFrom(data);
assertEquals(2, messageWithUnknownEnums.getInt32ToInt32Field().size());
assertEquals(1, messageWithUnknownEnums.getInt32ToInt32Field().get(1).intValue());
assertEquals(54321, messageWithUnknownEnums.getInt32ToInt32Field().get(2).intValue());
@@ -506,18 +488,19 @@ public final class MapForProto2LiteTest extends TestCase {
setMapValues(builder);
TestMap message = builder.build();
- assertEquals(Arrays.asList("1", "2", "3"),
+ assertEquals(
+ Arrays.asList("1", "2", "3"),
new ArrayList<String>(message.getStringToInt32Field().keySet()));
}
private static <K, V> Map<K, V> newMap(K key1, V value1) {
- Map<K, V> map = new HashMap<K, V>();
+ Map<K, V> map = new HashMap<>();
map.put(key1, value1);
return map;
}
private static <K, V> Map<K, V> newMap(K key1, V value1, K key2, V value2) {
- Map<K, V> map = new HashMap<K, V>();
+ Map<K, V> map = new HashMap<>();
map.put(key1, value1);
map.put(key2, value2);
return map;
@@ -527,18 +510,10 @@ public final class MapForProto2LiteTest extends TestCase {
TestMap.Builder builder = TestMap.newBuilder();
setMapValues(builder);
TestMap message = builder.build();
- assertEquals(
- message.getStringToInt32Field(),
- message.getStringToInt32FieldMap());
- assertEquals(
- message.getInt32ToBytesField(),
- message.getInt32ToBytesFieldMap());
- assertEquals(
- message.getInt32ToEnumField(),
- message.getInt32ToEnumFieldMap());
- assertEquals(
- message.getInt32ToMessageField(),
- message.getInt32ToMessageFieldMap());
+ assertEquals(message.getStringToInt32Field(), message.getStringToInt32FieldMap());
+ assertEquals(message.getInt32ToBytesField(), message.getInt32ToBytesFieldMap());
+ assertEquals(message.getInt32ToEnumField(), message.getInt32ToEnumFieldMap());
+ assertEquals(message.getInt32ToMessageField(), message.getInt32ToMessageFieldMap());
}
public void testContains() {
@@ -629,7 +604,8 @@ public final class MapForProto2LiteTest extends TestCase {
assertEquals(TestMap.EnumValue.FOO, testMapOrBuilder.getInt32ToEnumFieldOrDefault(1, null));
assertNull(testMapOrBuilder.getInt32ToEnumFieldOrDefault(-1, null));
- assertEquals(MessageValue.newBuilder().setValue(11).build(),
+ assertEquals(
+ MessageValue.newBuilder().setValue(11).build(),
testMapOrBuilder.getInt32ToMessageFieldOrDefault(1, null));
assertNull(testMapOrBuilder.getInt32ToMessageFieldOrDefault(-1, null));
@@ -687,7 +663,8 @@ public final class MapForProto2LiteTest extends TestCase {
// expected
}
- assertEquals(MessageValue.newBuilder().setValue(11).build(),
+ assertEquals(
+ MessageValue.newBuilder().setValue(11).build(),
testMapOrBuilder.getInt32ToMessageFieldOrThrow(1));
try {
testMapOrBuilder.getInt32ToMessageFieldOrThrow(-1);
diff --git a/java/core/src/test/java/com/google/protobuf/MapTest.java b/java/core/src/test/java/com/google/protobuf/MapTest.java
index 58efce92..ef8b27e8 100644
--- a/java/core/src/test/java/com/google/protobuf/MapTest.java
+++ b/java/core/src/test/java/com/google/protobuf/MapTest.java
@@ -31,6 +31,7 @@
package com.google.protobuf;
import static org.junit.Assert.assertArrayEquals;
+
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
@@ -51,9 +52,7 @@ import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
-/**
- * Unit tests for map fields.
- */
+/** Unit tests for map fields. */
public class MapTest extends TestCase {
private void setMapValuesUsingMutableMap(TestMap.Builder builder) {
@@ -90,23 +89,18 @@ public class MapTest extends TestCase {
.putInt32ToInt32Field(1, 11)
.putInt32ToInt32Field(2, 22)
.putInt32ToInt32Field(3, 33)
-
.putInt32ToStringField(1, "11")
.putInt32ToStringField(2, "22")
.putInt32ToStringField(3, "33")
-
.putInt32ToBytesField(1, TestUtil.toBytes("11"))
.putInt32ToBytesField(2, TestUtil.toBytes("22"))
.putInt32ToBytesField(3, TestUtil.toBytes("33"))
-
.putInt32ToEnumField(1, TestMap.EnumValue.FOO)
.putInt32ToEnumField(2, TestMap.EnumValue.BAR)
.putInt32ToEnumField(3, TestMap.EnumValue.BAZ)
-
.putInt32ToMessageField(1, MessageValue.newBuilder().setValue(11).build())
.putInt32ToMessageField(2, MessageValue.newBuilder().setValue(22).build())
.putInt32ToMessageField(3, MessageValue.newBuilder().setValue(33).build())
-
.putStringToInt32Field("1", 11)
.putStringToInt32Field("2", 22)
.putStringToInt32Field("3", 33);
@@ -201,23 +195,18 @@ public class MapTest extends TestCase {
.putInt32ToInt32Field(1, 111)
.removeInt32ToInt32Field(2)
.putInt32ToInt32Field(4, 44)
-
.putInt32ToStringField(1, "111")
.removeInt32ToStringField(2)
.putInt32ToStringField(4, "44")
-
.putInt32ToBytesField(1, TestUtil.toBytes("111"))
.removeInt32ToBytesField(2)
.putInt32ToBytesField(4, TestUtil.toBytes("44"))
-
.putInt32ToEnumField(1, TestMap.EnumValue.BAR)
.removeInt32ToEnumField(2)
.putInt32ToEnumField(4, TestMap.EnumValue.QUX)
-
.putInt32ToMessageField(1, MessageValue.newBuilder().setValue(111).build())
.removeInt32ToMessageField(2)
.putInt32ToMessageField(4, MessageValue.newBuilder().setValue(44).build())
-
.putStringToInt32Field("1", 111)
.removeStringToInt32Field("2")
.putStringToInt32Field("4", 44);
@@ -435,7 +424,6 @@ public class MapTest extends TestCase {
assertEquals(newMap(1, 2), builder.build().getInt32ToInt32Field());
}
-
public void testGettersAndSetters() throws Exception {
TestMap.Builder builder = TestMap.newBuilder();
TestMap message = builder.build();
@@ -470,16 +458,17 @@ public class MapTest extends TestCase {
}
public void testPutAllForUnknownEnumValues() throws Exception {
- TestMap source = TestMap.newBuilder()
- .putAllInt32ToEnumFieldValue(newMap(
- 0, 0,
- 1, 1,
- 2, 1000)) // unknown value.
- .build();
+ TestMap source =
+ TestMap.newBuilder()
+ .putAllInt32ToEnumFieldValue(
+ newMap(
+ 0, 0,
+ 1, 1,
+ 2, 1000)) // unknown value.
+ .build();
- TestMap destination = TestMap.newBuilder()
- .putAllInt32ToEnumFieldValue(source.getInt32ToEnumFieldValue())
- .build();
+ TestMap destination =
+ TestMap.newBuilder().putAllInt32ToEnumFieldValue(source.getInt32ToEnumFieldValue()).build();
assertEquals(0, destination.getInt32ToEnumFieldValue().get(0).intValue());
assertEquals(1, destination.getInt32ToEnumFieldValue().get(1).intValue());
@@ -488,10 +477,11 @@ public class MapTest extends TestCase {
}
public void testPutForUnknownEnumValues() throws Exception {
- TestMap.Builder builder = TestMap.newBuilder()
- .putInt32ToEnumFieldValue(0, 0)
- .putInt32ToEnumFieldValue(1, 1)
- .putInt32ToEnumFieldValue(2, 1000); // unknown value.
+ TestMap.Builder builder =
+ TestMap.newBuilder()
+ .putInt32ToEnumFieldValue(0, 0)
+ .putInt32ToEnumFieldValue(1, 1)
+ .putInt32ToEnumFieldValue(2, 1000); // unknown value.
TestMap message = builder.build();
assertEquals(0, message.getInt32ToEnumFieldValueOrThrow(0));
assertEquals(1, message.getInt32ToEnumFieldValueOrThrow(1));
@@ -573,30 +563,22 @@ public class MapTest extends TestCase {
ByteString bytes = TestUtil.toBytes("SOME BYTES");
String stringKey = "a string key";
- TestMap map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToInt32Field(5, bytes)
- .build());
+ TestMap map =
+ tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToInt32Field(5, bytes).build());
assertEquals(0, map.getInt32ToInt32FieldOrDefault(5, -1));
- map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToStringField(stringKey, 5)
- .build());
+ map = tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToStringField(stringKey, 5).build());
assertEquals("", map.getInt32ToStringFieldOrDefault(0, null));
- map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToBytesField(stringKey, 5)
- .build());
+ map = tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToBytesField(stringKey, 5).build());
assertEquals(map.getInt32ToBytesFieldOrDefault(0, null), ByteString.EMPTY);
- map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToEnumField(stringKey, bytes)
- .build());
+ map =
+ tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToEnumField(stringKey, bytes).build());
assertEquals(TestMap.EnumValue.FOO, map.getInt32ToEnumFieldOrDefault(0, null));
try {
- tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToMessageField(stringKey, bytes)
- .build());
+ tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToMessageField(stringKey, bytes).build());
fail();
} catch (InvalidProtocolBufferException expected) {
assertTrue(expected.getUnfinishedMessage() instanceof TestMap);
@@ -604,9 +586,9 @@ public class MapTest extends TestCase {
assertTrue(map.getInt32ToMessageField().isEmpty());
}
- map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putStringToInt32Field(stringKey, bytes)
- .build());
+ map =
+ tryParseTestMap(
+ BizarroTestMap.newBuilder().putStringToInt32Field(stringKey, bytes).build());
assertEquals(0, map.getStringToInt32FieldOrDefault(stringKey, -1));
}
@@ -626,16 +608,18 @@ public class MapTest extends TestCase {
// We can't control the order of elements in a HashMap. The best we can do
// here is to add elements in different order.
- TestMap.Builder b1 = TestMap.newBuilder()
- .putInt32ToInt32Field(1, 2)
- .putInt32ToInt32Field(3, 4)
- .putInt32ToInt32Field(5, 6);
+ TestMap.Builder b1 =
+ TestMap.newBuilder()
+ .putInt32ToInt32Field(1, 2)
+ .putInt32ToInt32Field(3, 4)
+ .putInt32ToInt32Field(5, 6);
TestMap m1 = b1.build();
- TestMap.Builder b2 = TestMap.newBuilder()
- .putInt32ToInt32Field(5, 6)
- .putInt32ToInt32Field(1, 2)
- .putInt32ToInt32Field(3, 4);
+ TestMap.Builder b2 =
+ TestMap.newBuilder()
+ .putInt32ToInt32Field(5, 6)
+ .putInt32ToInt32Field(1, 2)
+ .putInt32ToInt32Field(3, 4);
TestMap m2 = b2.build();
assertEquals(m1, m2);
@@ -657,8 +641,7 @@ public class MapTest extends TestCase {
}
public void testNestedBuilderOnChangeEventPropagation() {
- TestOnChangeEventPropagation.Builder parent =
- TestOnChangeEventPropagation.newBuilder();
+ TestOnChangeEventPropagation.Builder parent = TestOnChangeEventPropagation.newBuilder();
parent.getOptionalMessageBuilder().putInt32ToInt32Field(1, 2);
TestOnChangeEventPropagation message = parent.build();
assertEquals(2, message.getOptionalMessage().getInt32ToInt32Field().get(1).intValue());
@@ -689,16 +672,14 @@ public class MapTest extends TestCase {
public void testNestedBuilderOnChangeEventPropagationReflection() {
FieldDescriptor intMapField = f("int32_to_int32_field");
// Create an outer message builder with nested builder.
- TestOnChangeEventPropagation.Builder parentBuilder =
- TestOnChangeEventPropagation.newBuilder();
+ TestOnChangeEventPropagation.Builder parentBuilder = TestOnChangeEventPropagation.newBuilder();
TestMap.Builder testMapBuilder = parentBuilder.getOptionalMessageBuilder();
// Create a map entry message.
TestMap.Builder entryBuilder = TestMap.newBuilder().putInt32ToInt32Field(1, 1);
// Put the entry into the nested builder.
- testMapBuilder.addRepeatedField(
- intMapField, entryBuilder.getRepeatedField(intMapField, 0));
+ testMapBuilder.addRepeatedField(intMapField, entryBuilder.getRepeatedField(intMapField, 0));
// Should be able to observe the change.
TestOnChangeEventPropagation message = parentBuilder.build();
@@ -707,13 +688,11 @@ public class MapTest extends TestCase {
// Change the entry value.
entryBuilder.putInt32ToInt32Field(1, 4);
testMapBuilder = parentBuilder.getOptionalMessageBuilder();
- testMapBuilder.setRepeatedField(
- intMapField, 0, entryBuilder.getRepeatedField(intMapField, 0));
+ testMapBuilder.setRepeatedField(intMapField, 0, entryBuilder.getRepeatedField(intMapField, 0));
// Should be able to observe the change.
message = parentBuilder.build();
- assertEquals(4,
- message.getOptionalMessage().getInt32ToInt32Field().get(1).intValue());
+ assertEquals(4, message.getOptionalMessage().getInt32ToInt32Field().get(1).intValue());
// Clear the nested builder.
testMapBuilder = parentBuilder.getOptionalMessageBuilder();
@@ -761,8 +740,7 @@ public class MapTest extends TestCase {
}
}
- private static <KeyType, ValueType>
- Message newMapEntry(Message.Builder builder, String name, KeyType key, ValueType value) {
+ private static <K, V> Message newMapEntry(Message.Builder builder, String name, K key, V value) {
FieldDescriptor field = builder.getDescriptorForType().findFieldByName(name);
Message.Builder entryBuilder = builder.newBuilderForField(field);
FieldDescriptor keyField = entryBuilder.getDescriptorForType().findFieldByName("key");
@@ -781,10 +759,8 @@ public class MapTest extends TestCase {
builder.setField(field, entryList);
}
- private static <KeyType, ValueType>
- Map<KeyType, ValueType> mapForValues(
- KeyType key1, ValueType value1, KeyType key2, ValueType value2) {
- Map<KeyType, ValueType> map = new HashMap<KeyType, ValueType>();
+ private static <K, V> Map<K, V> mapForValues(K key1, V value1, K key2, V value2) {
+ Map<K, V> map = new HashMap<K, V>();
map.put(key1, value1);
map.put(key2, value2);
return map;
@@ -792,17 +768,19 @@ public class MapTest extends TestCase {
public void testReflectionApi() throws Exception {
// In reflection API, map fields are just repeated message fields.
- TestMap.Builder builder = TestMap.newBuilder()
- .putInt32ToInt32Field(1, 2)
- .putInt32ToInt32Field(3, 4)
- .putInt32ToMessageField(11, MessageValue.newBuilder().setValue(22).build())
- .putInt32ToMessageField(33, MessageValue.newBuilder().setValue(44).build());
+ TestMap.Builder builder =
+ TestMap.newBuilder()
+ .putInt32ToInt32Field(1, 2)
+ .putInt32ToInt32Field(3, 4)
+ .putInt32ToMessageField(11, MessageValue.newBuilder().setValue(22).build())
+ .putInt32ToMessageField(33, MessageValue.newBuilder().setValue(44).build());
TestMap message = builder.build();
// Test getField(), getRepeatedFieldCount(), getRepeatedField().
- assertHasMapValues(message, "int32_to_int32_field",
- mapForValues(1, 2, 3, 4));
- assertHasMapValues(message, "int32_to_message_field",
+ assertHasMapValues(message, "int32_to_int32_field", mapForValues(1, 2, 3, 4));
+ assertHasMapValues(
+ message,
+ "int32_to_message_field",
mapForValues(
11, MessageValue.newBuilder().setValue(22).build(),
33, MessageValue.newBuilder().setValue(44).build()));
@@ -815,9 +793,10 @@ public class MapTest extends TestCase {
assertEquals(0, message.getInt32ToMessageField().size());
// Test setField()
- setMapValues(builder, "int32_to_int32_field",
- mapForValues(11, 22, 33, 44));
- setMapValues(builder, "int32_to_message_field",
+ setMapValues(builder, "int32_to_int32_field", mapForValues(11, 22, 33, 44));
+ setMapValues(
+ builder,
+ "int32_to_message_field",
mapForValues(
111, MessageValue.newBuilder().setValue(222).build(),
333, MessageValue.newBuilder().setValue(444).build()));
@@ -828,20 +807,28 @@ public class MapTest extends TestCase {
assertEquals(444, message.getInt32ToMessageField().get(333).getValue());
// Test addRepeatedField
- builder.addRepeatedField(f("int32_to_int32_field"),
- newMapEntry(builder, "int32_to_int32_field", 55, 66));
- builder.addRepeatedField(f("int32_to_message_field"),
- newMapEntry(builder, "int32_to_message_field", 555,
+ builder.addRepeatedField(
+ f("int32_to_int32_field"), newMapEntry(builder, "int32_to_int32_field", 55, 66));
+ builder.addRepeatedField(
+ f("int32_to_message_field"),
+ newMapEntry(
+ builder,
+ "int32_to_message_field",
+ 555,
MessageValue.newBuilder().setValue(666).build()));
message = builder.build();
assertEquals(66, message.getInt32ToInt32Field().get(55).intValue());
assertEquals(666, message.getInt32ToMessageField().get(555).getValue());
// Test addRepeatedField (overriding existing values)
- builder.addRepeatedField(f("int32_to_int32_field"),
- newMapEntry(builder, "int32_to_int32_field", 55, 55));
- builder.addRepeatedField(f("int32_to_message_field"),
- newMapEntry(builder, "int32_to_message_field", 555,
+ builder.addRepeatedField(
+ f("int32_to_int32_field"), newMapEntry(builder, "int32_to_int32_field", 55, 55));
+ builder.addRepeatedField(
+ f("int32_to_message_field"),
+ newMapEntry(
+ builder,
+ "int32_to_message_field",
+ 555,
MessageValue.newBuilder().setValue(555).build()));
message = builder.build();
assertEquals(55, message.getInt32ToInt32Field().get(55).intValue());
@@ -884,10 +871,9 @@ public class MapTest extends TestCase {
setMapValuesUsingAccessors(builder);
TestMap message = builder.build();
- Message dynamicDefaultInstance =
- DynamicMessage.getDefaultInstance(TestMap.getDescriptor());
- Message dynamicMessage = dynamicDefaultInstance
- .newBuilderForType().mergeFrom(message.toByteString()).build();
+ Message dynamicDefaultInstance = DynamicMessage.getDefaultInstance(TestMap.getDescriptor());
+ Message dynamicMessage =
+ dynamicDefaultInstance.newBuilderForType().mergeFrom(message.toByteString()).build();
assertEquals(message, dynamicMessage);
assertEquals(message.hashCode(), dynamicMessage.hashCode());
@@ -898,8 +884,7 @@ public class MapTest extends TestCase {
public void testDynamicMessageUnsetKeyAndValue() throws Exception {
FieldDescriptor field = f("int32_to_int32_field");
- Message dynamicDefaultInstance =
- DynamicMessage.getDefaultInstance(TestMap.getDescriptor());
+ Message dynamicDefaultInstance = DynamicMessage.getDefaultInstance(TestMap.getDescriptor());
Message.Builder builder = dynamicDefaultInstance.newBuilderForType();
// Add an entry without key and value.
builder.addRepeatedField(field, builder.newBuilderForField(field).build());
@@ -916,8 +901,7 @@ public class MapTest extends TestCase {
// of map entries when comparing/hashing map fields.
// We use DynamicMessage to test reflection based equals()/hashCode().
- Message dynamicDefaultInstance =
- DynamicMessage.getDefaultInstance(TestMap.getDescriptor());
+ Message dynamicDefaultInstance = DynamicMessage.getDefaultInstance(TestMap.getDescriptor());
FieldDescriptor field = f("int32_to_int32_field");
Message.Builder b1 = dynamicDefaultInstance.newBuilderForType();
@@ -944,19 +928,18 @@ public class MapTest extends TestCase {
}
public void testUnknownEnumValues() throws Exception {
- TestMap.Builder builder = TestMap.newBuilder()
- .putAllInt32ToEnumFieldValue(newMap(
- 0, 0,
- 1, 1,
- 2, 1000)); // unknown value.
+ TestMap.Builder builder =
+ TestMap.newBuilder()
+ .putAllInt32ToEnumFieldValue(
+ newMap(
+ 0, 0,
+ 1, 1,
+ 2, 1000)); // unknown value.
TestMap message = builder.build();
- assertEquals(TestMap.EnumValue.FOO,
- message.getInt32ToEnumField().get(0));
- assertEquals(TestMap.EnumValue.BAR,
- message.getInt32ToEnumField().get(1));
- assertEquals(TestMap.EnumValue.UNRECOGNIZED,
- message.getInt32ToEnumField().get(2));
+ assertEquals(TestMap.EnumValue.FOO, message.getInt32ToEnumField().get(0));
+ assertEquals(TestMap.EnumValue.BAR, message.getInt32ToEnumField().get(1));
+ assertEquals(TestMap.EnumValue.UNRECOGNIZED, message.getInt32ToEnumField().get(2));
assertEquals(1000, message.getInt32ToEnumFieldValue().get(2).intValue());
// Unknown enum values should be preserved after:
@@ -977,7 +960,7 @@ public class MapTest extends TestCase {
assertFalse(message.equals(message2));
// Unknown values will be converted to UNRECOGNIZED so the resulted enum map
// should be the same.
- assertTrue(message.getInt32ToEnumField().equals(message2.getInt32ToEnumField()));
+ assertEquals(message2.getInt32ToEnumField(), message.getInt32ToEnumField());
}
public void testUnknownEnumValuesInReflectionApi() throws Exception {
@@ -985,13 +968,13 @@ public class MapTest extends TestCase {
EnumDescriptor enumDescriptor = TestMap.EnumValue.getDescriptor();
FieldDescriptor field = descriptor.findFieldByName("int32_to_enum_field");
- Map<Integer, Integer> data = newMap(
- 0, 0,
- 1, 1,
- 2, 1000); // unknown value
+ Map<Integer, Integer> data =
+ newMap(
+ 0, 0,
+ 1, 1,
+ 2, 1000); // unknown value
- TestMap.Builder builder = TestMap.newBuilder()
- .putAllInt32ToEnumFieldValue(data);
+ TestMap.Builder builder = TestMap.newBuilder().putAllInt32ToEnumFieldValue(data);
// Try to read unknown enum values using reflection API.
for (int i = 0; i < builder.getRepeatedFieldCount(field); i++) {
@@ -1001,8 +984,8 @@ public class MapTest extends TestCase {
assertEquals(data.get(key).intValue(), value);
Message.Builder mapEntryBuilder = mapEntry.toBuilder();
// Increase the value by 1.
- setFieldValue(mapEntryBuilder, "value",
- enumDescriptor.findValueByNumberCreatingIfUnknown(value + 1));
+ setFieldValue(
+ mapEntryBuilder, "value", enumDescriptor.findValueByNumberCreatingIfUnknown(value + 1));
builder.setRepeatedField(field, i, mapEntryBuilder.build());
}
@@ -1018,7 +1001,8 @@ public class MapTest extends TestCase {
setMapValuesUsingAccessors(builder);
TestMap message = builder.build();
- assertEquals(Arrays.asList("1", "2", "3"),
+ assertEquals(
+ Arrays.asList("1", "2", "3"),
new ArrayList<String>(message.getStringToInt32Field().keySet()));
}
@@ -1026,21 +1010,11 @@ public class MapTest extends TestCase {
TestMap.Builder builder = TestMap.newBuilder();
setMapValuesUsingAccessors(builder);
TestMap message = builder.build();
- assertEquals(
- message.getStringToInt32Field(),
- message.getStringToInt32FieldMap());
- assertEquals(
- message.getInt32ToBytesField(),
- message.getInt32ToBytesFieldMap());
- assertEquals(
- message.getInt32ToEnumField(),
- message.getInt32ToEnumFieldMap());
- assertEquals(
- message.getInt32ToEnumFieldValue(),
- message.getInt32ToEnumFieldValueMap());
- assertEquals(
- message.getInt32ToMessageField(),
- message.getInt32ToMessageFieldMap());
+ assertEquals(message.getStringToInt32Field(), message.getStringToInt32FieldMap());
+ assertEquals(message.getInt32ToBytesField(), message.getInt32ToBytesFieldMap());
+ assertEquals(message.getInt32ToEnumField(), message.getInt32ToEnumFieldMap());
+ assertEquals(message.getInt32ToEnumFieldValue(), message.getInt32ToEnumFieldValueMap());
+ assertEquals(message.getInt32ToMessageField(), message.getInt32ToMessageFieldMap());
}
public void testContains() {
@@ -1133,10 +1107,11 @@ public class MapTest extends TestCase {
assertEquals(
TestMap.EnumValue.BAR.getNumber(),
- (int) testMapOrBuilder.getInt32ToEnumFieldValueOrDefault(2, -1));
+ testMapOrBuilder.getInt32ToEnumFieldValueOrDefault(2, -1));
assertEquals(-1, testMapOrBuilder.getInt32ToEnumFieldValueOrDefault(-1000, -1));
- assertEquals(MessageValue.newBuilder().setValue(11).build(),
+ assertEquals(
+ MessageValue.newBuilder().setValue(11).build(),
testMapOrBuilder.getInt32ToMessageFieldOrDefault(1, null));
assertNull(testMapOrBuilder.getInt32ToMessageFieldOrDefault(-1, null));
@@ -1203,7 +1178,8 @@ public class MapTest extends TestCase {
// expected
}
- assertEquals(MessageValue.newBuilder().setValue(11).build(),
+ assertEquals(
+ MessageValue.newBuilder().setValue(11).build(),
testMapOrBuilder.getInt32ToMessageFieldOrThrow(1));
try {
testMapOrBuilder.getInt32ToMessageFieldOrThrow(-1);
@@ -1261,8 +1237,7 @@ public class MapTest extends TestCase {
}
builder.putInt32ToEnumFieldValue(1, TestMap.EnumValue.BAR.getNumber());
- assertEquals(
- TestMap.EnumValue.BAR.getNumber(), builder.getInt32ToEnumFieldValueOrThrow(1));
+ assertEquals(TestMap.EnumValue.BAR.getNumber(), builder.getInt32ToEnumFieldValueOrThrow(1));
builder.putInt32ToEnumFieldValue(1, -1);
assertEquals(-1, builder.getInt32ToEnumFieldValueOrThrow(1));
assertEquals(TestMap.EnumValue.UNRECOGNIZED, builder.getInt32ToEnumFieldOrThrow(1));
@@ -1391,18 +1366,10 @@ public class MapTest extends TestCase {
}
input.popLimit(oldLimit);
}
- assertEquals(
- Arrays.asList(-2, 0, 1, 4, 5),
- int32Keys);
- assertEquals(
- Arrays.asList(-2, 0, 1, 4, 5),
- uint32Keys);
- assertEquals(
- Arrays.asList(-2L, 0L, 1L, 4L, 5L),
- int64Keys);
- assertEquals(
- Arrays.asList("", "bar", "baz", "foo", "hello", "world"),
- stringKeys);
+ assertEquals(Arrays.asList(-2, 0, 1, 4, 5), int32Keys);
+ assertEquals(Arrays.asList(-2, 0, 1, 4, 5), uint32Keys);
+ assertEquals(Arrays.asList(-2L, 0L, 1L, 4L, 5L), int64Keys);
+ assertEquals(Arrays.asList("", "bar", "baz", "foo", "hello", "world"), stringKeys);
}
public void testInitFromPartialDynamicMessage() {
@@ -1525,8 +1492,7 @@ public class MapTest extends TestCase {
}
try {
- builder.putAllInt32ToMessageField(
- MapTest.<Integer, MessageValue>newMap(4, null, 5, null));
+ builder.putAllInt32ToMessageField(MapTest.<Integer, MessageValue>newMap(4, null, 5, null));
fail();
} catch (NullPointerException expected) {
}
diff --git a/java/core/src/test/java/com/google/protobuf/MessageTest.java b/java/core/src/test/java/com/google/protobuf/MessageTest.java
index 4fc8f78e..760511b6 100644
--- a/java/core/src/test/java/com/google/protobuf/MessageTest.java
+++ b/java/core/src/test/java/com/google/protobuf/MessageTest.java
@@ -39,8 +39,7 @@ import java.util.List;
import junit.framework.TestCase;
/**
- * Misc. unit tests for message operations that apply to both generated
- * and dynamic messages.
+ * Misc. unit tests for message operations that apply to both generated and dynamic messages.
*
* @author kenton@google.com Kenton Varda
*/
@@ -49,30 +48,31 @@ public class MessageTest extends TestCase {
// Message-merging tests.
static final TestAllTypes MERGE_SOURCE =
- TestAllTypes.newBuilder()
- .setOptionalInt32(1)
- .setOptionalString("foo")
- .setOptionalForeignMessage(ForeignMessage.getDefaultInstance())
- .addRepeatedString("bar")
- .build();
+ TestAllTypes.newBuilder()
+ .setOptionalInt32(1)
+ .setOptionalString("foo")
+ .setOptionalForeignMessage(ForeignMessage.getDefaultInstance())
+ .addRepeatedString("bar")
+ .build();
static final TestAllTypes MERGE_DEST =
- TestAllTypes.newBuilder()
- .setOptionalInt64(2)
- .setOptionalString("baz")
- .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(3).build())
- .addRepeatedString("qux")
- .build();
+ TestAllTypes.newBuilder()
+ .setOptionalInt64(2)
+ .setOptionalString("baz")
+ .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(3).build())
+ .addRepeatedString("qux")
+ .build();
static final String MERGE_RESULT_TEXT =
- "optional_int32: 1\n" +
- "optional_int64: 2\n" +
- "optional_string: \"foo\"\n" +
- "optional_foreign_message {\n" +
- " c: 3\n" +
- "}\n" +
- "repeated_string: \"qux\"\n" +
- "repeated_string: \"bar\"\n";
+ ""
+ + "optional_int32: 1\n"
+ + "optional_int64: 2\n"
+ + "optional_string: \"foo\"\n"
+ + "optional_foreign_message {\n"
+ + " c: 3\n"
+ + "}\n"
+ + "repeated_string: \"qux\"\n"
+ + "repeated_string: \"bar\"\n";
public void testParsingWithNullExtensionRegistry() throws Exception {
try {
@@ -83,23 +83,20 @@ public class MessageTest extends TestCase {
}
public void testMergeFrom() throws Exception {
- TestAllTypes result =
- TestAllTypes.newBuilder(MERGE_DEST)
- .mergeFrom(MERGE_SOURCE).build();
+ TestAllTypes result = TestAllTypes.newBuilder(MERGE_DEST).mergeFrom(MERGE_SOURCE).build();
assertEquals(MERGE_RESULT_TEXT, result.toString());
}
/**
- * Test merging a DynamicMessage into a GeneratedMessage. As long as they
- * have the same descriptor, this should work, but it is an entirely different
- * code path.
+ * Test merging a DynamicMessage into a GeneratedMessage. As long as they have the same
+ * descriptor, this should work, but it is an entirely different code path.
*/
public void testMergeFromDynamic() throws Exception {
TestAllTypes result =
- TestAllTypes.newBuilder(MERGE_DEST)
- .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build())
- .build();
+ TestAllTypes.newBuilder(MERGE_DEST)
+ .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build())
+ .build();
assertEquals(MERGE_RESULT_TEXT, result.toString());
}
@@ -107,9 +104,9 @@ public class MessageTest extends TestCase {
/** Test merging two DynamicMessages. */
public void testDynamicMergeFrom() throws Exception {
DynamicMessage result =
- DynamicMessage.newBuilder(MERGE_DEST)
- .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build())
- .build();
+ DynamicMessage.newBuilder(MERGE_DEST)
+ .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build())
+ .build();
assertEquals(MERGE_RESULT_TEXT, result.toString());
}
@@ -117,10 +114,9 @@ public class MessageTest extends TestCase {
// =================================================================
// Required-field-related tests.
- private static final TestRequired TEST_REQUIRED_UNINITIALIZED =
- TestRequired.getDefaultInstance();
+ private static final TestRequired TEST_REQUIRED_UNINITIALIZED = TestRequired.getDefaultInstance();
private static final TestRequired TEST_REQUIRED_INITIALIZED =
- TestRequired.newBuilder().setA(1).setB(2).setC(3).build();
+ TestRequired.newBuilder().setA(1).setB(2).setC(3).build();
public void testRequired() throws Exception {
TestRequired.Builder builder = TestRequired.newBuilder();
@@ -189,20 +185,18 @@ public class MessageTest extends TestCase {
assertTrue(builder.isInitialized());
- builder.setField(descriptor.findFieldByName("optional_message"),
- TEST_REQUIRED_UNINITIALIZED);
+ builder.setField(descriptor.findFieldByName("optional_message"), TEST_REQUIRED_UNINITIALIZED);
assertFalse(builder.isInitialized());
- builder.setField(descriptor.findFieldByName("optional_message"),
- TEST_REQUIRED_INITIALIZED);
+ builder.setField(descriptor.findFieldByName("optional_message"), TEST_REQUIRED_INITIALIZED);
assertTrue(builder.isInitialized());
- builder.addRepeatedField(descriptor.findFieldByName("repeated_message"),
- TEST_REQUIRED_UNINITIALIZED);
+ builder.addRepeatedField(
+ descriptor.findFieldByName("repeated_message"), TEST_REQUIRED_UNINITIALIZED);
assertFalse(builder.isInitialized());
- builder.setRepeatedField(descriptor.findFieldByName("repeated_message"), 0,
- TEST_REQUIRED_INITIALIZED);
+ builder.setRepeatedField(
+ descriptor.findFieldByName("repeated_message"), 0, TEST_REQUIRED_INITIALIZED);
assertTrue(builder.isInitialized());
}
@@ -224,35 +218,35 @@ public class MessageTest extends TestCase {
public void testNestedUninitializedException() throws Exception {
try {
TestRequiredForeign.newBuilder()
- .setOptionalMessage(TEST_REQUIRED_UNINITIALIZED)
- .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
- .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
- .build();
+ .setOptionalMessage(TEST_REQUIRED_UNINITIALIZED)
+ .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
+ .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
+ .build();
fail("Should have thrown an exception.");
} catch (UninitializedMessageException e) {
assertEquals(
- "Message missing required fields: " +
- "optional_message.a, " +
- "optional_message.b, " +
- "optional_message.c, " +
- "repeated_message[0].a, " +
- "repeated_message[0].b, " +
- "repeated_message[0].c, " +
- "repeated_message[1].a, " +
- "repeated_message[1].b, " +
- "repeated_message[1].c",
- e.getMessage());
+ "Message missing required fields: "
+ + "optional_message.a, "
+ + "optional_message.b, "
+ + "optional_message.c, "
+ + "repeated_message[0].a, "
+ + "repeated_message[0].b, "
+ + "repeated_message[0].c, "
+ + "repeated_message[1].a, "
+ + "repeated_message[1].b, "
+ + "repeated_message[1].c",
+ e.getMessage());
}
}
public void testBuildNestedPartial() throws Exception {
// We're mostly testing that no exception is thrown.
TestRequiredForeign message =
- TestRequiredForeign.newBuilder()
- .setOptionalMessage(TEST_REQUIRED_UNINITIALIZED)
- .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
- .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
- .buildPartial();
+ TestRequiredForeign.newBuilder()
+ .setOptionalMessage(TEST_REQUIRED_UNINITIALIZED)
+ .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
+ .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
+ .buildPartial();
assertFalse(message.isInitialized());
}
@@ -267,28 +261,29 @@ public class MessageTest extends TestCase {
public void testParseNestedUnititialized() throws Exception {
ByteString data =
- TestRequiredForeign.newBuilder()
- .setOptionalMessage(TEST_REQUIRED_UNINITIALIZED)
- .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
- .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
- .buildPartial().toByteString();
+ TestRequiredForeign.newBuilder()
+ .setOptionalMessage(TEST_REQUIRED_UNINITIALIZED)
+ .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
+ .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
+ .buildPartial()
+ .toByteString();
try {
TestRequiredForeign.parseFrom(data);
fail("Should have thrown an exception.");
} catch (InvalidProtocolBufferException e) {
assertEquals(
- "Message missing required fields: " +
- "optional_message.a, " +
- "optional_message.b, " +
- "optional_message.c, " +
- "repeated_message[0].a, " +
- "repeated_message[0].b, " +
- "repeated_message[0].c, " +
- "repeated_message[1].a, " +
- "repeated_message[1].b, " +
- "repeated_message[1].c",
- e.getMessage());
+ "Message missing required fields: "
+ + "optional_message.a, "
+ + "optional_message.b, "
+ + "optional_message.c, "
+ + "repeated_message[0].a, "
+ + "repeated_message[0].b, "
+ + "repeated_message[0].c, "
+ + "repeated_message[1].a, "
+ + "repeated_message[1].b, "
+ + "repeated_message[1].c",
+ e.getMessage());
}
}
@@ -303,9 +298,7 @@ public class MessageTest extends TestCase {
public void testDynamicBuildPartial() throws Exception {
// We're mostly testing that no exception is thrown.
- DynamicMessage message =
- DynamicMessage.newBuilder(TestRequired.getDescriptor())
- .buildPartial();
+ DynamicMessage message = DynamicMessage.newBuilder(TestRequired.getDescriptor()).buildPartial();
assertFalse(message.isInitialized());
}
@@ -318,43 +311,44 @@ public class MessageTest extends TestCase {
assertEquals("Message missing required fields: a, b, c", e.getMessage());
}
}
-
+
/** Test reading unset repeated message from DynamicMessage. */
public void testDynamicRepeatedMessageNull() throws Exception {
- Descriptors.Descriptor descriptor = TestRequired.getDescriptor();
+ TestRequired.getDescriptor();
DynamicMessage result =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor())
- .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build())
- .build();
+ DynamicMessage.newBuilder(TestAllTypes.getDescriptor())
+ .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build())
+ .build();
- assertTrue(result.getField(result.getDescriptorForType()
- .findFieldByName("repeated_foreign_message")) instanceof List<?>);
+ assertTrue(
+ result.getField(result.getDescriptorForType().findFieldByName("repeated_foreign_message"))
+ instanceof List<?>);
assertEquals(
0,
result.getRepeatedFieldCount(
result.getDescriptorForType().findFieldByName("repeated_foreign_message")));
}
-
+
/** Test reading repeated message from DynamicMessage. */
public void testDynamicRepeatedMessageNotNull() throws Exception {
-
- TestAllTypes REPEATED_NESTED =
- TestAllTypes.newBuilder()
- .setOptionalInt32(1)
- .setOptionalString("foo")
- .setOptionalForeignMessage(ForeignMessage.getDefaultInstance())
- .addRepeatedString("bar")
- .addRepeatedForeignMessage(ForeignMessage.getDefaultInstance())
- .addRepeatedForeignMessage(ForeignMessage.getDefaultInstance())
- .build();
- Descriptors.Descriptor descriptor = TestRequired.getDescriptor();
+ TestAllTypes repeatedNested =
+ TestAllTypes.newBuilder()
+ .setOptionalInt32(1)
+ .setOptionalString("foo")
+ .setOptionalForeignMessage(ForeignMessage.getDefaultInstance())
+ .addRepeatedString("bar")
+ .addRepeatedForeignMessage(ForeignMessage.getDefaultInstance())
+ .addRepeatedForeignMessage(ForeignMessage.getDefaultInstance())
+ .build();
+ TestRequired.getDescriptor();
DynamicMessage result =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor())
- .mergeFrom(DynamicMessage.newBuilder(REPEATED_NESTED).build())
- .build();
+ DynamicMessage.newBuilder(TestAllTypes.getDescriptor())
+ .mergeFrom(DynamicMessage.newBuilder(repeatedNested).build())
+ .build();
- assertTrue(result.getField(result.getDescriptorForType()
- .findFieldByName("repeated_foreign_message")) instanceof List<?>);
+ assertTrue(
+ result.getField(result.getDescriptorForType().findFieldByName("repeated_foreign_message"))
+ instanceof List<?>);
assertEquals(
2,
result.getRepeatedFieldCount(
diff --git a/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java b/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java
index 03ed65a5..7bfeaf17 100644
--- a/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java
+++ b/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java
@@ -37,8 +37,8 @@ import java.util.List;
import junit.framework.TestCase;
/**
- * Test cases that exercise end-to-end use cases involving
- * {@link SingleFieldBuilder} and {@link RepeatedFieldBuilder}.
+ * Test cases that exercise end-to-end use cases involving {@link SingleFieldBuilder} and {@link
+ * RepeatedFieldBuilder}.
*
* @author jonp@google.com (Jon Perlow)
*/
@@ -46,20 +46,11 @@ public class NestedBuildersTest extends TestCase {
public void testMessagesAndBuilders() {
Vehicle.Builder vehicleBuilder = Vehicle.newBuilder();
- vehicleBuilder.addWheelBuilder()
- .setRadius(4)
- .setWidth(1);
- vehicleBuilder.addWheelBuilder()
- .setRadius(4)
- .setWidth(2);
- vehicleBuilder.addWheelBuilder()
- .setRadius(4)
- .setWidth(3);
- vehicleBuilder.addWheelBuilder()
- .setRadius(4)
- .setWidth(4);
- vehicleBuilder.getEngineBuilder()
- .setLiters(10);
+ vehicleBuilder.addWheelBuilder().setRadius(4).setWidth(1);
+ vehicleBuilder.addWheelBuilder().setRadius(4).setWidth(2);
+ vehicleBuilder.addWheelBuilder().setRadius(4).setWidth(3);
+ vehicleBuilder.addWheelBuilder().setRadius(4).setWidth(4);
+ vehicleBuilder.getEngineBuilder().setLiters(10);
Vehicle vehicle = vehicleBuilder.build();
assertEquals(4, vehicle.getWheelCount());
@@ -71,9 +62,7 @@ public class NestedBuildersTest extends TestCase {
assertEquals(10, vehicle.getEngine().getLiters());
for (int i = 0; i < 4; i++) {
- vehicleBuilder.getWheelBuilder(i)
- .setRadius(5)
- .setWidth(i + 10);
+ vehicleBuilder.getWheelBuilder(i).setRadius(5).setWidth(i + 10);
}
vehicleBuilder.getEngineBuilder().setLiters(20);
@@ -89,18 +78,10 @@ public class NestedBuildersTest extends TestCase {
public void testMessagesAreCached() {
Vehicle.Builder vehicleBuilder = Vehicle.newBuilder();
- vehicleBuilder.addWheelBuilder()
- .setRadius(1)
- .setWidth(2);
- vehicleBuilder.addWheelBuilder()
- .setRadius(3)
- .setWidth(4);
- vehicleBuilder.addWheelBuilder()
- .setRadius(5)
- .setWidth(6);
- vehicleBuilder.addWheelBuilder()
- .setRadius(7)
- .setWidth(8);
+ vehicleBuilder.addWheelBuilder().setRadius(1).setWidth(2);
+ vehicleBuilder.addWheelBuilder().setRadius(3).setWidth(4);
+ vehicleBuilder.addWheelBuilder().setRadius(5).setWidth(6);
+ vehicleBuilder.addWheelBuilder().setRadius(7).setWidth(8);
// Make sure messages are cached.
List<Wheel> wheels = new ArrayList<Wheel>(vehicleBuilder.getWheelList());
@@ -117,8 +98,7 @@ public class NestedBuildersTest extends TestCase {
}
// Change just one
- vehicleBuilder.getWheelBuilder(3)
- .setRadius(20).setWidth(20);
+ vehicleBuilder.getWheelBuilder(3).setRadius(20).setWidth(20);
// Now get wheels and check that only that one changed
for (int i = 0; i < wheels.size(); i++) {
@@ -132,12 +112,8 @@ public class NestedBuildersTest extends TestCase {
public void testRemove_WithNestedBuilders() {
Vehicle.Builder vehicleBuilder = Vehicle.newBuilder();
- vehicleBuilder.addWheelBuilder()
- .setRadius(1)
- .setWidth(1);
- vehicleBuilder.addWheelBuilder()
- .setRadius(2)
- .setWidth(2);
+ vehicleBuilder.addWheelBuilder().setRadius(1).setWidth(1);
+ vehicleBuilder.addWheelBuilder().setRadius(2).setWidth(2);
vehicleBuilder.removeWheel(0);
assertEquals(1, vehicleBuilder.getWheelCount());
@@ -146,12 +122,8 @@ public class NestedBuildersTest extends TestCase {
public void testRemove_WithNestedMessages() {
Vehicle.Builder vehicleBuilder = Vehicle.newBuilder();
- vehicleBuilder.addWheel(Wheel.newBuilder()
- .setRadius(1)
- .setWidth(1));
- vehicleBuilder.addWheel(Wheel.newBuilder()
- .setRadius(2)
- .setWidth(2));
+ vehicleBuilder.addWheel(Wheel.newBuilder().setRadius(1).setWidth(1));
+ vehicleBuilder.addWheel(Wheel.newBuilder().setRadius(2).setWidth(2));
vehicleBuilder.removeWheel(0);
assertEquals(1, vehicleBuilder.getWheelCount());
@@ -159,14 +131,13 @@ public class NestedBuildersTest extends TestCase {
}
public void testMerge() {
- Vehicle vehicle1 = Vehicle.newBuilder()
- .addWheel(Wheel.newBuilder().setRadius(1).build())
- .addWheel(Wheel.newBuilder().setRadius(2).build())
- .build();
-
- Vehicle vehicle2 = Vehicle.newBuilder()
- .mergeFrom(vehicle1)
- .build();
+ Vehicle vehicle1 =
+ Vehicle.newBuilder()
+ .addWheel(Wheel.newBuilder().setRadius(1).build())
+ .addWheel(Wheel.newBuilder().setRadius(2).build())
+ .build();
+
+ Vehicle vehicle2 = Vehicle.newBuilder().mergeFrom(vehicle1).build();
// List should be the same -- no allocation
assertSame(vehicle1.getWheelList(), vehicle2.getWheelList());
diff --git a/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java b/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java
index c388bd05..4a68c8b8 100644
--- a/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java
+++ b/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java
@@ -48,9 +48,7 @@ import java.util.List;
import java.util.NoSuchElementException;
import junit.framework.TestCase;
-/**
- * Tests for {@link NioByteString}.
- */
+/** Tests for {@link NioByteString}. */
public class NioByteStringTest extends TestCase {
private static final ByteString EMPTY = new NioByteString(ByteBuffer.wrap(new byte[0]));
private static final String CLASSNAME = NioByteString.class.getSimpleName();
@@ -108,8 +106,7 @@ public class NioByteStringTest extends TestCase {
}
public void testSize() {
- assertEquals(CLASSNAME + " must have the expected size", BYTES.length,
- testString.size());
+ assertEquals(CLASSNAME + " must have the expected size", BYTES.length, testString.size());
}
public void testGetTreeDepth() {
@@ -140,10 +137,8 @@ public class NioByteStringTest extends TestCase {
try {
// Copy one too many bytes
- testString.copyTo(destination, testString.size() + 1 - length,
- destinationOffset, length);
- fail("Should have thrown an exception when copying too many bytes of a "
- + CLASSNAME);
+ testString.copyTo(destination, testString.size() + 1 - length, destinationOffset, length);
+ fail("Should have thrown an exception when copying too many bytes of a " + CLASSNAME);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -151,8 +146,7 @@ public class NioByteStringTest extends TestCase {
try {
// Copy with illegal negative sourceOffset
testString.copyTo(destination, -1, destinationOffset, length);
- fail("Should have thrown an exception when given a negative sourceOffset in "
- + CLASSNAME);
+ fail("Should have thrown an exception when given a negative sourceOffset in " + CLASSNAME);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -160,8 +154,9 @@ public class NioByteStringTest extends TestCase {
try {
// Copy with illegal negative destinationOffset
testString.copyTo(destination, 0, -1, length);
- fail("Should have thrown an exception when given a negative destinationOffset in "
- + CLASSNAME);
+ fail(
+ "Should have thrown an exception when given a negative destinationOffset in "
+ + CLASSNAME);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -169,8 +164,7 @@ public class NioByteStringTest extends TestCase {
try {
// Copy with illegal negative size
testString.copyTo(destination, 0, 0, -1);
- fail("Should have thrown an exception when given a negative size in "
- + CLASSNAME);
+ fail("Should have thrown an exception when given a negative size in " + CLASSNAME);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -178,8 +172,9 @@ public class NioByteStringTest extends TestCase {
try {
// Copy with illegal too-large sourceOffset
testString.copyTo(destination, 2 * testString.size(), 0, length);
- fail("Should have thrown an exception when the destinationOffset is too large in "
- + CLASSNAME);
+ fail(
+ "Should have thrown an exception when the destinationOffset is too large in "
+ + CLASSNAME);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -187,8 +182,9 @@ public class NioByteStringTest extends TestCase {
try {
// Copy with illegal too-large destinationOffset
testString.copyTo(destination, 0, 2 * destination.length, length);
- fail("Should have thrown an exception when the destinationOffset is too large in "
- + CLASSNAME);
+ fail(
+ "Should have thrown an exception when the destinationOffset is too large in "
+ + CLASSNAME);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -199,8 +195,8 @@ public class NioByteStringTest extends TestCase {
ByteBuffer myBuffer = ByteBuffer.allocate(BYTES.length);
testString.copyTo(myBuffer);
myBuffer.flip();
- assertEquals(CLASSNAME + ".copyTo(ByteBuffer) must give back the same bytes",
- backingBuffer, myBuffer);
+ assertEquals(
+ CLASSNAME + ".copyTo(ByteBuffer) must give back the same bytes", backingBuffer, myBuffer);
// Target buffer bigger than required.
myBuffer = ByteBuffer.allocate(testString.size() + 1);
@@ -241,30 +237,31 @@ public class NioByteStringTest extends TestCase {
skipFully(stream, fraction); // Skip a large fraction, but not all.
assertEquals(
CLASSNAME + ": after skipping to the 'middle', half the bytes are available",
- (testString.size() - fraction), stream.available());
+ (testString.size() - fraction),
+ stream.available());
stream.reset();
assertEquals(
CLASSNAME + ": after resetting, all bytes are available",
- testString.size(), stream.available());
+ testString.size(),
+ stream.available());
skipFully(stream, testString.size()); // Skip to the end.
assertEquals(
CLASSNAME + ": after skipping to the end, no more bytes are available",
- 0, stream.available());
+ 0,
+ stream.available());
}
/**
- * Discards {@code n} bytes of data from the input stream. This method
- * will block until the full amount has been skipped. Does not close the
- * stream.
+ * Discards {@code n} bytes of data from the input stream. This method will block until the full
+ * amount has been skipped. Does not close the stream.
+ *
* <p>Copied from com.google.common.io.ByteStreams to avoid adding dependency.
*
* @param in the input stream to read from
* @param n the number of bytes to skip
- * @throws EOFException if this stream reaches the end before skipping all
- * the bytes
- * @throws IOException if an I/O error occurs, or the stream does not
- * support skipping
+ * @throws EOFException if this stream reaches the end before skipping all the bytes
+ * @throws IOException if an I/O error occurs, or the stream does not support skipping
*/
static void skipFully(InputStream in, long n) throws IOException {
long toSkip = n;
@@ -274,8 +271,12 @@ public class NioByteStringTest extends TestCase {
// Force a blocking read to avoid infinite loop
if (in.read() == -1) {
long skipped = toSkip - n;
- throw new EOFException("reached end of stream after skipping "
- + skipped + " bytes; " + toSkip + " bytes expected");
+ throw new EOFException(
+ "reached end of stream after skipping "
+ + skipped
+ + " bytes; "
+ + toSkip
+ + " bytes expected");
}
n--;
} else {
@@ -290,7 +291,8 @@ public class NioByteStringTest extends TestCase {
assertTrue(byteBuffer.remaining() == BYTES.length);
assertTrue(byteBuffer.isReadOnly());
byteBuffer.get(roundTripBytes);
- assertTrue(CLASSNAME + ".asReadOnlyByteBuffer() must give back the same bytes",
+ assertTrue(
+ CLASSNAME + ".asReadOnlyByteBuffer() must give back the same bytes",
Arrays.equals(BYTES, roundTripBytes));
}
@@ -306,13 +308,15 @@ public class NioByteStringTest extends TestCase {
bytesSeen += thisLength;
}
assertTrue(bytesSeen == BYTES.length);
- assertTrue(CLASSNAME + ".asReadOnlyByteBufferTest() must give back the same bytes",
+ assertTrue(
+ CLASSNAME + ".asReadOnlyByteBufferTest() must give back the same bytes",
Arrays.equals(BYTES, roundTripBytes));
}
public void testToByteArray() {
byte[] roundTripBytes = testString.toByteArray();
- assertTrue(CLASSNAME + ".toByteArray() must give back the same bytes",
+ assertTrue(
+ CLASSNAME + ".toByteArray() must give back the same bytes",
Arrays.equals(BYTES, roundTripBytes));
}
@@ -320,80 +324,87 @@ public class NioByteStringTest extends TestCase {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
testString.writeTo(bos);
byte[] roundTripBytes = bos.toByteArray();
- assertTrue(CLASSNAME + ".writeTo() must give back the same bytes",
+ assertTrue(
+ CLASSNAME + ".writeTo() must give back the same bytes",
Arrays.equals(BYTES, roundTripBytes));
}
public void testWriteToShouldNotExposeInternalBufferToOutputStream() throws IOException {
- OutputStream os = new OutputStream() {
- @Override
- public void write(byte[] b, int off, int len) {
- Arrays.fill(b, off, off + len, (byte) 0);
- }
-
- @Override
- public void write(int b) {
- throw new UnsupportedOperationException();
- }
- };
+ OutputStream os =
+ new OutputStream() {
+ @Override
+ public void write(byte[] b, int off, int len) {
+ Arrays.fill(b, off, off + len, (byte) 0);
+ }
+
+ @Override
+ public void write(int b) {
+ throw new UnsupportedOperationException();
+ }
+ };
byte[] original = Arrays.copyOf(BYTES, BYTES.length);
testString.writeTo(os);
- assertTrue(CLASSNAME + ".writeTo() must NOT grant access to underlying buffer",
+ assertTrue(
+ CLASSNAME + ".writeTo() must NOT grant access to underlying buffer",
Arrays.equals(original, BYTES));
}
public void testWriteToInternalShouldExposeInternalBufferToOutputStream() throws IOException {
- OutputStream os = new OutputStream() {
- @Override
- public void write(byte[] b, int off, int len) {
- Arrays.fill(b, off, off + len, (byte) 0);
- }
-
- @Override
- public void write(int b) {
- throw new UnsupportedOperationException();
- }
- };
+ OutputStream os =
+ new OutputStream() {
+ @Override
+ public void write(byte[] b, int off, int len) {
+ Arrays.fill(b, off, off + len, (byte) 0);
+ }
+
+ @Override
+ public void write(int b) {
+ throw new UnsupportedOperationException();
+ }
+ };
testString.writeToInternal(os, 0, testString.size());
byte[] allZeros = new byte[testString.size()];
- assertTrue(CLASSNAME + ".writeToInternal() must grant access to underlying buffer",
+ assertTrue(
+ CLASSNAME + ".writeToInternal() must grant access to underlying buffer",
Arrays.equals(allZeros, backingBuffer.array()));
}
public void testWriteToShouldExposeInternalBufferToByteOutput() throws IOException {
- ByteOutput out = new ByteOutput() {
- @Override
- public void write(byte value) throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void write(byte[] value, int offset, int length) throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void writeLazy(byte[] value, int offset, int length) throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void write(ByteBuffer value) throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void writeLazy(ByteBuffer value) throws IOException {
- Arrays.fill(value.array(), value.arrayOffset(), value.arrayOffset() + value.limit(),
- (byte) 0);
- }
- };
+ ByteOutput out =
+ new ByteOutput() {
+ @Override
+ public void write(byte value) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void write(byte[] value, int offset, int length) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeLazy(byte[] value, int offset, int length) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void write(ByteBuffer value) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeLazy(ByteBuffer value) throws IOException {
+ Arrays.fill(
+ value.array(), value.arrayOffset(), value.arrayOffset() + value.limit(), (byte) 0);
+ }
+ };
testString.writeTo(out);
byte[] allZeros = new byte[testString.size()];
- assertTrue(CLASSNAME + ".writeTo() must grant access to underlying buffer",
+ assertTrue(
+ CLASSNAME + ".writeTo() must grant access to underlying buffer",
Arrays.equals(allZeros, backingBuffer.array()));
}
@@ -401,21 +412,21 @@ public class NioByteStringTest extends TestCase {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ByteString.Output output = ByteString.newOutput();
testString.writeTo(output);
- assertEquals("Output Size returns correct result",
- output.size(), testString.size());
+ assertEquals("Output Size returns correct result", output.size(), testString.size());
output.writeTo(bos);
- assertTrue("Output.writeTo() must give back the same bytes",
- Arrays.equals(BYTES, bos.toByteArray()));
+ assertTrue(
+ "Output.writeTo() must give back the same bytes", Arrays.equals(BYTES, bos.toByteArray()));
// write the output stream to itself! This should cause it to double
output.writeTo(output);
- assertEquals("Writing an output stream to itself is successful",
- testString.concat(testString), output.toByteString());
+ assertEquals(
+ "Writing an output stream to itself is successful",
+ testString.concat(testString),
+ output.toByteString());
output.reset();
assertEquals("Output.reset() resets the output", 0, output.size());
- assertEquals("Output.reset() resets the output",
- EMPTY, output.toByteString());
+ assertEquals("Output.reset() resets the output", EMPTY, output.toByteString());
}
public void testToString() {
@@ -433,7 +444,8 @@ public class NioByteStringTest extends TestCase {
}
public void testToString_returnsCanonicalEmptyString() {
- assertSame(CLASSNAME + " must be the same string references",
+ assertSame(
+ CLASSNAME + " must be the same string references",
EMPTY.toString(UTF_8),
new NioByteString(ByteBuffer.wrap(new byte[0])).toString(UTF_8));
}
@@ -457,33 +469,34 @@ public class NioByteStringTest extends TestCase {
public void testEquals() {
assertEquals(CLASSNAME + " must not equal null", false, testString.equals(null));
assertEquals(CLASSNAME + " must equal self", testString, testString);
- assertFalse(CLASSNAME + " must not equal the empty string",
- testString.equals(EMPTY));
- assertEquals(CLASSNAME + " empty strings must be equal",
- EMPTY, testString.substring(55, 55));
- assertEquals(CLASSNAME + " must equal another string with the same value",
- testString, new NioByteString(backingBuffer));
+ assertFalse(CLASSNAME + " must not equal the empty string", testString.equals(EMPTY));
+ assertEquals(CLASSNAME + " empty strings must be equal", EMPTY, testString.substring(55, 55));
+ assertEquals(
+ CLASSNAME + " must equal another string with the same value",
+ testString,
+ new NioByteString(backingBuffer));
byte[] mungedBytes = mungedBytes();
- assertFalse(CLASSNAME + " must not equal every string with the same length",
+ assertFalse(
+ CLASSNAME + " must not equal every string with the same length",
testString.equals(new NioByteString(ByteBuffer.wrap(mungedBytes))));
}
public void testEqualsLiteralByteString() {
ByteString literal = ByteString.copyFrom(BYTES);
- assertEquals(CLASSNAME + " must equal LiteralByteString with same value", literal,
- testString);
- assertEquals(CLASSNAME + " must equal LiteralByteString with same value", testString,
- literal);
- assertFalse(CLASSNAME + " must not equal the empty string",
- testString.equals(ByteString.EMPTY));
- assertEquals(CLASSNAME + " empty strings must be equal",
- ByteString.EMPTY, testString.substring(55, 55));
+ assertEquals(CLASSNAME + " must equal LiteralByteString with same value", literal, testString);
+ assertEquals(CLASSNAME + " must equal LiteralByteString with same value", testString, literal);
+ assertFalse(
+ CLASSNAME + " must not equal the empty string", testString.equals(ByteString.EMPTY));
+ assertEquals(
+ CLASSNAME + " empty strings must be equal", ByteString.EMPTY, testString.substring(55, 55));
literal = ByteString.copyFrom(mungedBytes());
- assertFalse(CLASSNAME + " must not equal every LiteralByteString with the same length",
+ assertFalse(
+ CLASSNAME + " must not equal every LiteralByteString with the same length",
testString.equals(literal));
- assertFalse(CLASSNAME + " must not equal every LiteralByteString with the same length",
+ assertFalse(
+ CLASSNAME + " must not equal every LiteralByteString with the same length",
literal.equals(testString));
}
@@ -492,22 +505,25 @@ public class NioByteStringTest extends TestCase {
ByteString p2 = ByteString.copyFrom(BYTES, 5, BYTES.length - 5);
ByteString rope = p1.concat(p2);
- assertEquals(CLASSNAME + " must equal RopeByteString with same value", rope,
- testString);
- assertEquals(CLASSNAME + " must equal RopeByteString with same value", testString,
- rope);
- assertFalse(CLASSNAME + " must not equal the empty string",
+ assertEquals(CLASSNAME + " must equal RopeByteString with same value", rope, testString);
+ assertEquals(CLASSNAME + " must equal RopeByteString with same value", testString, rope);
+ assertFalse(
+ CLASSNAME + " must not equal the empty string",
testString.equals(ByteString.EMPTY.concat(ByteString.EMPTY)));
- assertEquals(CLASSNAME + " empty strings must be equal",
- ByteString.EMPTY.concat(ByteString.EMPTY), testString.substring(55, 55));
+ assertEquals(
+ CLASSNAME + " empty strings must be equal",
+ ByteString.EMPTY.concat(ByteString.EMPTY),
+ testString.substring(55, 55));
byte[] mungedBytes = mungedBytes();
p1 = ByteString.copyFrom(mungedBytes, 0, 5);
p2 = ByteString.copyFrom(mungedBytes, 5, mungedBytes.length - 5);
rope = p1.concat(p2);
- assertFalse(CLASSNAME + " must not equal every RopeByteString with the same length",
+ assertFalse(
+ CLASSNAME + " must not equal every RopeByteString with the same length",
testString.equals(rope));
- assertFalse(CLASSNAME + " must not equal every RopeByteString with the same length",
+ assertFalse(
+ CLASSNAME + " must not equal every RopeByteString with the same length",
rope.equals(testString));
}
@@ -525,32 +541,34 @@ public class NioByteStringTest extends TestCase {
public void testPeekCachedHashCode() {
ByteString newString = new NioByteString(backingBuffer);
- assertEquals(CLASSNAME + ".peekCachedHashCode() should return zero at first", 0,
+ assertEquals(
+ CLASSNAME + ".peekCachedHashCode() should return zero at first",
+ 0,
newString.peekCachedHashCode());
newString.hashCode();
- assertEquals(CLASSNAME + ".peekCachedHashCode should return zero at first",
- EXPECTED_HASH, newString.peekCachedHashCode());
+ assertEquals(
+ CLASSNAME + ".peekCachedHashCode should return zero at first",
+ EXPECTED_HASH,
+ newString.peekCachedHashCode());
}
public void testPartialHash() {
// partialHash() is more strenuously tested elsewhere by testing hashes of substrings.
// This test would fail if the expected hash were 1. It's not.
int hash = testString.partialHash(testString.size(), 0, testString.size());
- assertEquals(CLASSNAME + ".partialHash() must yield expected hashCode",
- EXPECTED_HASH, hash);
+ assertEquals(CLASSNAME + ".partialHash() must yield expected hashCode", EXPECTED_HASH, hash);
}
public void testNewInput() throws IOException {
InputStream input = testString.newInput();
- assertEquals("InputStream.available() returns correct value",
- testString.size(), input.available());
+ assertEquals(
+ "InputStream.available() returns correct value", testString.size(), input.available());
boolean stillEqual = true;
for (byte referenceByte : BYTES) {
int expectedInt = (referenceByte & 0xFF);
stillEqual = (expectedInt == input.read());
}
- assertEquals("InputStream.available() returns correct value",
- 0, input.available());
+ assertEquals("InputStream.available() returns correct value", 0, input.available());
assertTrue(CLASSNAME + " must give the same bytes from the InputStream", stillEqual);
assertEquals(CLASSNAME + " InputStream must now be exhausted", -1, input.read());
}
@@ -561,43 +579,44 @@ public class NioByteStringTest extends TestCase {
int nearEndIndex = stringSize * 2 / 3;
long skipped1 = input.skip(nearEndIndex);
assertEquals("InputStream.skip()", skipped1, nearEndIndex);
- assertEquals("InputStream.available()",
- stringSize - skipped1, input.available());
+ assertEquals("InputStream.available()", stringSize - skipped1, input.available());
assertTrue("InputStream.mark() is available", input.markSupported());
input.mark(0);
- assertEquals("InputStream.skip(), read()",
- testString.byteAt(nearEndIndex) & 0xFF, input.read());
- assertEquals("InputStream.available()",
- stringSize - skipped1 - 1, input.available());
+ assertEquals(
+ "InputStream.skip(), read()", testString.byteAt(nearEndIndex) & 0xFF, input.read());
+ assertEquals("InputStream.available()", stringSize - skipped1 - 1, input.available());
long skipped2 = input.skip(stringSize);
- assertEquals("InputStream.skip() incomplete",
- skipped2, stringSize - skipped1 - 1);
+ assertEquals("InputStream.skip() incomplete", skipped2, stringSize - skipped1 - 1);
assertEquals("InputStream.skip(), no more input", 0, input.available());
assertEquals("InputStream.skip(), no more input", -1, input.read());
input.reset();
- assertEquals("InputStream.reset() succeded",
- stringSize - skipped1, input.available());
- assertEquals("InputStream.reset(), read()",
- testString.byteAt(nearEndIndex) & 0xFF, input.read());
+ assertEquals("InputStream.reset() succeded", stringSize - skipped1, input.available());
+ assertEquals(
+ "InputStream.reset(), read()", testString.byteAt(nearEndIndex) & 0xFF, input.read());
}
public void testNewCodedInput() throws IOException {
CodedInputStream cis = testString.newCodedInput();
byte[] roundTripBytes = cis.readRawBytes(BYTES.length);
- assertTrue(CLASSNAME + " must give the same bytes back from the CodedInputStream",
+ assertTrue(
+ CLASSNAME + " must give the same bytes back from the CodedInputStream",
Arrays.equals(BYTES, roundTripBytes));
assertTrue(CLASSNAME + " CodedInputStream must now be exhausted", cis.isAtEnd());
}
/**
- * Make sure we keep things simple when concatenating with empty. See also
- * {@link ByteStringTest#testConcat_empty()}.
+ * Make sure we keep things simple when concatenating with empty. See also {@link
+ * ByteStringTest#testConcat_empty()}.
*/
public void testConcat_empty() {
- assertSame(CLASSNAME + " concatenated with empty must give " + CLASSNAME,
- testString.concat(EMPTY), testString);
- assertSame("empty concatenated with " + CLASSNAME + " must give " + CLASSNAME,
- EMPTY.concat(testString), testString);
+ assertSame(
+ CLASSNAME + " concatenated with empty must give " + CLASSNAME,
+ testString.concat(EMPTY),
+ testString);
+ assertSame(
+ "empty concatenated with " + CLASSNAME + " must give " + CLASSNAME,
+ EMPTY.concat(testString),
+ testString);
}
public void testJavaSerialization() throws Exception {
diff --git a/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java b/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java
index e376b1cd..20b93809 100644
--- a/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java
@@ -48,9 +48,9 @@ import org.junit.runners.JUnit4;
/**
* Tests the exceptions thrown when parsing from a stream. The methods on the {@link Parser}
* interface are specified to only throw {@link InvalidProtocolBufferException}. But we really want
- * to distinguish between invalid protos vs. actual I/O errors (like failures reading from a
- * socket, etc.). So, when we're not using the parser directly, an {@link IOException} should be
- * thrown where appropriate, instead of always an {@link InvalidProtocolBufferException}.
+ * to distinguish between invalid protos vs. actual I/O errors (like failures reading from a socket,
+ * etc.). So, when we're not using the parser directly, an {@link IOException} should be thrown
+ * where appropriate, instead of always an {@link InvalidProtocolBufferException}.
*
* @author jh@squareup.com (Joshua Humphries)
*/
@@ -61,7 +61,7 @@ public class ParseExceptionsTest {
DescriptorProto parse(InputStream in) throws IOException;
}
- private byte serializedProto[];
+ private byte[] serializedProto;
private void setup() {
serializedProto = DescriptorProto.getDescriptor().toProto().toByteArray();
@@ -77,7 +77,8 @@ public class ParseExceptionsTest {
serializedProto = bos.toByteArray();
}
- @Test public void message_parseFrom_InputStream() {
+ @Test
+ public void message_parseFrom_InputStream() {
setup();
verifyExceptions(
new ParseTester() {
@@ -88,7 +89,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void message_parseFrom_InputStreamAndExtensionRegistry() {
+ @Test
+ public void message_parseFrom_InputStreamAndExtensionRegistry() {
setup();
verifyExceptions(
new ParseTester() {
@@ -99,7 +101,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void message_parseFrom_CodedInputStream() {
+ @Test
+ public void message_parseFrom_CodedInputStream() {
setup();
verifyExceptions(
new ParseTester() {
@@ -110,7 +113,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void message_parseFrom_CodedInputStreamAndExtensionRegistry() {
+ @Test
+ public void message_parseFrom_CodedInputStreamAndExtensionRegistry() {
setup();
verifyExceptions(
new ParseTester() {
@@ -122,7 +126,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void message_parseDelimitedFrom_InputStream() {
+ @Test
+ public void message_parseDelimitedFrom_InputStream() {
setupDelimited();
verifyExceptions(
new ParseTester() {
@@ -133,7 +138,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void message_parseDelimitedFrom_InputStreamAndExtensionRegistry() {
+ @Test
+ public void message_parseDelimitedFrom_InputStreamAndExtensionRegistry() {
setupDelimited();
verifyExceptions(
new ParseTester() {
@@ -144,7 +150,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void messageBuilder_mergeFrom_InputStream() {
+ @Test
+ public void messageBuilder_mergeFrom_InputStream() {
setup();
verifyExceptions(
new ParseTester() {
@@ -155,7 +162,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void messageBuilder_mergeFrom_InputStreamAndExtensionRegistry() {
+ @Test
+ public void messageBuilder_mergeFrom_InputStreamAndExtensionRegistry() {
setup();
verifyExceptions(
new ParseTester() {
@@ -168,7 +176,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void messageBuilder_mergeFrom_CodedInputStream() {
+ @Test
+ public void messageBuilder_mergeFrom_CodedInputStream() {
setup();
verifyExceptions(
new ParseTester() {
@@ -179,7 +188,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void messageBuilder_mergeFrom_CodedInputStreamAndExtensionRegistry() {
+ @Test
+ public void messageBuilder_mergeFrom_CodedInputStreamAndExtensionRegistry() {
setup();
verifyExceptions(
new ParseTester() {
@@ -192,7 +202,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void messageBuilder_mergeDelimitedFrom_InputStream() {
+ @Test
+ public void messageBuilder_mergeDelimitedFrom_InputStream() {
setupDelimited();
verifyExceptions(
new ParseTester() {
@@ -205,7 +216,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void messageBuilder_mergeDelimitedFrom_InputStreamAndExtensionRegistry() {
+ @Test
+ public void messageBuilder_mergeDelimitedFrom_InputStreamAndExtensionRegistry() {
setupDelimited();
verifyExceptions(
new ParseTester() {
@@ -221,7 +233,8 @@ public class ParseExceptionsTest {
private void verifyExceptions(ParseTester parseTester) {
// No exception
try {
- assertEquals(DescriptorProto.getDescriptor().toProto(),
+ assertEquals(
+ DescriptorProto.getDescriptor().toProto(),
parseTester.parse(new ByteArrayInputStream(serializedProto)));
} catch (IOException e) {
fail("No exception expected: " + e);
@@ -253,14 +266,16 @@ public class ParseExceptionsTest {
return new FilterInputStream(i) {
int count = 0;
- @Override public int read() throws IOException {
+ @Override
+ public int read() throws IOException {
if (count++ >= 50) {
throw new IOException("I'm broken!");
}
return super.read();
}
- @Override public int read(byte b[], int off, int len) throws IOException {
+ @Override
+ public int read(byte[] b, int off, int len) throws IOException {
if ((count += len) >= 50) {
throw new IOException("I'm broken!");
}
diff --git a/java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java b/java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java
index 0a2c3e37..67b2881a 100644
--- a/java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java
@@ -38,9 +38,7 @@ import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
-/**
- * Tests for {@link ProtobufArrayList}.
- */
+/** Tests for {@link ProtobufArrayList}. */
public class ProtobufArrayListTest extends TestCase {
private static final ProtobufArrayList<Integer> UNARY_LIST = newImmutableProtoArrayList(1);
diff --git a/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java b/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java
index edbd0afd..c42813c8 100644
--- a/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java
+++ b/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java
@@ -37,9 +37,8 @@ import java.util.List;
import junit.framework.TestCase;
/**
- * Tests for {@link RepeatedFieldBuilderV3}. This tests basic functionality.
- * More extensive testing is provided via other tests that exercise the
- * builder.
+ * Tests for {@link RepeatedFieldBuilderV3}. This tests basic functionality. More extensive testing is
+ * provided via other tests that exercise the builder.
*
* @author jonp@google.com (Jon Perlow)
*/
@@ -47,8 +46,8 @@ public class RepeatedFieldBuilderV3Test extends TestCase {
public void testBasicUse() {
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder> builder = newRepeatedFieldBuilderV3(mockParent);
+ RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder> builder =
+ newRepeatedFieldBuilderV3(mockParent);
builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build());
builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build());
assertEquals(0, builder.getMessage(0).getOptionalInt32());
@@ -68,8 +67,8 @@ public class RepeatedFieldBuilderV3Test extends TestCase {
public void testGoingBackAndForth() {
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder> builder = newRepeatedFieldBuilderV3(mockParent);
+ RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder> builder =
+ newRepeatedFieldBuilderV3(mockParent);
builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build());
builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build());
assertEquals(0, builder.getMessage(0).getOptionalInt32());
@@ -89,7 +88,7 @@ public class RepeatedFieldBuilderV3Test extends TestCase {
list = builder.build();
assertEquals(2, list.size());
assertEquals(0, list.get(0).getOptionalInt32());
- assertEquals("foo", list.get(0).getOptionalString());
+ assertEquals("foo", list.get(0).getOptionalString());
assertEquals(1, list.get(1).getOptionalInt32());
assertIsUnmodifiable(list);
assertEquals(1, mockParent.getInvalidationCount());
@@ -97,12 +96,11 @@ public class RepeatedFieldBuilderV3Test extends TestCase {
public void testVariousMethods() {
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder> builder = newRepeatedFieldBuilderV3(mockParent);
+ RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder> builder =
+ newRepeatedFieldBuilderV3(mockParent);
builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build());
builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(2).build());
- builder.addBuilder(0, TestAllTypes.getDefaultInstance())
- .setOptionalInt32(0);
+ builder.addBuilder(0, TestAllTypes.getDefaultInstance()).setOptionalInt32(0);
builder.addBuilder(TestAllTypes.getDefaultInstance()).setOptionalInt32(3);
assertEquals(0, builder.getMessage(0).getOptionalInt32());
@@ -139,11 +137,10 @@ public class RepeatedFieldBuilderV3Test extends TestCase {
public void testLists() {
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder> builder = newRepeatedFieldBuilderV3(mockParent);
+ RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder> builder =
+ newRepeatedFieldBuilderV3(mockParent);
builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build());
- builder.addMessage(0,
- TestAllTypes.newBuilder().setOptionalInt32(0).build());
+ builder.addMessage(0, TestAllTypes.newBuilder().setOptionalInt32(0).build());
assertEquals(0, builder.getMessage(0).getOptionalInt32());
assertEquals(1, builder.getMessage(1).getOptionalInt32());
@@ -178,11 +175,9 @@ public class RepeatedFieldBuilderV3Test extends TestCase {
}
}
- private RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder>
+ private RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder>
newRepeatedFieldBuilderV3(GeneratedMessage.BuilderParent parent) {
- return new RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder>(Collections.<TestAllTypes>emptyList(), false,
- parent, false);
+ return new RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder>(
+ Collections.<TestAllTypes>emptyList(), false, parent, false);
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/RopeByteStringSubstringTest.java b/java/core/src/test/java/com/google/protobuf/RopeByteStringSubstringTest.java
index dc56f2e9..d7262161 100644
--- a/java/core/src/test/java/com/google/protobuf/RopeByteStringSubstringTest.java
+++ b/java/core/src/test/java/com/google/protobuf/RopeByteStringSubstringTest.java
@@ -34,8 +34,8 @@ import java.io.UnsupportedEncodingException;
import java.util.Iterator;
/**
- * This class tests {@link RopeByteString#substring(int, int)} by inheriting the tests from
- * {@link LiteralByteStringTest}. Only a couple of methods are overridden.
+ * This class tests {@link RopeByteString#substring(int, int)} by inheriting the tests from {@link
+ * LiteralByteStringTest}. Only a couple of methods are overridden.
*
* @author carlanton@google.com (Carl Haverl)
*/
@@ -61,8 +61,8 @@ public class RopeByteStringSubstringTest extends LiteralByteStringTest {
@Override
public void testGetTreeDepth() {
- assertEquals(classUnderTest + " must have the expected tree depth",
- 3, stringUnderTest.getTreeDepth());
+ assertEquals(
+ classUnderTest + " must have the expected tree depth", 3, stringUnderTest.getTreeDepth());
}
@Override
@@ -84,15 +84,18 @@ public class RopeByteStringSubstringTest extends LiteralByteStringTest {
testString = testString.substring(2, testString.length() - 6);
unicode = unicode.substring(2, unicode.size() - 6);
- assertEquals(classUnderTest + " from string must have the expected type",
- classUnderTest, getActualClassName(unicode));
+ assertEquals(
+ classUnderTest + " from string must have the expected type",
+ classUnderTest,
+ getActualClassName(unicode));
String roundTripString = unicode.toString(UTF_8);
- assertEquals(classUnderTest + " unicode bytes must match",
- testString, roundTripString);
+ assertEquals(classUnderTest + " unicode bytes must match", testString, roundTripString);
ByteString flatString = ByteString.copyFromUtf8(testString);
assertEquals(classUnderTest + " string must equal the flat string", flatString, unicode);
- assertEquals(classUnderTest + " string must must have same hashCode as the flat string",
- flatString.hashCode(), unicode.hashCode());
+ assertEquals(
+ classUnderTest + " string must must have same hashCode as the flat string",
+ flatString.hashCode(),
+ unicode.hashCode());
}
@Override
@@ -114,14 +117,17 @@ public class RopeByteStringSubstringTest extends LiteralByteStringTest {
testString = testString.substring(2, testString.length() - 6);
unicode = unicode.substring(2, unicode.size() - 6);
- assertEquals(classUnderTest + " from string must have the expected type",
- classUnderTest, getActualClassName(unicode));
+ assertEquals(
+ classUnderTest + " from string must have the expected type",
+ classUnderTest,
+ getActualClassName(unicode));
String roundTripString = unicode.toString(Internal.UTF_8);
- assertEquals(classUnderTest + " unicode bytes must match",
- testString, roundTripString);
+ assertEquals(classUnderTest + " unicode bytes must match", testString, roundTripString);
ByteString flatString = ByteString.copyFromUtf8(testString);
assertEquals(classUnderTest + " string must equal the flat string", flatString, unicode);
- assertEquals(classUnderTest + " string must must have same hashCode as the flat string",
- flatString.hashCode(), unicode.hashCode());
+ assertEquals(
+ classUnderTest + " string must must have same hashCode as the flat string",
+ flatString.hashCode(),
+ unicode.hashCode());
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/RopeByteStringTest.java b/java/core/src/test/java/com/google/protobuf/RopeByteStringTest.java
index 4ec3a409..59e8ede1 100644
--- a/java/core/src/test/java/com/google/protobuf/RopeByteStringTest.java
+++ b/java/core/src/test/java/com/google/protobuf/RopeByteStringTest.java
@@ -40,8 +40,8 @@ import java.util.Arrays;
import java.util.Iterator;
/**
- * This class tests {@link RopeByteString} by inheriting the tests from
- * {@link LiteralByteStringTest}. Only a couple of methods are overridden.
+ * This class tests {@link RopeByteString} by inheriting the tests from {@link
+ * LiteralByteStringTest}. Only a couple of methods are overridden.
*
* <p>A full test of the result of {@link RopeByteString#substring(int, int)} is found in the
* separate class {@link RopeByteStringSubstringTest}.
@@ -64,8 +64,8 @@ public class RopeByteStringTest extends LiteralByteStringTest {
@Override
public void testGetTreeDepth() {
- assertEquals(classUnderTest + " must have the expected tree depth",
- 4, stringUnderTest.getTreeDepth());
+ assertEquals(
+ classUnderTest + " must have the expected tree depth", 4, stringUnderTest.getTreeDepth());
}
public void testBalance() {
@@ -79,17 +79,22 @@ public class RopeByteStringTest extends LiteralByteStringTest {
concatenated = concatenated.concat(ByteString.copyFrom(testBytes, i * pieceSize, pieceSize));
}
- assertEquals(classUnderTest + " from string must have the expected type",
- classUnderTest, getActualClassName(concatenated));
- assertTrue(classUnderTest + " underlying bytes must match after balancing",
+ assertEquals(
+ classUnderTest + " from string must have the expected type",
+ classUnderTest,
+ getActualClassName(concatenated));
+ assertTrue(
+ classUnderTest + " underlying bytes must match after balancing",
Arrays.equals(testBytes, concatenated.toByteArray()));
ByteString testString = ByteString.copyFrom(testBytes);
- assertTrue(classUnderTest + " balanced string must equal flat string",
- concatenated.equals(testString));
- assertTrue(classUnderTest + " flat string must equal balanced string",
- testString.equals(concatenated));
- assertEquals(classUnderTest + " balanced string must have same hash code as flat string",
- testString.hashCode(), concatenated.hashCode());
+ assertEquals(
+ classUnderTest + " balanced string must equal flat string", testString, concatenated);
+ assertEquals(
+ classUnderTest + " flat string must equal balanced string", concatenated, testString);
+ assertEquals(
+ classUnderTest + " balanced string must have same hash code as flat string",
+ testString.hashCode(),
+ concatenated.hashCode());
}
@Override
@@ -107,15 +112,18 @@ public class RopeByteStringTest extends LiteralByteStringTest {
}
String testString = builder.toString();
- assertEquals(classUnderTest + " from string must have the expected type",
- classUnderTest, getActualClassName(unicode));
+ assertEquals(
+ classUnderTest + " from string must have the expected type",
+ classUnderTest,
+ getActualClassName(unicode));
String roundTripString = unicode.toString(UTF_8);
- assertEquals(classUnderTest + " unicode bytes must match",
- testString, roundTripString);
+ assertEquals(classUnderTest + " unicode bytes must match", testString, roundTripString);
ByteString flatString = ByteString.copyFromUtf8(testString);
assertEquals(classUnderTest + " string must equal the flat string", flatString, unicode);
- assertEquals(classUnderTest + " string must must have same hashCode as the flat string",
- flatString.hashCode(), unicode.hashCode());
+ assertEquals(
+ classUnderTest + " string must must have same hashCode as the flat string",
+ flatString.hashCode(),
+ unicode.hashCode());
}
@Override
@@ -133,30 +141,34 @@ public class RopeByteStringTest extends LiteralByteStringTest {
}
String testString = builder.toString();
- assertEquals(classUnderTest + " from string must have the expected type",
- classUnderTest, getActualClassName(unicode));
+ assertEquals(
+ classUnderTest + " from string must have the expected type",
+ classUnderTest,
+ getActualClassName(unicode));
String roundTripString = unicode.toString(Internal.UTF_8);
- assertEquals(classUnderTest + " unicode bytes must match",
- testString, roundTripString);
+ assertEquals(classUnderTest + " unicode bytes must match", testString, roundTripString);
ByteString flatString = ByteString.copyFromUtf8(testString);
assertEquals(classUnderTest + " string must equal the flat string", flatString, unicode);
- assertEquals(classUnderTest + " string must must have same hashCode as the flat string",
- flatString.hashCode(), unicode.hashCode());
+ assertEquals(
+ classUnderTest + " string must must have same hashCode as the flat string",
+ flatString.hashCode(),
+ unicode.hashCode());
}
@Override
public void testToString_returnsCanonicalEmptyString() {
RopeByteString ropeByteString =
RopeByteString.newInstanceForTest(ByteString.EMPTY, ByteString.EMPTY);
- assertSame(classUnderTest + " must be the same string references",
- ByteString.EMPTY.toString(Internal.UTF_8), ropeByteString.toString(Internal.UTF_8));
+ assertSame(
+ classUnderTest + " must be the same string references",
+ ByteString.EMPTY.toString(Internal.UTF_8),
+ ropeByteString.toString(Internal.UTF_8));
}
@Override
public void testToString_raisesException() {
try {
- ByteString byteString =
- RopeByteString.newInstanceForTest(ByteString.EMPTY, ByteString.EMPTY);
+ ByteString byteString = RopeByteString.newInstanceForTest(ByteString.EMPTY, ByteString.EMPTY);
byteString.toString("invalid");
fail("Should have thrown an exception.");
} catch (UnsupportedEncodingException expected) {
@@ -164,8 +176,9 @@ public class RopeByteStringTest extends LiteralByteStringTest {
}
try {
- ByteString byteString = RopeByteString.concatenate(ByteString.copyFromUtf8("foo"),
- ByteString.copyFromUtf8("bar"));
+ ByteString byteString =
+ RopeByteString.concatenate(
+ ByteString.copyFromUtf8("foo"), ByteString.copyFromUtf8("bar"));
byteString.toString("invalid");
fail("Should have thrown an exception.");
} catch (UnsupportedEncodingException expected) {
diff --git a/java/core/src/test/java/com/google/protobuf/ServiceTest.java b/java/core/src/test/java/com/google/protobuf/ServiceTest.java
index b895ad8d..1e583329 100644
--- a/java/core/src/test/java/com/google/protobuf/ServiceTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ServiceTest.java
@@ -41,7 +41,6 @@ import protobuf_unittest.UnittestProto.FooRequest;
import protobuf_unittest.UnittestProto.FooResponse;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestService;
-
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
@@ -270,30 +269,27 @@ public class ServiceTest extends TestCase {
}
-
// =================================================================
/**
- * wrapsCallback() is an EasyMock argument predicate. wrapsCallback(c)
- * matches a callback if calling that callback causes c to be called.
- * In other words, c wraps the given callback.
+ * wrapsCallback() is an EasyMock argument predicate. wrapsCallback(c) matches a callback if
+ * calling that callback causes c to be called. In other words, c wraps the given callback.
*/
- private <Type extends Message> RpcCallback<Type> wrapsCallback(
- MockCallback<?> callback) {
+ private <T extends Message> RpcCallback<T> wrapsCallback(MockCallback<?> callback) {
EasyMock.reportMatcher(new WrapsCallback(callback));
return null;
}
/** The parameter to wrapsCallback() must be a MockCallback. */
- private static class MockCallback<Type extends Message>
- implements RpcCallback<Type> {
+ private static class MockCallback<T extends Message> implements RpcCallback<T> {
private boolean called = false;
public boolean isCalled() { return called; }
public void reset() { called = false; }
+
@Override
- public void run(Type message) {
+ public void run(T message) {
called = true; }
}
diff --git a/java/core/src/test/java/com/google/protobuf/SingleFieldBuilderV3Test.java b/java/core/src/test/java/com/google/protobuf/SingleFieldBuilderV3Test.java
index e3a8d4f4..f2ae8f9b 100644
--- a/java/core/src/test/java/com/google/protobuf/SingleFieldBuilderV3Test.java
+++ b/java/core/src/test/java/com/google/protobuf/SingleFieldBuilderV3Test.java
@@ -32,13 +32,11 @@ package com.google.protobuf;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestAllTypesOrBuilder;
-
import junit.framework.TestCase;
/**
- * Tests for {@link SingleFieldBuilderV3}. This tests basic functionality.
- * More extensive testing is provided via other tests that exercise the
- * builder.
+ * Tests for {@link SingleFieldBuilderV3}. This tests basic functionality. More extensive testing is
+ * provided via other tests that exercise the builder.
*
* @author jonp@google.com (Jon Perlow)
*/
@@ -46,16 +44,11 @@ public class SingleFieldBuilderV3Test extends TestCase {
public void testBasicUseAndInvalidations() {
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder> builder =
- new SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder>(
- TestAllTypes.getDefaultInstance(),
- mockParent,
- false);
+ SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder> builder =
+ new SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder>(
+ TestAllTypes.getDefaultInstance(), mockParent, false);
assertSame(TestAllTypes.getDefaultInstance(), builder.getMessage());
- assertEquals(TestAllTypes.getDefaultInstance(),
- builder.getBuilder().buildPartial());
+ assertEquals(TestAllTypes.getDefaultInstance(), builder.getBuilder().buildPartial());
assertEquals(0, mockParent.getInvalidationCount());
builder.getBuilder().setOptionalInt32(10);
@@ -71,18 +64,13 @@ public class SingleFieldBuilderV3Test extends TestCase {
// Test that we don't keep getting invalidations on every change
builder.getBuilder().setOptionalInt32(30);
assertEquals(1, mockParent.getInvalidationCount());
-
}
public void testSetMessage() {
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder> builder =
- new SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder>(
- TestAllTypes.getDefaultInstance(),
- mockParent,
- false);
+ SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder> builder =
+ new SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder>(
+ TestAllTypes.getDefaultInstance(), mockParent, false);
builder.setMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build());
assertEquals(0, builder.getMessage().getOptionalInt32());
@@ -102,13 +90,9 @@ public class SingleFieldBuilderV3Test extends TestCase {
public void testClear() {
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder> builder =
- new SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder>(
- TestAllTypes.getDefaultInstance(),
- mockParent,
- false);
+ SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder> builder =
+ new SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder>(
+ TestAllTypes.getDefaultInstance(), mockParent, false);
builder.setMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build());
assertNotSame(TestAllTypes.getDefaultInstance(), builder.getMessage());
builder.clear();
@@ -122,13 +106,9 @@ public class SingleFieldBuilderV3Test extends TestCase {
public void testMerge() {
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder> builder =
- new SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder>(
- TestAllTypes.getDefaultInstance(),
- mockParent,
- false);
+ SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder> builder =
+ new SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder>(
+ TestAllTypes.getDefaultInstance(), mockParent, false);
// Merge into default field.
builder.mergeFrom(TestAllTypes.getDefaultInstance());
@@ -136,20 +116,14 @@ public class SingleFieldBuilderV3Test extends TestCase {
// Merge into non-default field on existing builder.
builder.getBuilder().setOptionalInt32(2);
- builder.mergeFrom(TestAllTypes.newBuilder()
- .setOptionalDouble(4.0)
- .buildPartial());
+ builder.mergeFrom(TestAllTypes.newBuilder().setOptionalDouble(4.0).buildPartial());
assertEquals(2, builder.getMessage().getOptionalInt32());
- assertEquals(4.0, builder.getMessage().getOptionalDouble());
+ assertEquals(4.0, builder.getMessage().getOptionalDouble(), 0.0);
// Merge into non-default field on existing message
- builder.setMessage(TestAllTypes.newBuilder()
- .setOptionalInt32(10)
- .buildPartial());
- builder.mergeFrom(TestAllTypes.newBuilder()
- .setOptionalDouble(5.0)
- .buildPartial());
+ builder.setMessage(TestAllTypes.newBuilder().setOptionalInt32(10).buildPartial());
+ builder.mergeFrom(TestAllTypes.newBuilder().setOptionalDouble(5.0).buildPartial());
assertEquals(10, builder.getMessage().getOptionalInt32());
- assertEquals(5.0, builder.getMessage().getOptionalDouble());
+ assertEquals(5.0, builder.getMessage().getOptionalDouble(), 0.0);
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java b/java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java
index a7f8342d..a1a7194b 100644
--- a/java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java
+++ b/java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java
@@ -40,9 +40,7 @@ import java.util.Set;
import java.util.TreeSet;
import junit.framework.TestCase;
-/**
- * @author darick@google.com Darick Tong
- */
+/** @author darick@google.com Darick Tong */
public class SmallSortedMapTest extends TestCase {
// java.util.AbstractMap.SimpleEntry is private in JDK 1.5. We re-implement it
// here for JDK 1.5 users.
@@ -78,16 +76,16 @@ public class SmallSortedMapTest extends TestCase {
@Override
public boolean equals(Object o) {
- if (!(o instanceof Map.Entry))
+ if (!(o instanceof Map.Entry)) {
return false;
+ }
Map.Entry e = (Map.Entry) o;
return eq(key, e.getKey()) && eq(value, e.getValue());
}
@Override
public int hashCode() {
- return ((key == null) ? 0 : key.hashCode()) ^
- ((value == null) ? 0 : value.hashCode());
+ return ((key == null) ? 0 : key.hashCode()) ^ ((value == null) ? 0 : value.hashCode());
}
}
@@ -101,14 +99,10 @@ public class SmallSortedMapTest extends TestCase {
private void runPutAndGetTest(int numElements) {
// Test with even and odd arraySize
- SmallSortedMap<Integer, Integer> map1 =
- SmallSortedMap.newInstanceForTest(3);
- SmallSortedMap<Integer, Integer> map2 =
- SmallSortedMap.newInstanceForTest(4);
- SmallSortedMap<Integer, Integer> map3 =
- SmallSortedMap.newInstanceForTest(3);
- SmallSortedMap<Integer, Integer> map4 =
- SmallSortedMap.newInstanceForTest(4);
+ SmallSortedMap<Integer, Integer> map1 = SmallSortedMap.newInstanceForTest(3);
+ SmallSortedMap<Integer, Integer> map2 = SmallSortedMap.newInstanceForTest(4);
+ SmallSortedMap<Integer, Integer> map3 = SmallSortedMap.newInstanceForTest(3);
+ SmallSortedMap<Integer, Integer> map4 = SmallSortedMap.newInstanceForTest(4);
// Test with puts in ascending order.
for (int i = 0; i < numElements; i++) {
@@ -136,7 +130,7 @@ public class SmallSortedMapTest extends TestCase {
for (SmallSortedMap<Integer, Integer> map : allMaps) {
assertEquals(numElements, map.size());
for (int i = 0; i < numElements; i++) {
- assertEquals(new Integer(i + 1), map.get(i));
+ assertEquals(Integer.valueOf(i + 1), map.get(i));
}
}
@@ -152,7 +146,7 @@ public class SmallSortedMapTest extends TestCase {
assertNull(map.remove(i + 1));
}
for (int i = 0; i < 6; i++) {
- assertEquals(new Integer(i + 1), map.put(i, i + 2));
+ assertEquals(Integer.valueOf(i + 1), map.put(i, i + 2));
}
}
@@ -165,22 +159,22 @@ public class SmallSortedMapTest extends TestCase {
assertEquals(3, map.getNumArrayEntries());
assertEquals(3, map.getNumOverflowEntries());
- assertEquals(6, map.size());
+ assertEquals(6, map.size());
assertEquals(makeSortedKeySet(0, 1, 2, 3, 4, 5), map.keySet());
- assertEquals(new Integer(2), map.remove(1));
+ assertEquals(Integer.valueOf(2), map.remove(1));
assertEquals(3, map.getNumArrayEntries());
assertEquals(2, map.getNumOverflowEntries());
- assertEquals(5, map.size());
+ assertEquals(5, map.size());
assertEquals(makeSortedKeySet(0, 2, 3, 4, 5), map.keySet());
- assertEquals(new Integer(5), map.remove(4));
+ assertEquals(Integer.valueOf(5), map.remove(4));
assertEquals(3, map.getNumArrayEntries());
assertEquals(1, map.getNumOverflowEntries());
- assertEquals(4, map.size());
+ assertEquals(4, map.size());
assertEquals(makeSortedKeySet(0, 2, 3, 5), map.keySet());
- assertEquals(new Integer(4), map.remove(3));
+ assertEquals(Integer.valueOf(4), map.remove(3));
assertEquals(3, map.getNumArrayEntries());
assertEquals(0, map.getNumOverflowEntries());
assertEquals(3, map.size());
@@ -191,7 +185,7 @@ public class SmallSortedMapTest extends TestCase {
assertEquals(0, map.getNumOverflowEntries());
assertEquals(3, map.size());
- assertEquals(new Integer(1), map.remove(0));
+ assertEquals(Integer.valueOf(1), map.remove(0));
assertEquals(2, map.getNumArrayEntries());
assertEquals(0, map.getNumOverflowEntries());
assertEquals(2, map.size());
@@ -216,16 +210,15 @@ public class SmallSortedMapTest extends TestCase {
assertEquals(3, map.getNumArrayEntries());
for (int i = 0; i < 3; i++) {
Map.Entry<Integer, Integer> entry = map.getArrayEntryAt(i);
- assertEquals(new Integer(i), entry.getKey());
- assertEquals(new Integer(i + 1), entry.getValue());
+ assertEquals(Integer.valueOf(i), entry.getKey());
+ assertEquals(Integer.valueOf(i + 1), entry.getValue());
}
- Iterator<Map.Entry<Integer, Integer>> it =
- map.getOverflowEntries().iterator();
+ Iterator<Map.Entry<Integer, Integer>> it = map.getOverflowEntries().iterator();
for (int i = 3; i < 6; i++) {
assertTrue(it.hasNext());
Map.Entry<Integer, Integer> entry = it.next();
- assertEquals(new Integer(i), entry.getKey());
- assertEquals(new Integer(i + 1), entry.getValue());
+ assertEquals(Integer.valueOf(i), entry.getKey());
+ assertEquals(Integer.valueOf(i + 1), entry.getValue());
}
assertFalse(it.hasNext());
}
@@ -237,10 +230,8 @@ public class SmallSortedMapTest extends TestCase {
}
Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet();
for (int i = 0; i < 6; i++) {
- assertTrue(
- entrySet.contains(new SimpleEntry<Integer, Integer>(i, i + 1)));
- assertFalse(
- entrySet.contains(new SimpleEntry<Integer, Integer>(i, i)));
+ assertTrue(entrySet.contains(new SimpleEntry<Integer, Integer>(i, i + 1)));
+ assertFalse(entrySet.contains(new SimpleEntry<Integer, Integer>(i, i)));
}
}
@@ -248,13 +239,12 @@ public class SmallSortedMapTest extends TestCase {
SmallSortedMap<Integer, Integer> map = SmallSortedMap.newInstanceForTest(3);
Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet();
for (int i = 0; i < 6; i++) {
- Map.Entry<Integer, Integer> entry =
- new SimpleEntry<Integer, Integer>(i, i + 1);
+ Map.Entry<Integer, Integer> entry = new SimpleEntry<Integer, Integer>(i, i + 1);
assertTrue(entrySet.add(entry));
assertFalse(entrySet.add(entry));
}
for (int i = 0; i < 6; i++) {
- assertEquals(new Integer(i + 1), map.get(i));
+ assertEquals(Integer.valueOf(i + 1), map.get(i));
}
assertEquals(3, map.getNumArrayEntries());
assertEquals(3, map.getNumOverflowEntries());
@@ -268,8 +258,7 @@ public class SmallSortedMapTest extends TestCase {
assertNull(map.put(i, i + 1));
}
for (int i = 0; i < 6; i++) {
- Map.Entry<Integer, Integer> entry =
- new SimpleEntry<Integer, Integer>(i, i + 1);
+ Map.Entry<Integer, Integer> entry = new SimpleEntry<Integer, Integer>(i, i + 1);
assertTrue(entrySet.remove(entry));
assertFalse(entrySet.remove(entry));
}
@@ -284,7 +273,7 @@ public class SmallSortedMapTest extends TestCase {
for (int i = 0; i < 6; i++) {
assertNull(map.put(i, i + 1));
}
- map.entrySet().clear();
+ map.clear();
assertTrue(map.isEmpty());
assertEquals(0, map.getNumArrayEntries());
assertEquals(0, map.getNumOverflowEntries());
@@ -300,8 +289,8 @@ public class SmallSortedMapTest extends TestCase {
for (int i = 0; i < 6; i++) {
assertTrue(it.hasNext());
Map.Entry<Integer, Integer> entry = it.next();
- assertEquals(new Integer(i), entry.getKey());
- assertEquals(new Integer(i + 1), entry.getValue());
+ assertEquals(Integer.valueOf(i), entry.getKey());
+ assertEquals(Integer.valueOf(i + 1), entry.getValue());
}
assertFalse(it.hasNext());
}
@@ -332,7 +321,7 @@ public class SmallSortedMapTest extends TestCase {
entry.setValue(i + 23);
}
for (int i = 0; i < 6; i++) {
- assertEquals(new Integer(i + 23), map.get(i));
+ assertEquals(Integer.valueOf(i + 23), map.get(i));
}
}
@@ -342,7 +331,7 @@ public class SmallSortedMapTest extends TestCase {
assertNull(map.put(i, i + 1));
}
map.makeImmutable();
- assertEquals(new Integer(1), map.get(0));
+ assertEquals(Integer.valueOf(1), map.get(0));
assertEquals(6, map.size());
try {
diff --git a/java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java b/java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java
index 4af55429..3d82c5f9 100644
--- a/java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java
+++ b/java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java
@@ -33,9 +33,9 @@ package com.google.protobuf;
import junit.framework.TestCase;
/**
- * Tests that proto2 api generation doesn't cause compile errors when
- * compiling protocol buffers that have names that would otherwise conflict
- * if not fully qualified (like @Deprecated and @Override).
+ * Tests that proto2 api generation doesn't cause compile errors when compiling protocol buffers
+ * that have names that would otherwise conflict if not fully qualified (like @Deprecated
+ * and @Override).
*
* @author jonp@google.com (Jon Perlow)
*/
@@ -48,17 +48,11 @@ public class TestBadIdentifiers extends TestCase {
}
public void testGetDescriptor() {
- Descriptors.FileDescriptor fileDescriptor =
- TestBadIdentifiersProto.getDescriptor();
- String descriptorField = TestBadIdentifiersProto.Descriptor
- .getDefaultInstance().getDescriptor();
- Descriptors.Descriptor protoDescriptor = TestBadIdentifiersProto.Descriptor
- .getDefaultInstance().getDescriptorForType();
- String nestedDescriptorField = TestBadIdentifiersProto.Descriptor
- .NestedDescriptor.getDefaultInstance().getDescriptor();
- Descriptors.Descriptor nestedProtoDescriptor = TestBadIdentifiersProto
- .Descriptor.NestedDescriptor.getDefaultInstance()
- .getDescriptorForType();
+ TestBadIdentifiersProto.getDescriptor();
+ TestBadIdentifiersProto.Descriptor.getDefaultInstance().getDescriptor();
+ TestBadIdentifiersProto.Descriptor.getDefaultInstance().getDescriptorForType();
+ TestBadIdentifiersProto.Descriptor.NestedDescriptor.getDefaultInstance().getDescriptor();
+ TestBadIdentifiersProto.Descriptor.NestedDescriptor.getDefaultInstance().getDescriptorForType();
}
public void testConflictingFieldNames() throws Exception {
@@ -87,10 +81,16 @@ public class TestBadIdentifiers extends TestCase {
assertEquals(0, message.getInt32FieldList31());
assertEquals(0, message.getInt64FieldCount());
- assertEquals(0L, message.getExtension(
- TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldCount).longValue());
- assertEquals(0L, message.getExtension(
- TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldList).longValue());
+ assertEquals(
+ 0L,
+ message
+ .getExtension(TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldCount)
+ .longValue());
+ assertEquals(
+ 0L,
+ message
+ .getExtension(TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldList)
+ .longValue());
assertEquals("", message.getFieldName32());
assertEquals("", message.getFieldName33());
diff --git a/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java b/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java
index 37f94c03..798d7ca6 100644
--- a/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java
+++ b/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java
@@ -75,9 +75,15 @@ public final class TestBadIdentifiersLite extends TestCase {
assertEquals(0, message.getInt32FieldList31());
assertEquals(0, message.getInt64FieldCount());
- assertEquals(0L, message.getExtension(
- TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldCount).longValue());
- assertEquals(0L, message.getExtension(
- TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldList).longValue());
+ assertEquals(
+ 0L,
+ message
+ .getExtension(TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldCount)
+ .longValue());
+ assertEquals(
+ 0L,
+ message
+ .getExtension(TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldList)
+ .longValue());
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/TestUtil.java b/java/core/src/test/java/com/google/protobuf/TestUtil.java
index 8ec22d3f..48ee9574 100644
--- a/java/core/src/test/java/com/google/protobuf/TestUtil.java
+++ b/java/core/src/test/java/com/google/protobuf/TestUtil.java
@@ -237,14 +237,12 @@ import java.io.RandomAccessFile;
import junit.framework.Assert;
/**
- * Contains methods for setting all fields of {@code TestAllTypes} to
- * some values as well as checking that all the fields are set to those values.
- * These are useful for testing various protocol message features, e.g.
- * set all fields of a message, serialize it, parse it, and check that all
- * fields are set.
+ * Contains methods for setting all fields of {@code TestAllTypes} to some values as well as
+ * checking that all the fields are set to those values. These are useful for testing various
+ * protocol message features, e.g. set all fields of a message, serialize it, parse it, and check
+ * that all fields are set.
*
- * <p>This code is not to be used outside of {@code com.google.protobuf} and
- * subpackages.
+ * <p>This code is not to be used outside of {@code com.google.protobuf} and subpackages.
*
* @author kenton@google.com Kenton Varda
*/
@@ -262,17 +260,15 @@ public final class TestUtil {
}
// BEGIN FULL-RUNTIME
- /**
- * Dirties the message by resetting the momoized serialized size.
- */
+ /** Dirties the message by resetting the momoized serialized size. */
public static void resetMemoizedSize(AbstractMessage message) {
message.memoizedSize = -1;
}
// END FULL-RUNTIME
/**
- * Get a {@code TestAllTypes} with all fields set as they would be by
- * {@link #setAllFields(TestAllTypes.Builder)}.
+ * Get a {@code TestAllTypes} with all fields set as they would be by {@link
+ * #setAllFields(TestAllTypes.Builder)}.
*/
public static TestAllTypes getAllSet() {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
@@ -281,8 +277,8 @@ public final class TestUtil {
}
/**
- * Get a {@code TestAllTypes.Builder} with all fields set as they would be by
- * {@link #setAllFields(TestAllTypes.Builder)}.
+ * Get a {@code TestAllTypes.Builder} with all fields set as they would be by {@link
+ * #setAllFields(TestAllTypes.Builder)}.
*/
public static TestAllTypes.Builder getAllSetBuilder() {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
@@ -291,8 +287,8 @@ public final class TestUtil {
}
/**
- * Get a {@code TestAllExtensions} with all fields set as they would be by
- * {@link #setAllExtensions(TestAllExtensions.Builder)}.
+ * Get a {@code TestAllExtensions} with all fields set as they would be by {@link
+ * #setAllExtensions(TestAllExtensions.Builder)}.
*/
public static TestAllExtensions getAllExtensionsSet() {
TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
@@ -318,146 +314,126 @@ public final class TestUtil {
return builder.build();
}
- /**
- * Set every field of {@code message} to the values expected by
- * {@code assertAllFieldsSet()}.
- */
+ /** Set every field of {@code message} to the values expected by {@code assertAllFieldsSet()}. */
public static void setAllFields(TestAllTypes.Builder message) {
- message.setOptionalInt32 (101);
- message.setOptionalInt64 (102);
- message.setOptionalUint32 (103);
- message.setOptionalUint64 (104);
- message.setOptionalSint32 (105);
- message.setOptionalSint64 (106);
- message.setOptionalFixed32 (107);
- message.setOptionalFixed64 (108);
+ message.setOptionalInt32(101);
+ message.setOptionalInt64(102);
+ message.setOptionalUint32(103);
+ message.setOptionalUint64(104);
+ message.setOptionalSint32(105);
+ message.setOptionalSint64(106);
+ message.setOptionalFixed32(107);
+ message.setOptionalFixed64(108);
message.setOptionalSfixed32(109);
message.setOptionalSfixed64(110);
- message.setOptionalFloat (111);
- message.setOptionalDouble (112);
- message.setOptionalBool (true);
- message.setOptionalString ("115");
- message.setOptionalBytes (toBytes("116"));
-
- message.setOptionalGroup(
- TestAllTypes.OptionalGroup.newBuilder().setA(117).build());
- message.setOptionalNestedMessage(
- TestAllTypes.NestedMessage.newBuilder().setBb(118).build());
- message.setOptionalForeignMessage(
- ForeignMessage.newBuilder().setC(119).build());
- message.setOptionalImportMessage(
- ImportMessage.newBuilder().setD(120).build());
- message.setOptionalPublicImportMessage(
- PublicImportMessage.newBuilder().setE(126).build());
- message.setOptionalLazyMessage(
- TestAllTypes.NestedMessage.newBuilder().setBb(127).build());
-
- message.setOptionalNestedEnum (TestAllTypes.NestedEnum.BAZ);
+ message.setOptionalFloat(111);
+ message.setOptionalDouble(112);
+ message.setOptionalBool(true);
+ message.setOptionalString("115");
+ message.setOptionalBytes(toBytes("116"));
+
+ message.setOptionalGroup(TestAllTypes.OptionalGroup.newBuilder().setA(117).build());
+ message.setOptionalNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(118).build());
+ message.setOptionalForeignMessage(ForeignMessage.newBuilder().setC(119).build());
+ message.setOptionalImportMessage(ImportMessage.newBuilder().setD(120).build());
+ message.setOptionalPublicImportMessage(PublicImportMessage.newBuilder().setE(126).build());
+ message.setOptionalLazyMessage(TestAllTypes.NestedMessage.newBuilder().setBb(127).build());
+
+ message.setOptionalNestedEnum(TestAllTypes.NestedEnum.BAZ);
message.setOptionalForeignEnum(ForeignEnum.FOREIGN_BAZ);
- message.setOptionalImportEnum (ImportEnum.IMPORT_BAZ);
+ message.setOptionalImportEnum(ImportEnum.IMPORT_BAZ);
message.setOptionalStringPiece("124");
message.setOptionalCord("125");
// -----------------------------------------------------------------
- message.addRepeatedInt32 (201);
- message.addRepeatedInt64 (202);
- message.addRepeatedUint32 (203);
- message.addRepeatedUint64 (204);
- message.addRepeatedSint32 (205);
- message.addRepeatedSint64 (206);
- message.addRepeatedFixed32 (207);
- message.addRepeatedFixed64 (208);
+ message.addRepeatedInt32(201);
+ message.addRepeatedInt64(202);
+ message.addRepeatedUint32(203);
+ message.addRepeatedUint64(204);
+ message.addRepeatedSint32(205);
+ message.addRepeatedSint64(206);
+ message.addRepeatedFixed32(207);
+ message.addRepeatedFixed64(208);
message.addRepeatedSfixed32(209);
message.addRepeatedSfixed64(210);
- message.addRepeatedFloat (211);
- message.addRepeatedDouble (212);
- message.addRepeatedBool (true);
- message.addRepeatedString ("215");
- message.addRepeatedBytes (toBytes("216"));
-
- message.addRepeatedGroup(
- TestAllTypes.RepeatedGroup.newBuilder().setA(217).build());
- message.addRepeatedNestedMessage(
- TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
- message.addRepeatedForeignMessage(
- ForeignMessage.newBuilder().setC(219).build());
- message.addRepeatedImportMessage(
- ImportMessage.newBuilder().setD(220).build());
- message.addRepeatedLazyMessage(
- TestAllTypes.NestedMessage.newBuilder().setBb(227).build());
-
- message.addRepeatedNestedEnum (TestAllTypes.NestedEnum.BAR);
+ message.addRepeatedFloat(211);
+ message.addRepeatedDouble(212);
+ message.addRepeatedBool(true);
+ message.addRepeatedString("215");
+ message.addRepeatedBytes(toBytes("216"));
+
+ message.addRepeatedGroup(TestAllTypes.RepeatedGroup.newBuilder().setA(217).build());
+ message.addRepeatedNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
+ message.addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(219).build());
+ message.addRepeatedImportMessage(ImportMessage.newBuilder().setD(220).build());
+ message.addRepeatedLazyMessage(TestAllTypes.NestedMessage.newBuilder().setBb(227).build());
+
+ message.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAR);
message.addRepeatedForeignEnum(ForeignEnum.FOREIGN_BAR);
- message.addRepeatedImportEnum (ImportEnum.IMPORT_BAR);
+ message.addRepeatedImportEnum(ImportEnum.IMPORT_BAR);
message.addRepeatedStringPiece("224");
message.addRepeatedCord("225");
// Add a second one of each field.
- message.addRepeatedInt32 (301);
- message.addRepeatedInt64 (302);
- message.addRepeatedUint32 (303);
- message.addRepeatedUint64 (304);
- message.addRepeatedSint32 (305);
- message.addRepeatedSint64 (306);
- message.addRepeatedFixed32 (307);
- message.addRepeatedFixed64 (308);
+ message.addRepeatedInt32(301);
+ message.addRepeatedInt64(302);
+ message.addRepeatedUint32(303);
+ message.addRepeatedUint64(304);
+ message.addRepeatedSint32(305);
+ message.addRepeatedSint64(306);
+ message.addRepeatedFixed32(307);
+ message.addRepeatedFixed64(308);
message.addRepeatedSfixed32(309);
message.addRepeatedSfixed64(310);
- message.addRepeatedFloat (311);
- message.addRepeatedDouble (312);
- message.addRepeatedBool (false);
- message.addRepeatedString ("315");
- message.addRepeatedBytes (toBytes("316"));
-
- message.addRepeatedGroup(
- TestAllTypes.RepeatedGroup.newBuilder().setA(317).build());
- message.addRepeatedNestedMessage(
- TestAllTypes.NestedMessage.newBuilder().setBb(318).build());
- message.addRepeatedForeignMessage(
- ForeignMessage.newBuilder().setC(319).build());
- message.addRepeatedImportMessage(
- ImportMessage.newBuilder().setD(320).build());
- message.addRepeatedLazyMessage(
- TestAllTypes.NestedMessage.newBuilder().setBb(327).build());
-
- message.addRepeatedNestedEnum (TestAllTypes.NestedEnum.BAZ);
+ message.addRepeatedFloat(311);
+ message.addRepeatedDouble(312);
+ message.addRepeatedBool(false);
+ message.addRepeatedString("315");
+ message.addRepeatedBytes(toBytes("316"));
+
+ message.addRepeatedGroup(TestAllTypes.RepeatedGroup.newBuilder().setA(317).build());
+ message.addRepeatedNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(318).build());
+ message.addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(319).build());
+ message.addRepeatedImportMessage(ImportMessage.newBuilder().setD(320).build());
+ message.addRepeatedLazyMessage(TestAllTypes.NestedMessage.newBuilder().setBb(327).build());
+
+ message.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAZ);
message.addRepeatedForeignEnum(ForeignEnum.FOREIGN_BAZ);
- message.addRepeatedImportEnum (ImportEnum.IMPORT_BAZ);
+ message.addRepeatedImportEnum(ImportEnum.IMPORT_BAZ);
message.addRepeatedStringPiece("324");
message.addRepeatedCord("325");
// -----------------------------------------------------------------
- message.setDefaultInt32 (401);
- message.setDefaultInt64 (402);
- message.setDefaultUint32 (403);
- message.setDefaultUint64 (404);
- message.setDefaultSint32 (405);
- message.setDefaultSint64 (406);
- message.setDefaultFixed32 (407);
- message.setDefaultFixed64 (408);
+ message.setDefaultInt32(401);
+ message.setDefaultInt64(402);
+ message.setDefaultUint32(403);
+ message.setDefaultUint64(404);
+ message.setDefaultSint32(405);
+ message.setDefaultSint64(406);
+ message.setDefaultFixed32(407);
+ message.setDefaultFixed64(408);
message.setDefaultSfixed32(409);
message.setDefaultSfixed64(410);
- message.setDefaultFloat (411);
- message.setDefaultDouble (412);
- message.setDefaultBool (false);
- message.setDefaultString ("415");
- message.setDefaultBytes (toBytes("416"));
+ message.setDefaultFloat(411);
+ message.setDefaultDouble(412);
+ message.setDefaultBool(false);
+ message.setDefaultString("415");
+ message.setDefaultBytes(toBytes("416"));
- message.setDefaultNestedEnum (TestAllTypes.NestedEnum.FOO);
+ message.setDefaultNestedEnum(TestAllTypes.NestedEnum.FOO);
message.setDefaultForeignEnum(ForeignEnum.FOREIGN_FOO);
- message.setDefaultImportEnum (ImportEnum.IMPORT_FOO);
+ message.setDefaultImportEnum(ImportEnum.IMPORT_FOO);
message.setDefaultStringPiece("424");
message.setDefaultCord("425");
message.setOneofUint32(601);
- message.setOneofNestedMessage(
- TestAllTypes.NestedMessage.newBuilder().setBb(602).build());
+ message.setOneofNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(602).build());
message.setOneofString("603");
message.setOneofBytes(toBytes("604"));
}
@@ -465,40 +441,35 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Modify the repeated fields of {@code message} to contain the values
- * expected by {@code assertRepeatedFieldsModified()}.
+ * Modify the repeated fields of {@code message} to contain the values expected by {@code
+ * assertRepeatedFieldsModified()}.
*/
public static void modifyRepeatedFields(TestAllTypes.Builder message) {
- message.setRepeatedInt32 (1, 501);
- message.setRepeatedInt64 (1, 502);
- message.setRepeatedUint32 (1, 503);
- message.setRepeatedUint64 (1, 504);
- message.setRepeatedSint32 (1, 505);
- message.setRepeatedSint64 (1, 506);
- message.setRepeatedFixed32 (1, 507);
- message.setRepeatedFixed64 (1, 508);
+ message.setRepeatedInt32(1, 501);
+ message.setRepeatedInt64(1, 502);
+ message.setRepeatedUint32(1, 503);
+ message.setRepeatedUint64(1, 504);
+ message.setRepeatedSint32(1, 505);
+ message.setRepeatedSint64(1, 506);
+ message.setRepeatedFixed32(1, 507);
+ message.setRepeatedFixed64(1, 508);
message.setRepeatedSfixed32(1, 509);
message.setRepeatedSfixed64(1, 510);
- message.setRepeatedFloat (1, 511);
- message.setRepeatedDouble (1, 512);
- message.setRepeatedBool (1, true);
- message.setRepeatedString (1, "515");
- message.setRepeatedBytes (1, toBytes("516"));
-
- message.setRepeatedGroup(1,
- TestAllTypes.RepeatedGroup.newBuilder().setA(517).build());
- message.setRepeatedNestedMessage(1,
- TestAllTypes.NestedMessage.newBuilder().setBb(518).build());
- message.setRepeatedForeignMessage(1,
- ForeignMessage.newBuilder().setC(519).build());
- message.setRepeatedImportMessage(1,
- ImportMessage.newBuilder().setD(520).build());
- message.setRepeatedLazyMessage(1,
- TestAllTypes.NestedMessage.newBuilder().setBb(527).build());
-
- message.setRepeatedNestedEnum (1, TestAllTypes.NestedEnum.FOO);
+ message.setRepeatedFloat(1, 511);
+ message.setRepeatedDouble(1, 512);
+ message.setRepeatedBool(1, true);
+ message.setRepeatedString(1, "515");
+ message.setRepeatedBytes(1, toBytes("516"));
+
+ message.setRepeatedGroup(1, TestAllTypes.RepeatedGroup.newBuilder().setA(517).build());
+ message.setRepeatedNestedMessage(1, TestAllTypes.NestedMessage.newBuilder().setBb(518).build());
+ message.setRepeatedForeignMessage(1, ForeignMessage.newBuilder().setC(519).build());
+ message.setRepeatedImportMessage(1, ImportMessage.newBuilder().setD(520).build());
+ message.setRepeatedLazyMessage(1, TestAllTypes.NestedMessage.newBuilder().setBb(527).build());
+
+ message.setRepeatedNestedEnum(1, TestAllTypes.NestedEnum.FOO);
message.setRepeatedForeignEnum(1, ForeignEnum.FOREIGN_FOO);
- message.setRepeatedImportEnum (1, ImportEnum.IMPORT_FOO);
+ message.setRepeatedImportEnum(1, ImportEnum.IMPORT_FOO);
message.setRepeatedStringPiece(1, "524");
message.setRepeatedCord(1, "525");
@@ -507,65 +478,65 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all fields of
- * {@code message} are set to the values assigned by {@code setAllFields}.
+ * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to the
+ * values assigned by {@code setAllFields}.
*/
public static void assertAllFieldsSet(TestAllTypesOrBuilder message) {
- Assert.assertTrue(message.hasOptionalInt32 ());
- Assert.assertTrue(message.hasOptionalInt64 ());
- Assert.assertTrue(message.hasOptionalUint32 ());
- Assert.assertTrue(message.hasOptionalUint64 ());
- Assert.assertTrue(message.hasOptionalSint32 ());
- Assert.assertTrue(message.hasOptionalSint64 ());
- Assert.assertTrue(message.hasOptionalFixed32 ());
- Assert.assertTrue(message.hasOptionalFixed64 ());
+ Assert.assertTrue(message.hasOptionalInt32());
+ Assert.assertTrue(message.hasOptionalInt64());
+ Assert.assertTrue(message.hasOptionalUint32());
+ Assert.assertTrue(message.hasOptionalUint64());
+ Assert.assertTrue(message.hasOptionalSint32());
+ Assert.assertTrue(message.hasOptionalSint64());
+ Assert.assertTrue(message.hasOptionalFixed32());
+ Assert.assertTrue(message.hasOptionalFixed64());
Assert.assertTrue(message.hasOptionalSfixed32());
Assert.assertTrue(message.hasOptionalSfixed64());
- Assert.assertTrue(message.hasOptionalFloat ());
- Assert.assertTrue(message.hasOptionalDouble ());
- Assert.assertTrue(message.hasOptionalBool ());
- Assert.assertTrue(message.hasOptionalString ());
- Assert.assertTrue(message.hasOptionalBytes ());
-
- Assert.assertTrue(message.hasOptionalGroup ());
- Assert.assertTrue(message.hasOptionalNestedMessage ());
+ Assert.assertTrue(message.hasOptionalFloat());
+ Assert.assertTrue(message.hasOptionalDouble());
+ Assert.assertTrue(message.hasOptionalBool());
+ Assert.assertTrue(message.hasOptionalString());
+ Assert.assertTrue(message.hasOptionalBytes());
+
+ Assert.assertTrue(message.hasOptionalGroup());
+ Assert.assertTrue(message.hasOptionalNestedMessage());
Assert.assertTrue(message.hasOptionalForeignMessage());
- Assert.assertTrue(message.hasOptionalImportMessage ());
+ Assert.assertTrue(message.hasOptionalImportMessage());
- Assert.assertTrue(message.getOptionalGroup ().hasA());
- Assert.assertTrue(message.getOptionalNestedMessage ().hasBb());
+ Assert.assertTrue(message.getOptionalGroup().hasA());
+ Assert.assertTrue(message.getOptionalNestedMessage().hasBb());
Assert.assertTrue(message.getOptionalForeignMessage().hasC());
- Assert.assertTrue(message.getOptionalImportMessage ().hasD());
+ Assert.assertTrue(message.getOptionalImportMessage().hasD());
- Assert.assertTrue(message.hasOptionalNestedEnum ());
+ Assert.assertTrue(message.hasOptionalNestedEnum());
Assert.assertTrue(message.hasOptionalForeignEnum());
- Assert.assertTrue(message.hasOptionalImportEnum ());
+ Assert.assertTrue(message.hasOptionalImportEnum());
Assert.assertTrue(message.hasOptionalStringPiece());
Assert.assertTrue(message.hasOptionalCord());
- Assert.assertEquals(101 , message.getOptionalInt32 ());
- Assert.assertEquals(102 , message.getOptionalInt64 ());
- Assert.assertEquals(103 , message.getOptionalUint32 ());
- Assert.assertEquals(104 , message.getOptionalUint64 ());
- Assert.assertEquals(105 , message.getOptionalSint32 ());
- Assert.assertEquals(106 , message.getOptionalSint64 ());
- Assert.assertEquals(107 , message.getOptionalFixed32 ());
- Assert.assertEquals(108 , message.getOptionalFixed64 ());
- Assert.assertEquals(109 , message.getOptionalSfixed32());
- Assert.assertEquals(110 , message.getOptionalSfixed64());
- Assert.assertEquals(111 , message.getOptionalFloat (), 0.0);
- Assert.assertEquals(112 , message.getOptionalDouble (), 0.0);
- Assert.assertEquals(true , message.getOptionalBool ());
- Assert.assertEquals("115", message.getOptionalString ());
+ Assert.assertEquals(101, message.getOptionalInt32());
+ Assert.assertEquals(102, message.getOptionalInt64());
+ Assert.assertEquals(103, message.getOptionalUint32());
+ Assert.assertEquals(104, message.getOptionalUint64());
+ Assert.assertEquals(105, message.getOptionalSint32());
+ Assert.assertEquals(106, message.getOptionalSint64());
+ Assert.assertEquals(107, message.getOptionalFixed32());
+ Assert.assertEquals(108, message.getOptionalFixed64());
+ Assert.assertEquals(109, message.getOptionalSfixed32());
+ Assert.assertEquals(110, message.getOptionalSfixed64());
+ Assert.assertEquals(111, message.getOptionalFloat(), 0.0);
+ Assert.assertEquals(112, message.getOptionalDouble(), 0.0);
+ Assert.assertEquals(true, message.getOptionalBool());
+ Assert.assertEquals("115", message.getOptionalString());
Assert.assertEquals(toBytes("116"), message.getOptionalBytes());
- Assert.assertEquals(117, message.getOptionalGroup ().getA());
- Assert.assertEquals(118, message.getOptionalNestedMessage ().getBb());
- Assert.assertEquals(119, message.getOptionalForeignMessage ().getC());
- Assert.assertEquals(120, message.getOptionalImportMessage ().getD());
+ Assert.assertEquals(117, message.getOptionalGroup().getA());
+ Assert.assertEquals(118, message.getOptionalNestedMessage().getBb());
+ Assert.assertEquals(119, message.getOptionalForeignMessage().getC());
+ Assert.assertEquals(120, message.getOptionalImportMessage().getD());
Assert.assertEquals(126, message.getOptionalPublicImportMessage().getE());
- Assert.assertEquals(127, message.getOptionalLazyMessage ().getBb());
+ Assert.assertEquals(127, message.getOptionalLazyMessage().getBb());
Assert.assertEquals(TestAllTypes.NestedEnum.BAZ, message.getOptionalNestedEnum());
Assert.assertEquals(ForeignEnum.FOREIGN_BAZ, message.getOptionalForeignEnum());
@@ -576,86 +547,86 @@ public final class TestUtil {
// -----------------------------------------------------------------
- Assert.assertEquals(2, message.getRepeatedInt32Count ());
- Assert.assertEquals(2, message.getRepeatedInt64Count ());
- Assert.assertEquals(2, message.getRepeatedUint32Count ());
- Assert.assertEquals(2, message.getRepeatedUint64Count ());
- Assert.assertEquals(2, message.getRepeatedSint32Count ());
- Assert.assertEquals(2, message.getRepeatedSint64Count ());
- Assert.assertEquals(2, message.getRepeatedFixed32Count ());
- Assert.assertEquals(2, message.getRepeatedFixed64Count ());
+ Assert.assertEquals(2, message.getRepeatedInt32Count());
+ Assert.assertEquals(2, message.getRepeatedInt64Count());
+ Assert.assertEquals(2, message.getRepeatedUint32Count());
+ Assert.assertEquals(2, message.getRepeatedUint64Count());
+ Assert.assertEquals(2, message.getRepeatedSint32Count());
+ Assert.assertEquals(2, message.getRepeatedSint64Count());
+ Assert.assertEquals(2, message.getRepeatedFixed32Count());
+ Assert.assertEquals(2, message.getRepeatedFixed64Count());
Assert.assertEquals(2, message.getRepeatedSfixed32Count());
Assert.assertEquals(2, message.getRepeatedSfixed64Count());
- Assert.assertEquals(2, message.getRepeatedFloatCount ());
- Assert.assertEquals(2, message.getRepeatedDoubleCount ());
- Assert.assertEquals(2, message.getRepeatedBoolCount ());
- Assert.assertEquals(2, message.getRepeatedStringCount ());
- Assert.assertEquals(2, message.getRepeatedBytesCount ());
-
- Assert.assertEquals(2, message.getRepeatedGroupCount ());
- Assert.assertEquals(2, message.getRepeatedNestedMessageCount ());
+ Assert.assertEquals(2, message.getRepeatedFloatCount());
+ Assert.assertEquals(2, message.getRepeatedDoubleCount());
+ Assert.assertEquals(2, message.getRepeatedBoolCount());
+ Assert.assertEquals(2, message.getRepeatedStringCount());
+ Assert.assertEquals(2, message.getRepeatedBytesCount());
+
+ Assert.assertEquals(2, message.getRepeatedGroupCount());
+ Assert.assertEquals(2, message.getRepeatedNestedMessageCount());
Assert.assertEquals(2, message.getRepeatedForeignMessageCount());
- Assert.assertEquals(2, message.getRepeatedImportMessageCount ());
- Assert.assertEquals(2, message.getRepeatedLazyMessageCount ());
- Assert.assertEquals(2, message.getRepeatedNestedEnumCount ());
- Assert.assertEquals(2, message.getRepeatedForeignEnumCount ());
- Assert.assertEquals(2, message.getRepeatedImportEnumCount ());
+ Assert.assertEquals(2, message.getRepeatedImportMessageCount());
+ Assert.assertEquals(2, message.getRepeatedLazyMessageCount());
+ Assert.assertEquals(2, message.getRepeatedNestedEnumCount());
+ Assert.assertEquals(2, message.getRepeatedForeignEnumCount());
+ Assert.assertEquals(2, message.getRepeatedImportEnumCount());
Assert.assertEquals(2, message.getRepeatedStringPieceCount());
Assert.assertEquals(2, message.getRepeatedCordCount());
- Assert.assertEquals(201 , message.getRepeatedInt32 (0));
- Assert.assertEquals(202 , message.getRepeatedInt64 (0));
- Assert.assertEquals(203 , message.getRepeatedUint32 (0));
- Assert.assertEquals(204 , message.getRepeatedUint64 (0));
- Assert.assertEquals(205 , message.getRepeatedSint32 (0));
- Assert.assertEquals(206 , message.getRepeatedSint64 (0));
- Assert.assertEquals(207 , message.getRepeatedFixed32 (0));
- Assert.assertEquals(208 , message.getRepeatedFixed64 (0));
- Assert.assertEquals(209 , message.getRepeatedSfixed32(0));
- Assert.assertEquals(210 , message.getRepeatedSfixed64(0));
- Assert.assertEquals(211 , message.getRepeatedFloat (0), 0.0);
- Assert.assertEquals(212 , message.getRepeatedDouble (0), 0.0);
- Assert.assertEquals(true , message.getRepeatedBool (0));
- Assert.assertEquals("215", message.getRepeatedString (0));
+ Assert.assertEquals(201, message.getRepeatedInt32(0));
+ Assert.assertEquals(202, message.getRepeatedInt64(0));
+ Assert.assertEquals(203, message.getRepeatedUint32(0));
+ Assert.assertEquals(204, message.getRepeatedUint64(0));
+ Assert.assertEquals(205, message.getRepeatedSint32(0));
+ Assert.assertEquals(206, message.getRepeatedSint64(0));
+ Assert.assertEquals(207, message.getRepeatedFixed32(0));
+ Assert.assertEquals(208, message.getRepeatedFixed64(0));
+ Assert.assertEquals(209, message.getRepeatedSfixed32(0));
+ Assert.assertEquals(210, message.getRepeatedSfixed64(0));
+ Assert.assertEquals(211, message.getRepeatedFloat(0), 0.0);
+ Assert.assertEquals(212, message.getRepeatedDouble(0), 0.0);
+ Assert.assertEquals(true, message.getRepeatedBool(0));
+ Assert.assertEquals("215", message.getRepeatedString(0));
Assert.assertEquals(toBytes("216"), message.getRepeatedBytes(0));
- Assert.assertEquals(217, message.getRepeatedGroup (0).getA());
- Assert.assertEquals(218, message.getRepeatedNestedMessage (0).getBb());
+ Assert.assertEquals(217, message.getRepeatedGroup(0).getA());
+ Assert.assertEquals(218, message.getRepeatedNestedMessage(0).getBb());
Assert.assertEquals(219, message.getRepeatedForeignMessage(0).getC());
- Assert.assertEquals(220, message.getRepeatedImportMessage (0).getD());
- Assert.assertEquals(227, message.getRepeatedLazyMessage (0).getBb());
+ Assert.assertEquals(220, message.getRepeatedImportMessage(0).getD());
+ Assert.assertEquals(227, message.getRepeatedLazyMessage(0).getBb());
- Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getRepeatedNestedEnum (0));
+ Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getRepeatedNestedEnum(0));
Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getRepeatedForeignEnum(0));
Assert.assertEquals(ImportEnum.IMPORT_BAR, message.getRepeatedImportEnum(0));
Assert.assertEquals("224", message.getRepeatedStringPiece(0));
Assert.assertEquals("225", message.getRepeatedCord(0));
- Assert.assertEquals(301 , message.getRepeatedInt32 (1));
- Assert.assertEquals(302 , message.getRepeatedInt64 (1));
- Assert.assertEquals(303 , message.getRepeatedUint32 (1));
- Assert.assertEquals(304 , message.getRepeatedUint64 (1));
- Assert.assertEquals(305 , message.getRepeatedSint32 (1));
- Assert.assertEquals(306 , message.getRepeatedSint64 (1));
- Assert.assertEquals(307 , message.getRepeatedFixed32 (1));
- Assert.assertEquals(308 , message.getRepeatedFixed64 (1));
- Assert.assertEquals(309 , message.getRepeatedSfixed32(1));
- Assert.assertEquals(310 , message.getRepeatedSfixed64(1));
- Assert.assertEquals(311 , message.getRepeatedFloat (1), 0.0);
- Assert.assertEquals(312 , message.getRepeatedDouble (1), 0.0);
- Assert.assertEquals(false, message.getRepeatedBool (1));
- Assert.assertEquals("315", message.getRepeatedString (1));
+ Assert.assertEquals(301, message.getRepeatedInt32(1));
+ Assert.assertEquals(302, message.getRepeatedInt64(1));
+ Assert.assertEquals(303, message.getRepeatedUint32(1));
+ Assert.assertEquals(304, message.getRepeatedUint64(1));
+ Assert.assertEquals(305, message.getRepeatedSint32(1));
+ Assert.assertEquals(306, message.getRepeatedSint64(1));
+ Assert.assertEquals(307, message.getRepeatedFixed32(1));
+ Assert.assertEquals(308, message.getRepeatedFixed64(1));
+ Assert.assertEquals(309, message.getRepeatedSfixed32(1));
+ Assert.assertEquals(310, message.getRepeatedSfixed64(1));
+ Assert.assertEquals(311, message.getRepeatedFloat(1), 0.0);
+ Assert.assertEquals(312, message.getRepeatedDouble(1), 0.0);
+ Assert.assertEquals(false, message.getRepeatedBool(1));
+ Assert.assertEquals("315", message.getRepeatedString(1));
Assert.assertEquals(toBytes("316"), message.getRepeatedBytes(1));
- Assert.assertEquals(317, message.getRepeatedGroup (1).getA());
- Assert.assertEquals(318, message.getRepeatedNestedMessage (1).getBb());
+ Assert.assertEquals(317, message.getRepeatedGroup(1).getA());
+ Assert.assertEquals(318, message.getRepeatedNestedMessage(1).getBb());
Assert.assertEquals(319, message.getRepeatedForeignMessage(1).getC());
- Assert.assertEquals(320, message.getRepeatedImportMessage (1).getD());
- Assert.assertEquals(327, message.getRepeatedLazyMessage (1).getBb());
+ Assert.assertEquals(320, message.getRepeatedImportMessage(1).getD());
+ Assert.assertEquals(327, message.getRepeatedLazyMessage(1).getBb());
- Assert.assertEquals(TestAllTypes.NestedEnum.BAZ, message.getRepeatedNestedEnum (1));
+ Assert.assertEquals(TestAllTypes.NestedEnum.BAZ, message.getRepeatedNestedEnum(1));
Assert.assertEquals(ForeignEnum.FOREIGN_BAZ, message.getRepeatedForeignEnum(1));
Assert.assertEquals(ImportEnum.IMPORT_BAZ, message.getRepeatedImportEnum(1));
@@ -664,46 +635,46 @@ public final class TestUtil {
// -----------------------------------------------------------------
- Assert.assertTrue(message.hasDefaultInt32 ());
- Assert.assertTrue(message.hasDefaultInt64 ());
- Assert.assertTrue(message.hasDefaultUint32 ());
- Assert.assertTrue(message.hasDefaultUint64 ());
- Assert.assertTrue(message.hasDefaultSint32 ());
- Assert.assertTrue(message.hasDefaultSint64 ());
- Assert.assertTrue(message.hasDefaultFixed32 ());
- Assert.assertTrue(message.hasDefaultFixed64 ());
+ Assert.assertTrue(message.hasDefaultInt32());
+ Assert.assertTrue(message.hasDefaultInt64());
+ Assert.assertTrue(message.hasDefaultUint32());
+ Assert.assertTrue(message.hasDefaultUint64());
+ Assert.assertTrue(message.hasDefaultSint32());
+ Assert.assertTrue(message.hasDefaultSint64());
+ Assert.assertTrue(message.hasDefaultFixed32());
+ Assert.assertTrue(message.hasDefaultFixed64());
Assert.assertTrue(message.hasDefaultSfixed32());
Assert.assertTrue(message.hasDefaultSfixed64());
- Assert.assertTrue(message.hasDefaultFloat ());
- Assert.assertTrue(message.hasDefaultDouble ());
- Assert.assertTrue(message.hasDefaultBool ());
- Assert.assertTrue(message.hasDefaultString ());
- Assert.assertTrue(message.hasDefaultBytes ());
+ Assert.assertTrue(message.hasDefaultFloat());
+ Assert.assertTrue(message.hasDefaultDouble());
+ Assert.assertTrue(message.hasDefaultBool());
+ Assert.assertTrue(message.hasDefaultString());
+ Assert.assertTrue(message.hasDefaultBytes());
- Assert.assertTrue(message.hasDefaultNestedEnum ());
+ Assert.assertTrue(message.hasDefaultNestedEnum());
Assert.assertTrue(message.hasDefaultForeignEnum());
- Assert.assertTrue(message.hasDefaultImportEnum ());
+ Assert.assertTrue(message.hasDefaultImportEnum());
Assert.assertTrue(message.hasDefaultStringPiece());
Assert.assertTrue(message.hasDefaultCord());
- Assert.assertEquals(401 , message.getDefaultInt32 ());
- Assert.assertEquals(402 , message.getDefaultInt64 ());
- Assert.assertEquals(403 , message.getDefaultUint32 ());
- Assert.assertEquals(404 , message.getDefaultUint64 ());
- Assert.assertEquals(405 , message.getDefaultSint32 ());
- Assert.assertEquals(406 , message.getDefaultSint64 ());
- Assert.assertEquals(407 , message.getDefaultFixed32 ());
- Assert.assertEquals(408 , message.getDefaultFixed64 ());
- Assert.assertEquals(409 , message.getDefaultSfixed32());
- Assert.assertEquals(410 , message.getDefaultSfixed64());
- Assert.assertEquals(411 , message.getDefaultFloat (), 0.0);
- Assert.assertEquals(412 , message.getDefaultDouble (), 0.0);
- Assert.assertEquals(false, message.getDefaultBool ());
- Assert.assertEquals("415", message.getDefaultString ());
+ Assert.assertEquals(401, message.getDefaultInt32());
+ Assert.assertEquals(402, message.getDefaultInt64());
+ Assert.assertEquals(403, message.getDefaultUint32());
+ Assert.assertEquals(404, message.getDefaultUint64());
+ Assert.assertEquals(405, message.getDefaultSint32());
+ Assert.assertEquals(406, message.getDefaultSint64());
+ Assert.assertEquals(407, message.getDefaultFixed32());
+ Assert.assertEquals(408, message.getDefaultFixed64());
+ Assert.assertEquals(409, message.getDefaultSfixed32());
+ Assert.assertEquals(410, message.getDefaultSfixed64());
+ Assert.assertEquals(411, message.getDefaultFloat(), 0.0);
+ Assert.assertEquals(412, message.getDefaultDouble(), 0.0);
+ Assert.assertEquals(false, message.getDefaultBool());
+ Assert.assertEquals("415", message.getDefaultString());
Assert.assertEquals(toBytes("416"), message.getDefaultBytes());
- Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getDefaultNestedEnum ());
+ Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getDefaultNestedEnum());
Assert.assertEquals(ForeignEnum.FOREIGN_FOO, message.getDefaultForeignEnum());
Assert.assertEquals(ImportEnum.IMPORT_FOO, message.getDefaultImportEnum());
@@ -721,74 +692,73 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all fields of
- * {@code message} are cleared, and that getting the fields returns their
- * default values.
+ * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are cleared,
+ * and that getting the fields returns their default values.
*/
public static void assertClear(TestAllTypesOrBuilder message) {
// hasBlah() should initially be false for all optional fields.
- Assert.assertFalse(message.hasOptionalInt32 ());
- Assert.assertFalse(message.hasOptionalInt64 ());
- Assert.assertFalse(message.hasOptionalUint32 ());
- Assert.assertFalse(message.hasOptionalUint64 ());
- Assert.assertFalse(message.hasOptionalSint32 ());
- Assert.assertFalse(message.hasOptionalSint64 ());
- Assert.assertFalse(message.hasOptionalFixed32 ());
- Assert.assertFalse(message.hasOptionalFixed64 ());
+ Assert.assertFalse(message.hasOptionalInt32());
+ Assert.assertFalse(message.hasOptionalInt64());
+ Assert.assertFalse(message.hasOptionalUint32());
+ Assert.assertFalse(message.hasOptionalUint64());
+ Assert.assertFalse(message.hasOptionalSint32());
+ Assert.assertFalse(message.hasOptionalSint64());
+ Assert.assertFalse(message.hasOptionalFixed32());
+ Assert.assertFalse(message.hasOptionalFixed64());
Assert.assertFalse(message.hasOptionalSfixed32());
Assert.assertFalse(message.hasOptionalSfixed64());
- Assert.assertFalse(message.hasOptionalFloat ());
- Assert.assertFalse(message.hasOptionalDouble ());
- Assert.assertFalse(message.hasOptionalBool ());
- Assert.assertFalse(message.hasOptionalString ());
- Assert.assertFalse(message.hasOptionalBytes ());
-
- Assert.assertFalse(message.hasOptionalGroup ());
- Assert.assertFalse(message.hasOptionalNestedMessage ());
+ Assert.assertFalse(message.hasOptionalFloat());
+ Assert.assertFalse(message.hasOptionalDouble());
+ Assert.assertFalse(message.hasOptionalBool());
+ Assert.assertFalse(message.hasOptionalString());
+ Assert.assertFalse(message.hasOptionalBytes());
+
+ Assert.assertFalse(message.hasOptionalGroup());
+ Assert.assertFalse(message.hasOptionalNestedMessage());
Assert.assertFalse(message.hasOptionalForeignMessage());
- Assert.assertFalse(message.hasOptionalImportMessage ());
+ Assert.assertFalse(message.hasOptionalImportMessage());
- Assert.assertFalse(message.hasOptionalNestedEnum ());
+ Assert.assertFalse(message.hasOptionalNestedEnum());
Assert.assertFalse(message.hasOptionalForeignEnum());
- Assert.assertFalse(message.hasOptionalImportEnum ());
+ Assert.assertFalse(message.hasOptionalImportEnum());
Assert.assertFalse(message.hasOptionalStringPiece());
Assert.assertFalse(message.hasOptionalCord());
// Optional fields without defaults are set to zero or something like it.
- Assert.assertEquals(0 , message.getOptionalInt32 ());
- Assert.assertEquals(0 , message.getOptionalInt64 ());
- Assert.assertEquals(0 , message.getOptionalUint32 ());
- Assert.assertEquals(0 , message.getOptionalUint64 ());
- Assert.assertEquals(0 , message.getOptionalSint32 ());
- Assert.assertEquals(0 , message.getOptionalSint64 ());
- Assert.assertEquals(0 , message.getOptionalFixed32 ());
- Assert.assertEquals(0 , message.getOptionalFixed64 ());
- Assert.assertEquals(0 , message.getOptionalSfixed32());
- Assert.assertEquals(0 , message.getOptionalSfixed64());
- Assert.assertEquals(0 , message.getOptionalFloat (), 0.0);
- Assert.assertEquals(0 , message.getOptionalDouble (), 0.0);
- Assert.assertEquals(false, message.getOptionalBool ());
- Assert.assertEquals("" , message.getOptionalString ());
+ Assert.assertEquals(0, message.getOptionalInt32());
+ Assert.assertEquals(0, message.getOptionalInt64());
+ Assert.assertEquals(0, message.getOptionalUint32());
+ Assert.assertEquals(0, message.getOptionalUint64());
+ Assert.assertEquals(0, message.getOptionalSint32());
+ Assert.assertEquals(0, message.getOptionalSint64());
+ Assert.assertEquals(0, message.getOptionalFixed32());
+ Assert.assertEquals(0, message.getOptionalFixed64());
+ Assert.assertEquals(0, message.getOptionalSfixed32());
+ Assert.assertEquals(0, message.getOptionalSfixed64());
+ Assert.assertEquals(0, message.getOptionalFloat(), 0.0);
+ Assert.assertEquals(0, message.getOptionalDouble(), 0.0);
+ Assert.assertEquals(false, message.getOptionalBool());
+ Assert.assertEquals("", message.getOptionalString());
Assert.assertEquals(ByteString.EMPTY, message.getOptionalBytes());
// Embedded messages should also be clear.
- Assert.assertFalse(message.getOptionalGroup ().hasA());
- Assert.assertFalse(message.getOptionalNestedMessage ().hasBb());
- Assert.assertFalse(message.getOptionalForeignMessage ().hasC());
- Assert.assertFalse(message.getOptionalImportMessage ().hasD());
+ Assert.assertFalse(message.getOptionalGroup().hasA());
+ Assert.assertFalse(message.getOptionalNestedMessage().hasBb());
+ Assert.assertFalse(message.getOptionalForeignMessage().hasC());
+ Assert.assertFalse(message.getOptionalImportMessage().hasD());
Assert.assertFalse(message.getOptionalPublicImportMessage().hasE());
- Assert.assertFalse(message.getOptionalLazyMessage ().hasBb());
+ Assert.assertFalse(message.getOptionalLazyMessage().hasBb());
- Assert.assertEquals(0, message.getOptionalGroup ().getA());
- Assert.assertEquals(0, message.getOptionalNestedMessage ().getBb());
- Assert.assertEquals(0, message.getOptionalForeignMessage ().getC());
- Assert.assertEquals(0, message.getOptionalImportMessage ().getD());
+ Assert.assertEquals(0, message.getOptionalGroup().getA());
+ Assert.assertEquals(0, message.getOptionalNestedMessage().getBb());
+ Assert.assertEquals(0, message.getOptionalForeignMessage().getC());
+ Assert.assertEquals(0, message.getOptionalImportMessage().getD());
Assert.assertEquals(0, message.getOptionalPublicImportMessage().getE());
- Assert.assertEquals(0, message.getOptionalLazyMessage ().getBb());
+ Assert.assertEquals(0, message.getOptionalLazyMessage().getBb());
// Enums without defaults are set to the first value in the enum.
- Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getOptionalNestedEnum ());
+ Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getOptionalNestedEnum());
Assert.assertEquals(ForeignEnum.FOREIGN_FOO, message.getOptionalForeignEnum());
Assert.assertEquals(ImportEnum.IMPORT_FOO, message.getOptionalImportEnum());
@@ -796,76 +766,76 @@ public final class TestUtil {
Assert.assertEquals("", message.getOptionalCord());
// Repeated fields are empty.
- Assert.assertEquals(0, message.getRepeatedInt32Count ());
- Assert.assertEquals(0, message.getRepeatedInt64Count ());
- Assert.assertEquals(0, message.getRepeatedUint32Count ());
- Assert.assertEquals(0, message.getRepeatedUint64Count ());
- Assert.assertEquals(0, message.getRepeatedSint32Count ());
- Assert.assertEquals(0, message.getRepeatedSint64Count ());
- Assert.assertEquals(0, message.getRepeatedFixed32Count ());
- Assert.assertEquals(0, message.getRepeatedFixed64Count ());
+ Assert.assertEquals(0, message.getRepeatedInt32Count());
+ Assert.assertEquals(0, message.getRepeatedInt64Count());
+ Assert.assertEquals(0, message.getRepeatedUint32Count());
+ Assert.assertEquals(0, message.getRepeatedUint64Count());
+ Assert.assertEquals(0, message.getRepeatedSint32Count());
+ Assert.assertEquals(0, message.getRepeatedSint64Count());
+ Assert.assertEquals(0, message.getRepeatedFixed32Count());
+ Assert.assertEquals(0, message.getRepeatedFixed64Count());
Assert.assertEquals(0, message.getRepeatedSfixed32Count());
Assert.assertEquals(0, message.getRepeatedSfixed64Count());
- Assert.assertEquals(0, message.getRepeatedFloatCount ());
- Assert.assertEquals(0, message.getRepeatedDoubleCount ());
- Assert.assertEquals(0, message.getRepeatedBoolCount ());
- Assert.assertEquals(0, message.getRepeatedStringCount ());
- Assert.assertEquals(0, message.getRepeatedBytesCount ());
-
- Assert.assertEquals(0, message.getRepeatedGroupCount ());
- Assert.assertEquals(0, message.getRepeatedNestedMessageCount ());
+ Assert.assertEquals(0, message.getRepeatedFloatCount());
+ Assert.assertEquals(0, message.getRepeatedDoubleCount());
+ Assert.assertEquals(0, message.getRepeatedBoolCount());
+ Assert.assertEquals(0, message.getRepeatedStringCount());
+ Assert.assertEquals(0, message.getRepeatedBytesCount());
+
+ Assert.assertEquals(0, message.getRepeatedGroupCount());
+ Assert.assertEquals(0, message.getRepeatedNestedMessageCount());
Assert.assertEquals(0, message.getRepeatedForeignMessageCount());
- Assert.assertEquals(0, message.getRepeatedImportMessageCount ());
- Assert.assertEquals(0, message.getRepeatedLazyMessageCount ());
- Assert.assertEquals(0, message.getRepeatedNestedEnumCount ());
- Assert.assertEquals(0, message.getRepeatedForeignEnumCount ());
- Assert.assertEquals(0, message.getRepeatedImportEnumCount ());
+ Assert.assertEquals(0, message.getRepeatedImportMessageCount());
+ Assert.assertEquals(0, message.getRepeatedLazyMessageCount());
+ Assert.assertEquals(0, message.getRepeatedNestedEnumCount());
+ Assert.assertEquals(0, message.getRepeatedForeignEnumCount());
+ Assert.assertEquals(0, message.getRepeatedImportEnumCount());
Assert.assertEquals(0, message.getRepeatedStringPieceCount());
Assert.assertEquals(0, message.getRepeatedCordCount());
// hasBlah() should also be false for all default fields.
- Assert.assertFalse(message.hasDefaultInt32 ());
- Assert.assertFalse(message.hasDefaultInt64 ());
- Assert.assertFalse(message.hasDefaultUint32 ());
- Assert.assertFalse(message.hasDefaultUint64 ());
- Assert.assertFalse(message.hasDefaultSint32 ());
- Assert.assertFalse(message.hasDefaultSint64 ());
- Assert.assertFalse(message.hasDefaultFixed32 ());
- Assert.assertFalse(message.hasDefaultFixed64 ());
+ Assert.assertFalse(message.hasDefaultInt32());
+ Assert.assertFalse(message.hasDefaultInt64());
+ Assert.assertFalse(message.hasDefaultUint32());
+ Assert.assertFalse(message.hasDefaultUint64());
+ Assert.assertFalse(message.hasDefaultSint32());
+ Assert.assertFalse(message.hasDefaultSint64());
+ Assert.assertFalse(message.hasDefaultFixed32());
+ Assert.assertFalse(message.hasDefaultFixed64());
Assert.assertFalse(message.hasDefaultSfixed32());
Assert.assertFalse(message.hasDefaultSfixed64());
- Assert.assertFalse(message.hasDefaultFloat ());
- Assert.assertFalse(message.hasDefaultDouble ());
- Assert.assertFalse(message.hasDefaultBool ());
- Assert.assertFalse(message.hasDefaultString ());
- Assert.assertFalse(message.hasDefaultBytes ());
+ Assert.assertFalse(message.hasDefaultFloat());
+ Assert.assertFalse(message.hasDefaultDouble());
+ Assert.assertFalse(message.hasDefaultBool());
+ Assert.assertFalse(message.hasDefaultString());
+ Assert.assertFalse(message.hasDefaultBytes());
- Assert.assertFalse(message.hasDefaultNestedEnum ());
+ Assert.assertFalse(message.hasDefaultNestedEnum());
Assert.assertFalse(message.hasDefaultForeignEnum());
- Assert.assertFalse(message.hasDefaultImportEnum ());
+ Assert.assertFalse(message.hasDefaultImportEnum());
Assert.assertFalse(message.hasDefaultStringPiece());
Assert.assertFalse(message.hasDefaultCord());
// Fields with defaults have their default values (duh).
- Assert.assertEquals( 41 , message.getDefaultInt32 ());
- Assert.assertEquals( 42 , message.getDefaultInt64 ());
- Assert.assertEquals( 43 , message.getDefaultUint32 ());
- Assert.assertEquals( 44 , message.getDefaultUint64 ());
- Assert.assertEquals(-45 , message.getDefaultSint32 ());
- Assert.assertEquals( 46 , message.getDefaultSint64 ());
- Assert.assertEquals( 47 , message.getDefaultFixed32 ());
- Assert.assertEquals( 48 , message.getDefaultFixed64 ());
- Assert.assertEquals( 49 , message.getDefaultSfixed32());
- Assert.assertEquals(-50 , message.getDefaultSfixed64());
- Assert.assertEquals( 51.5 , message.getDefaultFloat (), 0.0);
- Assert.assertEquals( 52e3 , message.getDefaultDouble (), 0.0);
- Assert.assertEquals(true , message.getDefaultBool ());
- Assert.assertEquals("hello", message.getDefaultString ());
+ Assert.assertEquals(41, message.getDefaultInt32());
+ Assert.assertEquals(42, message.getDefaultInt64());
+ Assert.assertEquals(43, message.getDefaultUint32());
+ Assert.assertEquals(44, message.getDefaultUint64());
+ Assert.assertEquals(-45, message.getDefaultSint32());
+ Assert.assertEquals(46, message.getDefaultSint64());
+ Assert.assertEquals(47, message.getDefaultFixed32());
+ Assert.assertEquals(48, message.getDefaultFixed64());
+ Assert.assertEquals(49, message.getDefaultSfixed32());
+ Assert.assertEquals(-50, message.getDefaultSfixed64());
+ Assert.assertEquals(51.5, message.getDefaultFloat(), 0.0);
+ Assert.assertEquals(52e3, message.getDefaultDouble(), 0.0);
+ Assert.assertEquals(true, message.getDefaultBool());
+ Assert.assertEquals("hello", message.getDefaultString());
Assert.assertEquals(toBytes("world"), message.getDefaultBytes());
- Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getDefaultNestedEnum ());
+ Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getDefaultNestedEnum());
Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getDefaultForeignEnum());
Assert.assertEquals(ImportEnum.IMPORT_BAR, message.getDefaultImportEnum());
@@ -881,66 +851,64 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all fields of
- * {@code message} are set to the values assigned by {@code setAllFields}
- * followed by {@code modifyRepeatedFields}.
+ * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to the
+ * values assigned by {@code setAllFields} followed by {@code modifyRepeatedFields}.
*/
- public static void assertRepeatedFieldsModified(
- TestAllTypesOrBuilder message) {
+ public static void assertRepeatedFieldsModified(TestAllTypesOrBuilder message) {
// ModifyRepeatedFields only sets the second repeated element of each
// field. In addition to verifying this, we also verify that the first
// element and size were *not* modified.
- Assert.assertEquals(2, message.getRepeatedInt32Count ());
- Assert.assertEquals(2, message.getRepeatedInt64Count ());
- Assert.assertEquals(2, message.getRepeatedUint32Count ());
- Assert.assertEquals(2, message.getRepeatedUint64Count ());
- Assert.assertEquals(2, message.getRepeatedSint32Count ());
- Assert.assertEquals(2, message.getRepeatedSint64Count ());
- Assert.assertEquals(2, message.getRepeatedFixed32Count ());
- Assert.assertEquals(2, message.getRepeatedFixed64Count ());
+ Assert.assertEquals(2, message.getRepeatedInt32Count());
+ Assert.assertEquals(2, message.getRepeatedInt64Count());
+ Assert.assertEquals(2, message.getRepeatedUint32Count());
+ Assert.assertEquals(2, message.getRepeatedUint64Count());
+ Assert.assertEquals(2, message.getRepeatedSint32Count());
+ Assert.assertEquals(2, message.getRepeatedSint64Count());
+ Assert.assertEquals(2, message.getRepeatedFixed32Count());
+ Assert.assertEquals(2, message.getRepeatedFixed64Count());
Assert.assertEquals(2, message.getRepeatedSfixed32Count());
Assert.assertEquals(2, message.getRepeatedSfixed64Count());
- Assert.assertEquals(2, message.getRepeatedFloatCount ());
- Assert.assertEquals(2, message.getRepeatedDoubleCount ());
- Assert.assertEquals(2, message.getRepeatedBoolCount ());
- Assert.assertEquals(2, message.getRepeatedStringCount ());
- Assert.assertEquals(2, message.getRepeatedBytesCount ());
-
- Assert.assertEquals(2, message.getRepeatedGroupCount ());
- Assert.assertEquals(2, message.getRepeatedNestedMessageCount ());
+ Assert.assertEquals(2, message.getRepeatedFloatCount());
+ Assert.assertEquals(2, message.getRepeatedDoubleCount());
+ Assert.assertEquals(2, message.getRepeatedBoolCount());
+ Assert.assertEquals(2, message.getRepeatedStringCount());
+ Assert.assertEquals(2, message.getRepeatedBytesCount());
+
+ Assert.assertEquals(2, message.getRepeatedGroupCount());
+ Assert.assertEquals(2, message.getRepeatedNestedMessageCount());
Assert.assertEquals(2, message.getRepeatedForeignMessageCount());
- Assert.assertEquals(2, message.getRepeatedImportMessageCount ());
- Assert.assertEquals(2, message.getRepeatedLazyMessageCount ());
- Assert.assertEquals(2, message.getRepeatedNestedEnumCount ());
- Assert.assertEquals(2, message.getRepeatedForeignEnumCount ());
- Assert.assertEquals(2, message.getRepeatedImportEnumCount ());
+ Assert.assertEquals(2, message.getRepeatedImportMessageCount());
+ Assert.assertEquals(2, message.getRepeatedLazyMessageCount());
+ Assert.assertEquals(2, message.getRepeatedNestedEnumCount());
+ Assert.assertEquals(2, message.getRepeatedForeignEnumCount());
+ Assert.assertEquals(2, message.getRepeatedImportEnumCount());
Assert.assertEquals(2, message.getRepeatedStringPieceCount());
Assert.assertEquals(2, message.getRepeatedCordCount());
- Assert.assertEquals(201 , message.getRepeatedInt32 (0));
- Assert.assertEquals(202L , message.getRepeatedInt64 (0));
- Assert.assertEquals(203 , message.getRepeatedUint32 (0));
- Assert.assertEquals(204L , message.getRepeatedUint64 (0));
- Assert.assertEquals(205 , message.getRepeatedSint32 (0));
- Assert.assertEquals(206L , message.getRepeatedSint64 (0));
- Assert.assertEquals(207 , message.getRepeatedFixed32 (0));
- Assert.assertEquals(208L , message.getRepeatedFixed64 (0));
- Assert.assertEquals(209 , message.getRepeatedSfixed32(0));
- Assert.assertEquals(210L , message.getRepeatedSfixed64(0));
- Assert.assertEquals(211F , message.getRepeatedFloat (0));
- Assert.assertEquals(212D , message.getRepeatedDouble (0));
- Assert.assertEquals(true , message.getRepeatedBool (0));
- Assert.assertEquals("215", message.getRepeatedString (0));
+ Assert.assertEquals(201, message.getRepeatedInt32(0));
+ Assert.assertEquals(202L, message.getRepeatedInt64(0));
+ Assert.assertEquals(203, message.getRepeatedUint32(0));
+ Assert.assertEquals(204L, message.getRepeatedUint64(0));
+ Assert.assertEquals(205, message.getRepeatedSint32(0));
+ Assert.assertEquals(206L, message.getRepeatedSint64(0));
+ Assert.assertEquals(207, message.getRepeatedFixed32(0));
+ Assert.assertEquals(208L, message.getRepeatedFixed64(0));
+ Assert.assertEquals(209, message.getRepeatedSfixed32(0));
+ Assert.assertEquals(210L, message.getRepeatedSfixed64(0));
+ Assert.assertEquals(211F, message.getRepeatedFloat(0));
+ Assert.assertEquals(212D, message.getRepeatedDouble(0));
+ Assert.assertEquals(true, message.getRepeatedBool(0));
+ Assert.assertEquals("215", message.getRepeatedString(0));
Assert.assertEquals(toBytes("216"), message.getRepeatedBytes(0));
- Assert.assertEquals(217, message.getRepeatedGroup (0).getA());
- Assert.assertEquals(218, message.getRepeatedNestedMessage (0).getBb());
+ Assert.assertEquals(217, message.getRepeatedGroup(0).getA());
+ Assert.assertEquals(218, message.getRepeatedNestedMessage(0).getBb());
Assert.assertEquals(219, message.getRepeatedForeignMessage(0).getC());
- Assert.assertEquals(220, message.getRepeatedImportMessage (0).getD());
- Assert.assertEquals(227, message.getRepeatedLazyMessage (0).getBb());
+ Assert.assertEquals(220, message.getRepeatedImportMessage(0).getD());
+ Assert.assertEquals(227, message.getRepeatedLazyMessage(0).getBb());
- Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getRepeatedNestedEnum (0));
+ Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getRepeatedNestedEnum(0));
Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getRepeatedForeignEnum(0));
Assert.assertEquals(ImportEnum.IMPORT_BAR, message.getRepeatedImportEnum(0));
@@ -948,29 +916,29 @@ public final class TestUtil {
Assert.assertEquals("225", message.getRepeatedCord(0));
// Actually verify the second (modified) elements now.
- Assert.assertEquals(501 , message.getRepeatedInt32 (1));
- Assert.assertEquals(502L , message.getRepeatedInt64 (1));
- Assert.assertEquals(503 , message.getRepeatedUint32 (1));
- Assert.assertEquals(504L , message.getRepeatedUint64 (1));
- Assert.assertEquals(505 , message.getRepeatedSint32 (1));
- Assert.assertEquals(506L , message.getRepeatedSint64 (1));
- Assert.assertEquals(507 , message.getRepeatedFixed32 (1));
- Assert.assertEquals(508L , message.getRepeatedFixed64 (1));
- Assert.assertEquals(509 , message.getRepeatedSfixed32(1));
- Assert.assertEquals(510L , message.getRepeatedSfixed64(1));
- Assert.assertEquals(511F , message.getRepeatedFloat (1));
- Assert.assertEquals(512D , message.getRepeatedDouble (1));
- Assert.assertEquals(true , message.getRepeatedBool (1));
- Assert.assertEquals("515", message.getRepeatedString (1));
+ Assert.assertEquals(501, message.getRepeatedInt32(1));
+ Assert.assertEquals(502L, message.getRepeatedInt64(1));
+ Assert.assertEquals(503, message.getRepeatedUint32(1));
+ Assert.assertEquals(504L, message.getRepeatedUint64(1));
+ Assert.assertEquals(505, message.getRepeatedSint32(1));
+ Assert.assertEquals(506L, message.getRepeatedSint64(1));
+ Assert.assertEquals(507, message.getRepeatedFixed32(1));
+ Assert.assertEquals(508L, message.getRepeatedFixed64(1));
+ Assert.assertEquals(509, message.getRepeatedSfixed32(1));
+ Assert.assertEquals(510L, message.getRepeatedSfixed64(1));
+ Assert.assertEquals(511F, message.getRepeatedFloat(1));
+ Assert.assertEquals(512D, message.getRepeatedDouble(1));
+ Assert.assertEquals(true, message.getRepeatedBool(1));
+ Assert.assertEquals("515", message.getRepeatedString(1));
Assert.assertEquals(toBytes("516"), message.getRepeatedBytes(1));
- Assert.assertEquals(517, message.getRepeatedGroup (1).getA());
- Assert.assertEquals(518, message.getRepeatedNestedMessage (1).getBb());
+ Assert.assertEquals(517, message.getRepeatedGroup(1).getA());
+ Assert.assertEquals(518, message.getRepeatedNestedMessage(1).getBb());
Assert.assertEquals(519, message.getRepeatedForeignMessage(1).getC());
- Assert.assertEquals(520, message.getRepeatedImportMessage (1).getD());
- Assert.assertEquals(527, message.getRepeatedLazyMessage (1).getBb());
+ Assert.assertEquals(520, message.getRepeatedImportMessage(1).getD());
+ Assert.assertEquals(527, message.getRepeatedLazyMessage(1).getBb());
- Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getRepeatedNestedEnum (1));
+ Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getRepeatedNestedEnum(1));
Assert.assertEquals(ForeignEnum.FOREIGN_FOO, message.getRepeatedForeignEnum(1));
Assert.assertEquals(ImportEnum.IMPORT_FOO, message.getRepeatedImportEnum(1));
@@ -978,172 +946,170 @@ public final class TestUtil {
Assert.assertEquals("525", message.getRepeatedCord(1));
}
- /**
- * Set every field of {@code message} to a unique value.
- */
+ /** Set every field of {@code message} to a unique value. */
public static void setPackedFields(TestPackedTypes.Builder message) {
- message.addPackedInt32 (601);
- message.addPackedInt64 (602);
- message.addPackedUint32 (603);
- message.addPackedUint64 (604);
- message.addPackedSint32 (605);
- message.addPackedSint64 (606);
- message.addPackedFixed32 (607);
- message.addPackedFixed64 (608);
+ message.addPackedInt32(601);
+ message.addPackedInt64(602);
+ message.addPackedUint32(603);
+ message.addPackedUint64(604);
+ message.addPackedSint32(605);
+ message.addPackedSint64(606);
+ message.addPackedFixed32(607);
+ message.addPackedFixed64(608);
message.addPackedSfixed32(609);
message.addPackedSfixed64(610);
- message.addPackedFloat (611);
- message.addPackedDouble (612);
- message.addPackedBool (true);
- message.addPackedEnum (ForeignEnum.FOREIGN_BAR);
+ message.addPackedFloat(611);
+ message.addPackedDouble(612);
+ message.addPackedBool(true);
+ message.addPackedEnum(ForeignEnum.FOREIGN_BAR);
// Add a second one of each field.
- message.addPackedInt32 (701);
- message.addPackedInt64 (702);
- message.addPackedUint32 (703);
- message.addPackedUint64 (704);
- message.addPackedSint32 (705);
- message.addPackedSint64 (706);
- message.addPackedFixed32 (707);
- message.addPackedFixed64 (708);
+ message.addPackedInt32(701);
+ message.addPackedInt64(702);
+ message.addPackedUint32(703);
+ message.addPackedUint64(704);
+ message.addPackedSint32(705);
+ message.addPackedSint64(706);
+ message.addPackedFixed32(707);
+ message.addPackedFixed64(708);
message.addPackedSfixed32(709);
message.addPackedSfixed64(710);
- message.addPackedFloat (711);
- message.addPackedDouble (712);
- message.addPackedBool (false);
- message.addPackedEnum (ForeignEnum.FOREIGN_BAZ);
+ message.addPackedFloat(711);
+ message.addPackedDouble(712);
+ message.addPackedBool(false);
+ message.addPackedEnum(ForeignEnum.FOREIGN_BAZ);
}
/**
- * Set every field of {@code message} to a unique value. Must correspond with
- * the values applied by {@code setPackedFields}.
+ * Set every field of {@code message} to a unique value. Must correspond with the values applied
+ * by {@code setPackedFields}.
*/
public static void setUnpackedFields(TestUnpackedTypes.Builder message) {
- message.addUnpackedInt32 (601);
- message.addUnpackedInt64 (602);
- message.addUnpackedUint32 (603);
- message.addUnpackedUint64 (604);
- message.addUnpackedSint32 (605);
- message.addUnpackedSint64 (606);
- message.addUnpackedFixed32 (607);
- message.addUnpackedFixed64 (608);
+ message.addUnpackedInt32(601);
+ message.addUnpackedInt64(602);
+ message.addUnpackedUint32(603);
+ message.addUnpackedUint64(604);
+ message.addUnpackedSint32(605);
+ message.addUnpackedSint64(606);
+ message.addUnpackedFixed32(607);
+ message.addUnpackedFixed64(608);
message.addUnpackedSfixed32(609);
message.addUnpackedSfixed64(610);
- message.addUnpackedFloat (611);
- message.addUnpackedDouble (612);
- message.addUnpackedBool (true);
- message.addUnpackedEnum (ForeignEnum.FOREIGN_BAR);
+ message.addUnpackedFloat(611);
+ message.addUnpackedDouble(612);
+ message.addUnpackedBool(true);
+ message.addUnpackedEnum(ForeignEnum.FOREIGN_BAR);
// Add a second one of each field.
- message.addUnpackedInt32 (701);
- message.addUnpackedInt64 (702);
- message.addUnpackedUint32 (703);
- message.addUnpackedUint64 (704);
- message.addUnpackedSint32 (705);
- message.addUnpackedSint64 (706);
- message.addUnpackedFixed32 (707);
- message.addUnpackedFixed64 (708);
+ message.addUnpackedInt32(701);
+ message.addUnpackedInt64(702);
+ message.addUnpackedUint32(703);
+ message.addUnpackedUint64(704);
+ message.addUnpackedSint32(705);
+ message.addUnpackedSint64(706);
+ message.addUnpackedFixed32(707);
+ message.addUnpackedFixed64(708);
message.addUnpackedSfixed32(709);
message.addUnpackedSfixed64(710);
- message.addUnpackedFloat (711);
- message.addUnpackedDouble (712);
- message.addUnpackedBool (false);
- message.addUnpackedEnum (ForeignEnum.FOREIGN_BAZ);
+ message.addUnpackedFloat(711);
+ message.addUnpackedDouble(712);
+ message.addUnpackedBool(false);
+ message.addUnpackedEnum(ForeignEnum.FOREIGN_BAZ);
}
/**
- * Assert (using {@code junit.framework.Assert}} that all fields of
- * {@code message} are set to the values assigned by {@code setPackedFields}.
+ * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to the
+ * values assigned by {@code setPackedFields}.
*/
public static void assertPackedFieldsSet(TestPackedTypes message) {
- Assert.assertEquals(2, message.getPackedInt32Count ());
- Assert.assertEquals(2, message.getPackedInt64Count ());
- Assert.assertEquals(2, message.getPackedUint32Count ());
- Assert.assertEquals(2, message.getPackedUint64Count ());
- Assert.assertEquals(2, message.getPackedSint32Count ());
- Assert.assertEquals(2, message.getPackedSint64Count ());
- Assert.assertEquals(2, message.getPackedFixed32Count ());
- Assert.assertEquals(2, message.getPackedFixed64Count ());
+ Assert.assertEquals(2, message.getPackedInt32Count());
+ Assert.assertEquals(2, message.getPackedInt64Count());
+ Assert.assertEquals(2, message.getPackedUint32Count());
+ Assert.assertEquals(2, message.getPackedUint64Count());
+ Assert.assertEquals(2, message.getPackedSint32Count());
+ Assert.assertEquals(2, message.getPackedSint64Count());
+ Assert.assertEquals(2, message.getPackedFixed32Count());
+ Assert.assertEquals(2, message.getPackedFixed64Count());
Assert.assertEquals(2, message.getPackedSfixed32Count());
Assert.assertEquals(2, message.getPackedSfixed64Count());
- Assert.assertEquals(2, message.getPackedFloatCount ());
- Assert.assertEquals(2, message.getPackedDoubleCount ());
- Assert.assertEquals(2, message.getPackedBoolCount ());
- Assert.assertEquals(2, message.getPackedEnumCount ());
- Assert.assertEquals(601 , message.getPackedInt32 (0));
- Assert.assertEquals(602 , message.getPackedInt64 (0));
- Assert.assertEquals(603 , message.getPackedUint32 (0));
- Assert.assertEquals(604 , message.getPackedUint64 (0));
- Assert.assertEquals(605 , message.getPackedSint32 (0));
- Assert.assertEquals(606 , message.getPackedSint64 (0));
- Assert.assertEquals(607 , message.getPackedFixed32 (0));
- Assert.assertEquals(608 , message.getPackedFixed64 (0));
- Assert.assertEquals(609 , message.getPackedSfixed32(0));
- Assert.assertEquals(610 , message.getPackedSfixed64(0));
- Assert.assertEquals(611 , message.getPackedFloat (0), 0.0);
- Assert.assertEquals(612 , message.getPackedDouble (0), 0.0);
- Assert.assertEquals(true , message.getPackedBool (0));
+ Assert.assertEquals(2, message.getPackedFloatCount());
+ Assert.assertEquals(2, message.getPackedDoubleCount());
+ Assert.assertEquals(2, message.getPackedBoolCount());
+ Assert.assertEquals(2, message.getPackedEnumCount());
+ Assert.assertEquals(601, message.getPackedInt32(0));
+ Assert.assertEquals(602, message.getPackedInt64(0));
+ Assert.assertEquals(603, message.getPackedUint32(0));
+ Assert.assertEquals(604, message.getPackedUint64(0));
+ Assert.assertEquals(605, message.getPackedSint32(0));
+ Assert.assertEquals(606, message.getPackedSint64(0));
+ Assert.assertEquals(607, message.getPackedFixed32(0));
+ Assert.assertEquals(608, message.getPackedFixed64(0));
+ Assert.assertEquals(609, message.getPackedSfixed32(0));
+ Assert.assertEquals(610, message.getPackedSfixed64(0));
+ Assert.assertEquals(611, message.getPackedFloat(0), 0.0);
+ Assert.assertEquals(612, message.getPackedDouble(0), 0.0);
+ Assert.assertEquals(true, message.getPackedBool(0));
Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getPackedEnum(0));
- Assert.assertEquals(701 , message.getPackedInt32 (1));
- Assert.assertEquals(702 , message.getPackedInt64 (1));
- Assert.assertEquals(703 , message.getPackedUint32 (1));
- Assert.assertEquals(704 , message.getPackedUint64 (1));
- Assert.assertEquals(705 , message.getPackedSint32 (1));
- Assert.assertEquals(706 , message.getPackedSint64 (1));
- Assert.assertEquals(707 , message.getPackedFixed32 (1));
- Assert.assertEquals(708 , message.getPackedFixed64 (1));
- Assert.assertEquals(709 , message.getPackedSfixed32(1));
- Assert.assertEquals(710 , message.getPackedSfixed64(1));
- Assert.assertEquals(711 , message.getPackedFloat (1), 0.0);
- Assert.assertEquals(712 , message.getPackedDouble (1), 0.0);
- Assert.assertEquals(false, message.getPackedBool (1));
+ Assert.assertEquals(701, message.getPackedInt32(1));
+ Assert.assertEquals(702, message.getPackedInt64(1));
+ Assert.assertEquals(703, message.getPackedUint32(1));
+ Assert.assertEquals(704, message.getPackedUint64(1));
+ Assert.assertEquals(705, message.getPackedSint32(1));
+ Assert.assertEquals(706, message.getPackedSint64(1));
+ Assert.assertEquals(707, message.getPackedFixed32(1));
+ Assert.assertEquals(708, message.getPackedFixed64(1));
+ Assert.assertEquals(709, message.getPackedSfixed32(1));
+ Assert.assertEquals(710, message.getPackedSfixed64(1));
+ Assert.assertEquals(711, message.getPackedFloat(1), 0.0);
+ Assert.assertEquals(712, message.getPackedDouble(1), 0.0);
+ Assert.assertEquals(false, message.getPackedBool(1));
Assert.assertEquals(ForeignEnum.FOREIGN_BAZ, message.getPackedEnum(1));
}
/**
- * Assert (using {@code junit.framework.Assert}} that all fields of
- * {@code message} are set to the values assigned by {@code setUnpackedFields}.
+ * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to the
+ * values assigned by {@code setUnpackedFields}.
*/
public static void assertUnpackedFieldsSet(TestUnpackedTypes message) {
- Assert.assertEquals(2, message.getUnpackedInt32Count ());
- Assert.assertEquals(2, message.getUnpackedInt64Count ());
- Assert.assertEquals(2, message.getUnpackedUint32Count ());
- Assert.assertEquals(2, message.getUnpackedUint64Count ());
- Assert.assertEquals(2, message.getUnpackedSint32Count ());
- Assert.assertEquals(2, message.getUnpackedSint64Count ());
- Assert.assertEquals(2, message.getUnpackedFixed32Count ());
- Assert.assertEquals(2, message.getUnpackedFixed64Count ());
+ Assert.assertEquals(2, message.getUnpackedInt32Count());
+ Assert.assertEquals(2, message.getUnpackedInt64Count());
+ Assert.assertEquals(2, message.getUnpackedUint32Count());
+ Assert.assertEquals(2, message.getUnpackedUint64Count());
+ Assert.assertEquals(2, message.getUnpackedSint32Count());
+ Assert.assertEquals(2, message.getUnpackedSint64Count());
+ Assert.assertEquals(2, message.getUnpackedFixed32Count());
+ Assert.assertEquals(2, message.getUnpackedFixed64Count());
Assert.assertEquals(2, message.getUnpackedSfixed32Count());
Assert.assertEquals(2, message.getUnpackedSfixed64Count());
- Assert.assertEquals(2, message.getUnpackedFloatCount ());
- Assert.assertEquals(2, message.getUnpackedDoubleCount ());
- Assert.assertEquals(2, message.getUnpackedBoolCount ());
- Assert.assertEquals(2, message.getUnpackedEnumCount ());
- Assert.assertEquals(601 , message.getUnpackedInt32 (0));
- Assert.assertEquals(602 , message.getUnpackedInt64 (0));
- Assert.assertEquals(603 , message.getUnpackedUint32 (0));
- Assert.assertEquals(604 , message.getUnpackedUint64 (0));
- Assert.assertEquals(605 , message.getUnpackedSint32 (0));
- Assert.assertEquals(606 , message.getUnpackedSint64 (0));
- Assert.assertEquals(607 , message.getUnpackedFixed32 (0));
- Assert.assertEquals(608 , message.getUnpackedFixed64 (0));
- Assert.assertEquals(609 , message.getUnpackedSfixed32(0));
- Assert.assertEquals(610 , message.getUnpackedSfixed64(0));
- Assert.assertEquals(611 , message.getUnpackedFloat (0), 0.0);
- Assert.assertEquals(612 , message.getUnpackedDouble (0), 0.0);
- Assert.assertEquals(true , message.getUnpackedBool (0));
+ Assert.assertEquals(2, message.getUnpackedFloatCount());
+ Assert.assertEquals(2, message.getUnpackedDoubleCount());
+ Assert.assertEquals(2, message.getUnpackedBoolCount());
+ Assert.assertEquals(2, message.getUnpackedEnumCount());
+ Assert.assertEquals(601, message.getUnpackedInt32(0));
+ Assert.assertEquals(602, message.getUnpackedInt64(0));
+ Assert.assertEquals(603, message.getUnpackedUint32(0));
+ Assert.assertEquals(604, message.getUnpackedUint64(0));
+ Assert.assertEquals(605, message.getUnpackedSint32(0));
+ Assert.assertEquals(606, message.getUnpackedSint64(0));
+ Assert.assertEquals(607, message.getUnpackedFixed32(0));
+ Assert.assertEquals(608, message.getUnpackedFixed64(0));
+ Assert.assertEquals(609, message.getUnpackedSfixed32(0));
+ Assert.assertEquals(610, message.getUnpackedSfixed64(0));
+ Assert.assertEquals(611, message.getUnpackedFloat(0), 0.0);
+ Assert.assertEquals(612, message.getUnpackedDouble(0), 0.0);
+ Assert.assertEquals(true, message.getUnpackedBool(0));
Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getUnpackedEnum(0));
- Assert.assertEquals(701 , message.getUnpackedInt32 (1));
- Assert.assertEquals(702 , message.getUnpackedInt64 (1));
- Assert.assertEquals(703 , message.getUnpackedUint32 (1));
- Assert.assertEquals(704 , message.getUnpackedUint64 (1));
- Assert.assertEquals(705 , message.getUnpackedSint32 (1));
- Assert.assertEquals(706 , message.getUnpackedSint64 (1));
- Assert.assertEquals(707 , message.getUnpackedFixed32 (1));
- Assert.assertEquals(708 , message.getUnpackedFixed64 (1));
- Assert.assertEquals(709 , message.getUnpackedSfixed32(1));
- Assert.assertEquals(710 , message.getUnpackedSfixed64(1));
- Assert.assertEquals(711 , message.getUnpackedFloat (1), 0.0);
- Assert.assertEquals(712 , message.getUnpackedDouble (1), 0.0);
- Assert.assertEquals(false, message.getUnpackedBool (1));
+ Assert.assertEquals(701, message.getUnpackedInt32(1));
+ Assert.assertEquals(702, message.getUnpackedInt64(1));
+ Assert.assertEquals(703, message.getUnpackedUint32(1));
+ Assert.assertEquals(704, message.getUnpackedUint64(1));
+ Assert.assertEquals(705, message.getUnpackedSint32(1));
+ Assert.assertEquals(706, message.getUnpackedSint64(1));
+ Assert.assertEquals(707, message.getUnpackedFixed32(1));
+ Assert.assertEquals(708, message.getUnpackedFixed64(1));
+ Assert.assertEquals(709, message.getUnpackedSfixed32(1));
+ Assert.assertEquals(710, message.getUnpackedSfixed64(1));
+ Assert.assertEquals(711, message.getUnpackedFloat(1), 0.0);
+ Assert.assertEquals(712, message.getUnpackedDouble(1), 0.0);
+ Assert.assertEquals(false, message.getUnpackedBool(1));
Assert.assertEquals(ForeignEnum.FOREIGN_BAZ, message.getUnpackedEnum(1));
}
@@ -1156,50 +1122,59 @@ public final class TestUtil {
private static void assertEqualsExactType(int a, int b) {
Assert.assertEquals(a, b);
}
+
private static void assertEqualsExactType(long a, long b) {
Assert.assertEquals(a, b);
}
+
private static void assertEqualsExactType(float a, float b) {
Assert.assertEquals(a, b, 0.0);
}
+
private static void assertEqualsExactType(double a, double b) {
Assert.assertEquals(a, b, 0.0);
}
+
private static void assertEqualsExactType(boolean a, boolean b) {
Assert.assertEquals(a, b);
}
+
private static void assertEqualsExactType(String a, String b) {
Assert.assertEquals(a, b);
}
+
private static void assertEqualsExactType(ByteString a, ByteString b) {
Assert.assertEquals(a, b);
}
- private static void assertEqualsExactType(TestAllTypes.NestedEnum a,
- TestAllTypes.NestedEnum b) {
+
+ private static void assertEqualsExactType(TestAllTypes.NestedEnum a, TestAllTypes.NestedEnum b) {
Assert.assertEquals(a, b);
}
+
private static void assertEqualsExactType(ForeignEnum a, ForeignEnum b) {
Assert.assertEquals(a, b);
}
+
private static void assertEqualsExactType(ImportEnum a, ImportEnum b) {
Assert.assertEquals(a, b);
}
- private static void assertEqualsExactType(TestAllTypesLite.NestedEnum a,
- TestAllTypesLite.NestedEnum b) {
+
+ private static void assertEqualsExactType(
+ TestAllTypesLite.NestedEnum a, TestAllTypesLite.NestedEnum b) {
Assert.assertEquals(a, b);
}
- private static void assertEqualsExactType(ForeignEnumLite a,
- ForeignEnumLite b) {
+
+ private static void assertEqualsExactType(ForeignEnumLite a, ForeignEnumLite b) {
Assert.assertEquals(a, b);
}
- private static void assertEqualsExactType(ImportEnumLite a,
- ImportEnumLite b) {
+
+ private static void assertEqualsExactType(ImportEnumLite a, ImportEnumLite b) {
Assert.assertEquals(a, b);
}
/**
- * Get an unmodifiable {@link ExtensionRegistry} containing all the
- * extensions of {@code TestAllExtensions}.
+ * Get an unmodifiable {@link ExtensionRegistry} containing all the extensions of {@code
+ * TestAllExtensions}.
*/
public static ExtensionRegistryLite getExtensionRegistry() {
ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance();
@@ -1209,8 +1184,8 @@ public final class TestUtil {
// BEGIN FULL-RUNTIME
/**
- * Get an unmodifiable {@link ExtensionRegistry} containing all the
- * extensions of {@code TestAllExtensions}.
+ * Get an unmodifiable {@link ExtensionRegistry} containing all the extensions of {@code
+ * TestAllExtensions}.
*/
public static ExtensionRegistry getFullExtensionRegistry() {
ExtensionRegistry registry = ExtensionRegistry.newInstance();
@@ -1220,8 +1195,8 @@ public final class TestUtil {
// END FULL-RUNTIME
/**
- * Register all of {@code TestAllExtensions}'s extensions with the
- * given {@link ExtensionRegistry}.
+ * Register all of {@code TestAllExtensions}'s extensions with the given {@link
+ * ExtensionRegistry}.
*/
public static void registerAllExtensions(ExtensionRegistryLite registry) {
UnittestProto.registerAllExtensions(registry);
@@ -1229,38 +1204,37 @@ public final class TestUtil {
}
/**
- * Set every field of {@code message} to the values expected by
- * {@code assertAllExtensionsSet()}.
+ * Set every field of {@code message} to the values expected by {@code assertAllExtensionsSet()}.
*/
public static void setAllExtensions(TestAllExtensions.Builder message) {
- message.setExtension(optionalInt32Extension , 101);
- message.setExtension(optionalInt64Extension , 102L);
- message.setExtension(optionalUint32Extension , 103);
- message.setExtension(optionalUint64Extension , 104L);
- message.setExtension(optionalSint32Extension , 105);
- message.setExtension(optionalSint64Extension , 106L);
- message.setExtension(optionalFixed32Extension , 107);
- message.setExtension(optionalFixed64Extension , 108L);
+ message.setExtension(optionalInt32Extension, 101);
+ message.setExtension(optionalInt64Extension, 102L);
+ message.setExtension(optionalUint32Extension, 103);
+ message.setExtension(optionalUint64Extension, 104L);
+ message.setExtension(optionalSint32Extension, 105);
+ message.setExtension(optionalSint64Extension, 106L);
+ message.setExtension(optionalFixed32Extension, 107);
+ message.setExtension(optionalFixed64Extension, 108L);
message.setExtension(optionalSfixed32Extension, 109);
message.setExtension(optionalSfixed64Extension, 110L);
- message.setExtension(optionalFloatExtension , 111F);
- message.setExtension(optionalDoubleExtension , 112D);
- message.setExtension(optionalBoolExtension , true);
- message.setExtension(optionalStringExtension , "115");
- message.setExtension(optionalBytesExtension , toBytes("116"));
-
- message.setExtension(optionalGroupExtension,
- OptionalGroup_extension.newBuilder().setA(117).build());
- message.setExtension(optionalNestedMessageExtension,
- TestAllTypes.NestedMessage.newBuilder().setBb(118).build());
- message.setExtension(optionalForeignMessageExtension,
- ForeignMessage.newBuilder().setC(119).build());
- message.setExtension(optionalImportMessageExtension,
- ImportMessage.newBuilder().setD(120).build());
- message.setExtension(optionalPublicImportMessageExtension,
- PublicImportMessage.newBuilder().setE(126).build());
- message.setExtension(optionalLazyMessageExtension,
- TestAllTypes.NestedMessage.newBuilder().setBb(127).build());
+ message.setExtension(optionalFloatExtension, 111F);
+ message.setExtension(optionalDoubleExtension, 112D);
+ message.setExtension(optionalBoolExtension, true);
+ message.setExtension(optionalStringExtension, "115");
+ message.setExtension(optionalBytesExtension, toBytes("116"));
+
+ message.setExtension(
+ optionalGroupExtension, OptionalGroup_extension.newBuilder().setA(117).build());
+ message.setExtension(
+ optionalNestedMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(118).build());
+ message.setExtension(
+ optionalForeignMessageExtension, ForeignMessage.newBuilder().setC(119).build());
+ message.setExtension(
+ optionalImportMessageExtension, ImportMessage.newBuilder().setD(120).build());
+ message.setExtension(
+ optionalPublicImportMessageExtension, PublicImportMessage.newBuilder().setE(126).build());
+ message.setExtension(
+ optionalLazyMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(127).build());
message.setExtension(optionalNestedEnumExtension, TestAllTypes.NestedEnum.BAZ);
message.setExtension(optionalForeignEnumExtension, ForeignEnum.FOREIGN_BAZ);
@@ -1271,32 +1245,32 @@ public final class TestUtil {
// -----------------------------------------------------------------
- message.addExtension(repeatedInt32Extension , 201);
- message.addExtension(repeatedInt64Extension , 202L);
- message.addExtension(repeatedUint32Extension , 203);
- message.addExtension(repeatedUint64Extension , 204L);
- message.addExtension(repeatedSint32Extension , 205);
- message.addExtension(repeatedSint64Extension , 206L);
- message.addExtension(repeatedFixed32Extension , 207);
- message.addExtension(repeatedFixed64Extension , 208L);
+ message.addExtension(repeatedInt32Extension, 201);
+ message.addExtension(repeatedInt64Extension, 202L);
+ message.addExtension(repeatedUint32Extension, 203);
+ message.addExtension(repeatedUint64Extension, 204L);
+ message.addExtension(repeatedSint32Extension, 205);
+ message.addExtension(repeatedSint64Extension, 206L);
+ message.addExtension(repeatedFixed32Extension, 207);
+ message.addExtension(repeatedFixed64Extension, 208L);
message.addExtension(repeatedSfixed32Extension, 209);
message.addExtension(repeatedSfixed64Extension, 210L);
- message.addExtension(repeatedFloatExtension , 211F);
- message.addExtension(repeatedDoubleExtension , 212D);
- message.addExtension(repeatedBoolExtension , true);
- message.addExtension(repeatedStringExtension , "215");
- message.addExtension(repeatedBytesExtension , toBytes("216"));
-
- message.addExtension(repeatedGroupExtension,
- RepeatedGroup_extension.newBuilder().setA(217).build());
- message.addExtension(repeatedNestedMessageExtension,
- TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
- message.addExtension(repeatedForeignMessageExtension,
- ForeignMessage.newBuilder().setC(219).build());
- message.addExtension(repeatedImportMessageExtension,
- ImportMessage.newBuilder().setD(220).build());
- message.addExtension(repeatedLazyMessageExtension,
- TestAllTypes.NestedMessage.newBuilder().setBb(227).build());
+ message.addExtension(repeatedFloatExtension, 211F);
+ message.addExtension(repeatedDoubleExtension, 212D);
+ message.addExtension(repeatedBoolExtension, true);
+ message.addExtension(repeatedStringExtension, "215");
+ message.addExtension(repeatedBytesExtension, toBytes("216"));
+
+ message.addExtension(
+ repeatedGroupExtension, RepeatedGroup_extension.newBuilder().setA(217).build());
+ message.addExtension(
+ repeatedNestedMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
+ message.addExtension(
+ repeatedForeignMessageExtension, ForeignMessage.newBuilder().setC(219).build());
+ message.addExtension(
+ repeatedImportMessageExtension, ImportMessage.newBuilder().setD(220).build());
+ message.addExtension(
+ repeatedLazyMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(227).build());
message.addExtension(repeatedNestedEnumExtension, TestAllTypes.NestedEnum.BAR);
message.addExtension(repeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAR);
@@ -1306,32 +1280,32 @@ public final class TestUtil {
message.addExtension(repeatedCordExtension, "225");
// Add a second one of each field.
- message.addExtension(repeatedInt32Extension , 301);
- message.addExtension(repeatedInt64Extension , 302L);
- message.addExtension(repeatedUint32Extension , 303);
- message.addExtension(repeatedUint64Extension , 304L);
- message.addExtension(repeatedSint32Extension , 305);
- message.addExtension(repeatedSint64Extension , 306L);
- message.addExtension(repeatedFixed32Extension , 307);
- message.addExtension(repeatedFixed64Extension , 308L);
+ message.addExtension(repeatedInt32Extension, 301);
+ message.addExtension(repeatedInt64Extension, 302L);
+ message.addExtension(repeatedUint32Extension, 303);
+ message.addExtension(repeatedUint64Extension, 304L);
+ message.addExtension(repeatedSint32Extension, 305);
+ message.addExtension(repeatedSint64Extension, 306L);
+ message.addExtension(repeatedFixed32Extension, 307);
+ message.addExtension(repeatedFixed64Extension, 308L);
message.addExtension(repeatedSfixed32Extension, 309);
message.addExtension(repeatedSfixed64Extension, 310L);
- message.addExtension(repeatedFloatExtension , 311F);
- message.addExtension(repeatedDoubleExtension , 312D);
- message.addExtension(repeatedBoolExtension , false);
- message.addExtension(repeatedStringExtension , "315");
- message.addExtension(repeatedBytesExtension , toBytes("316"));
-
- message.addExtension(repeatedGroupExtension,
- RepeatedGroup_extension.newBuilder().setA(317).build());
- message.addExtension(repeatedNestedMessageExtension,
- TestAllTypes.NestedMessage.newBuilder().setBb(318).build());
- message.addExtension(repeatedForeignMessageExtension,
- ForeignMessage.newBuilder().setC(319).build());
- message.addExtension(repeatedImportMessageExtension,
- ImportMessage.newBuilder().setD(320).build());
- message.addExtension(repeatedLazyMessageExtension,
- TestAllTypes.NestedMessage.newBuilder().setBb(327).build());
+ message.addExtension(repeatedFloatExtension, 311F);
+ message.addExtension(repeatedDoubleExtension, 312D);
+ message.addExtension(repeatedBoolExtension, false);
+ message.addExtension(repeatedStringExtension, "315");
+ message.addExtension(repeatedBytesExtension, toBytes("316"));
+
+ message.addExtension(
+ repeatedGroupExtension, RepeatedGroup_extension.newBuilder().setA(317).build());
+ message.addExtension(
+ repeatedNestedMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(318).build());
+ message.addExtension(
+ repeatedForeignMessageExtension, ForeignMessage.newBuilder().setC(319).build());
+ message.addExtension(
+ repeatedImportMessageExtension, ImportMessage.newBuilder().setD(320).build());
+ message.addExtension(
+ repeatedLazyMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(327).build());
message.addExtension(repeatedNestedEnumExtension, TestAllTypes.NestedEnum.BAZ);
message.addExtension(repeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAZ);
@@ -1342,21 +1316,21 @@ public final class TestUtil {
// -----------------------------------------------------------------
- message.setExtension(defaultInt32Extension , 401);
- message.setExtension(defaultInt64Extension , 402L);
- message.setExtension(defaultUint32Extension , 403);
- message.setExtension(defaultUint64Extension , 404L);
- message.setExtension(defaultSint32Extension , 405);
- message.setExtension(defaultSint64Extension , 406L);
- message.setExtension(defaultFixed32Extension , 407);
- message.setExtension(defaultFixed64Extension , 408L);
+ message.setExtension(defaultInt32Extension, 401);
+ message.setExtension(defaultInt64Extension, 402L);
+ message.setExtension(defaultUint32Extension, 403);
+ message.setExtension(defaultUint64Extension, 404L);
+ message.setExtension(defaultSint32Extension, 405);
+ message.setExtension(defaultSint64Extension, 406L);
+ message.setExtension(defaultFixed32Extension, 407);
+ message.setExtension(defaultFixed64Extension, 408L);
message.setExtension(defaultSfixed32Extension, 409);
message.setExtension(defaultSfixed64Extension, 410L);
- message.setExtension(defaultFloatExtension , 411F);
- message.setExtension(defaultDoubleExtension , 412D);
- message.setExtension(defaultBoolExtension , false);
- message.setExtension(defaultStringExtension , "415");
- message.setExtension(defaultBytesExtension , toBytes("416"));
+ message.setExtension(defaultFloatExtension, 411F);
+ message.setExtension(defaultDoubleExtension, 412D);
+ message.setExtension(defaultBoolExtension, false);
+ message.setExtension(defaultStringExtension, "415");
+ message.setExtension(defaultBytesExtension, toBytes("416"));
message.setExtension(defaultNestedEnumExtension, TestAllTypes.NestedEnum.FOO);
message.setExtension(defaultForeignEnumExtension, ForeignEnum.FOREIGN_FOO);
@@ -1366,8 +1340,8 @@ public final class TestUtil {
message.setExtension(defaultCordExtension, "425");
message.setExtension(oneofUint32Extension, 601);
- message.setExtension(oneofNestedMessageExtension,
- TestAllTypes.NestedMessage.newBuilder().setBb(602).build());
+ message.setExtension(
+ oneofNestedMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(602).build());
message.setExtension(oneofStringExtension, "603");
message.setExtension(oneofBytesExtension, toBytes("604"));
}
@@ -1375,41 +1349,44 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Modify the repeated extensions of {@code message} to contain the values
- * expected by {@code assertRepeatedExtensionsModified()}.
+ * Modify the repeated extensions of {@code message} to contain the values expected by {@code
+ * assertRepeatedExtensionsModified()}.
*/
- public static void modifyRepeatedExtensions(
- TestAllExtensions.Builder message) {
- message.setExtension(repeatedInt32Extension , 1, 501);
- message.setExtension(repeatedInt64Extension , 1, 502L);
- message.setExtension(repeatedUint32Extension , 1, 503);
- message.setExtension(repeatedUint64Extension , 1, 504L);
- message.setExtension(repeatedSint32Extension , 1, 505);
- message.setExtension(repeatedSint64Extension , 1, 506L);
- message.setExtension(repeatedFixed32Extension , 1, 507);
- message.setExtension(repeatedFixed64Extension , 1, 508L);
+ public static void modifyRepeatedExtensions(TestAllExtensions.Builder message) {
+ message.setExtension(repeatedInt32Extension, 1, 501);
+ message.setExtension(repeatedInt64Extension, 1, 502L);
+ message.setExtension(repeatedUint32Extension, 1, 503);
+ message.setExtension(repeatedUint64Extension, 1, 504L);
+ message.setExtension(repeatedSint32Extension, 1, 505);
+ message.setExtension(repeatedSint64Extension, 1, 506L);
+ message.setExtension(repeatedFixed32Extension, 1, 507);
+ message.setExtension(repeatedFixed64Extension, 1, 508L);
message.setExtension(repeatedSfixed32Extension, 1, 509);
message.setExtension(repeatedSfixed64Extension, 1, 510L);
- message.setExtension(repeatedFloatExtension , 1, 511F);
- message.setExtension(repeatedDoubleExtension , 1, 512D);
- message.setExtension(repeatedBoolExtension , 1, true);
- message.setExtension(repeatedStringExtension , 1, "515");
- message.setExtension(repeatedBytesExtension , 1, toBytes("516"));
-
- message.setExtension(repeatedGroupExtension, 1,
- RepeatedGroup_extension.newBuilder().setA(517).build());
- message.setExtension(repeatedNestedMessageExtension, 1,
- TestAllTypes.NestedMessage.newBuilder().setBb(518).build());
- message.setExtension(repeatedForeignMessageExtension, 1,
- ForeignMessage.newBuilder().setC(519).build());
- message.setExtension(repeatedImportMessageExtension, 1,
- ImportMessage.newBuilder().setD(520).build());
- message.setExtension(repeatedLazyMessageExtension, 1,
- TestAllTypes.NestedMessage.newBuilder().setBb(527).build());
-
- message.setExtension(repeatedNestedEnumExtension , 1, TestAllTypes.NestedEnum.FOO);
+ message.setExtension(repeatedFloatExtension, 1, 511F);
+ message.setExtension(repeatedDoubleExtension, 1, 512D);
+ message.setExtension(repeatedBoolExtension, 1, true);
+ message.setExtension(repeatedStringExtension, 1, "515");
+ message.setExtension(repeatedBytesExtension, 1, toBytes("516"));
+
+ message.setExtension(
+ repeatedGroupExtension, 1, RepeatedGroup_extension.newBuilder().setA(517).build());
+ message.setExtension(
+ repeatedNestedMessageExtension,
+ 1,
+ TestAllTypes.NestedMessage.newBuilder().setBb(518).build());
+ message.setExtension(
+ repeatedForeignMessageExtension, 1, ForeignMessage.newBuilder().setC(519).build());
+ message.setExtension(
+ repeatedImportMessageExtension, 1, ImportMessage.newBuilder().setD(520).build());
+ message.setExtension(
+ repeatedLazyMessageExtension,
+ 1,
+ TestAllTypes.NestedMessage.newBuilder().setBb(527).build());
+
+ message.setExtension(repeatedNestedEnumExtension, 1, TestAllTypes.NestedEnum.FOO);
message.setExtension(repeatedForeignEnumExtension, 1, ForeignEnum.FOREIGN_FOO);
- message.setExtension(repeatedImportEnumExtension , 1, ImportEnum.IMPORT_FOO);
+ message.setExtension(repeatedImportEnumExtension, 1, ImportEnum.IMPORT_FOO);
message.setExtension(repeatedStringPieceExtension, 1, "524");
message.setExtension(repeatedCordExtension, 1, "525");
@@ -1418,218 +1395,215 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all extensions of
- * {@code message} are set to the values assigned by {@code setAllExtensions}.
+ * Assert (using {@code junit.framework.Assert}} that all extensions of {@code message} are set to
+ * the values assigned by {@code setAllExtensions}.
*/
- public static void assertAllExtensionsSet(
- TestAllExtensionsOrBuilder message) {
- Assert.assertTrue(message.hasExtension(optionalInt32Extension ));
- Assert.assertTrue(message.hasExtension(optionalInt64Extension ));
- Assert.assertTrue(message.hasExtension(optionalUint32Extension ));
- Assert.assertTrue(message.hasExtension(optionalUint64Extension ));
- Assert.assertTrue(message.hasExtension(optionalSint32Extension ));
- Assert.assertTrue(message.hasExtension(optionalSint64Extension ));
- Assert.assertTrue(message.hasExtension(optionalFixed32Extension ));
- Assert.assertTrue(message.hasExtension(optionalFixed64Extension ));
+ public static void assertAllExtensionsSet(TestAllExtensionsOrBuilder message) {
+ Assert.assertTrue(message.hasExtension(optionalInt32Extension));
+ Assert.assertTrue(message.hasExtension(optionalInt64Extension));
+ Assert.assertTrue(message.hasExtension(optionalUint32Extension));
+ Assert.assertTrue(message.hasExtension(optionalUint64Extension));
+ Assert.assertTrue(message.hasExtension(optionalSint32Extension));
+ Assert.assertTrue(message.hasExtension(optionalSint64Extension));
+ Assert.assertTrue(message.hasExtension(optionalFixed32Extension));
+ Assert.assertTrue(message.hasExtension(optionalFixed64Extension));
Assert.assertTrue(message.hasExtension(optionalSfixed32Extension));
Assert.assertTrue(message.hasExtension(optionalSfixed64Extension));
- Assert.assertTrue(message.hasExtension(optionalFloatExtension ));
- Assert.assertTrue(message.hasExtension(optionalDoubleExtension ));
- Assert.assertTrue(message.hasExtension(optionalBoolExtension ));
- Assert.assertTrue(message.hasExtension(optionalStringExtension ));
- Assert.assertTrue(message.hasExtension(optionalBytesExtension ));
-
- Assert.assertTrue(message.hasExtension(optionalGroupExtension ));
- Assert.assertTrue(message.hasExtension(optionalNestedMessageExtension ));
+ Assert.assertTrue(message.hasExtension(optionalFloatExtension));
+ Assert.assertTrue(message.hasExtension(optionalDoubleExtension));
+ Assert.assertTrue(message.hasExtension(optionalBoolExtension));
+ Assert.assertTrue(message.hasExtension(optionalStringExtension));
+ Assert.assertTrue(message.hasExtension(optionalBytesExtension));
+
+ Assert.assertTrue(message.hasExtension(optionalGroupExtension));
+ Assert.assertTrue(message.hasExtension(optionalNestedMessageExtension));
Assert.assertTrue(message.hasExtension(optionalForeignMessageExtension));
- Assert.assertTrue(message.hasExtension(optionalImportMessageExtension ));
+ Assert.assertTrue(message.hasExtension(optionalImportMessageExtension));
- Assert.assertTrue(message.getExtension(optionalGroupExtension ).hasA());
- Assert.assertTrue(message.getExtension(optionalNestedMessageExtension ).hasBb());
+ Assert.assertTrue(message.getExtension(optionalGroupExtension).hasA());
+ Assert.assertTrue(message.getExtension(optionalNestedMessageExtension).hasBb());
Assert.assertTrue(message.getExtension(optionalForeignMessageExtension).hasC());
- Assert.assertTrue(message.getExtension(optionalImportMessageExtension ).hasD());
+ Assert.assertTrue(message.getExtension(optionalImportMessageExtension).hasD());
- Assert.assertTrue(message.hasExtension(optionalNestedEnumExtension ));
+ Assert.assertTrue(message.hasExtension(optionalNestedEnumExtension));
Assert.assertTrue(message.hasExtension(optionalForeignEnumExtension));
- Assert.assertTrue(message.hasExtension(optionalImportEnumExtension ));
+ Assert.assertTrue(message.hasExtension(optionalImportEnumExtension));
Assert.assertTrue(message.hasExtension(optionalStringPieceExtension));
Assert.assertTrue(message.hasExtension(optionalCordExtension));
- assertEqualsExactType(101 , message.getExtension(optionalInt32Extension ));
- assertEqualsExactType(102L , message.getExtension(optionalInt64Extension ));
- assertEqualsExactType(103 , message.getExtension(optionalUint32Extension ));
- assertEqualsExactType(104L , message.getExtension(optionalUint64Extension ));
- assertEqualsExactType(105 , message.getExtension(optionalSint32Extension ));
- assertEqualsExactType(106L , message.getExtension(optionalSint64Extension ));
- assertEqualsExactType(107 , message.getExtension(optionalFixed32Extension ));
- assertEqualsExactType(108L , message.getExtension(optionalFixed64Extension ));
- assertEqualsExactType(109 , message.getExtension(optionalSfixed32Extension));
- assertEqualsExactType(110L , message.getExtension(optionalSfixed64Extension));
- assertEqualsExactType(111F , message.getExtension(optionalFloatExtension ));
- assertEqualsExactType(112D , message.getExtension(optionalDoubleExtension ));
- assertEqualsExactType(true , message.getExtension(optionalBoolExtension ));
- assertEqualsExactType("115", message.getExtension(optionalStringExtension ));
+ assertEqualsExactType(101, message.getExtension(optionalInt32Extension));
+ assertEqualsExactType(102L, message.getExtension(optionalInt64Extension));
+ assertEqualsExactType(103, message.getExtension(optionalUint32Extension));
+ assertEqualsExactType(104L, message.getExtension(optionalUint64Extension));
+ assertEqualsExactType(105, message.getExtension(optionalSint32Extension));
+ assertEqualsExactType(106L, message.getExtension(optionalSint64Extension));
+ assertEqualsExactType(107, message.getExtension(optionalFixed32Extension));
+ assertEqualsExactType(108L, message.getExtension(optionalFixed64Extension));
+ assertEqualsExactType(109, message.getExtension(optionalSfixed32Extension));
+ assertEqualsExactType(110L, message.getExtension(optionalSfixed64Extension));
+ assertEqualsExactType(111F, message.getExtension(optionalFloatExtension));
+ assertEqualsExactType(112D, message.getExtension(optionalDoubleExtension));
+ assertEqualsExactType(true, message.getExtension(optionalBoolExtension));
+ assertEqualsExactType("115", message.getExtension(optionalStringExtension));
assertEqualsExactType(toBytes("116"), message.getExtension(optionalBytesExtension));
- assertEqualsExactType(117, message.getExtension(optionalGroupExtension ).getA());
- assertEqualsExactType(118, message.getExtension(optionalNestedMessageExtension ).getBb());
- assertEqualsExactType(119, message.getExtension(optionalForeignMessageExtension ).getC());
- assertEqualsExactType(120, message.getExtension(optionalImportMessageExtension ).getD());
+ assertEqualsExactType(117, message.getExtension(optionalGroupExtension).getA());
+ assertEqualsExactType(118, message.getExtension(optionalNestedMessageExtension).getBb());
+ assertEqualsExactType(119, message.getExtension(optionalForeignMessageExtension).getC());
+ assertEqualsExactType(120, message.getExtension(optionalImportMessageExtension).getD());
assertEqualsExactType(126, message.getExtension(optionalPublicImportMessageExtension).getE());
- assertEqualsExactType(127, message.getExtension(optionalLazyMessageExtension ).getBb());
+ assertEqualsExactType(127, message.getExtension(optionalLazyMessageExtension).getBb());
- assertEqualsExactType(TestAllTypes.NestedEnum.BAZ,
- message.getExtension(optionalNestedEnumExtension));
- assertEqualsExactType(ForeignEnum.FOREIGN_BAZ,
- message.getExtension(optionalForeignEnumExtension));
- assertEqualsExactType(ImportEnum.IMPORT_BAZ,
- message.getExtension(optionalImportEnumExtension));
+ assertEqualsExactType(
+ TestAllTypes.NestedEnum.BAZ, message.getExtension(optionalNestedEnumExtension));
+ assertEqualsExactType(
+ ForeignEnum.FOREIGN_BAZ, message.getExtension(optionalForeignEnumExtension));
+ assertEqualsExactType(ImportEnum.IMPORT_BAZ, message.getExtension(optionalImportEnumExtension));
assertEqualsExactType("124", message.getExtension(optionalStringPieceExtension));
assertEqualsExactType("125", message.getExtension(optionalCordExtension));
// -----------------------------------------------------------------
- Assert.assertEquals(2, message.getExtensionCount(repeatedInt32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedInt64Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedUint32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedUint64Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedSint32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedSint64Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64Extension ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedInt32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedInt64Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedUint32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedUint64Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedSint32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedSint64Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64Extension));
Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed32Extension));
Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed64Extension));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtension ));
-
- Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtension ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtension));
+
+ Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtension));
Assert.assertEquals(2, message.getExtensionCount(repeatedForeignMessageExtension));
- Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtension ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtension));
Assert.assertEquals(2, message.getExtensionCount(repeatedStringPieceExtension));
Assert.assertEquals(2, message.getExtensionCount(repeatedCordExtension));
- assertEqualsExactType(201 , message.getExtension(repeatedInt32Extension , 0));
- assertEqualsExactType(202L , message.getExtension(repeatedInt64Extension , 0));
- assertEqualsExactType(203 , message.getExtension(repeatedUint32Extension , 0));
- assertEqualsExactType(204L , message.getExtension(repeatedUint64Extension , 0));
- assertEqualsExactType(205 , message.getExtension(repeatedSint32Extension , 0));
- assertEqualsExactType(206L , message.getExtension(repeatedSint64Extension , 0));
- assertEqualsExactType(207 , message.getExtension(repeatedFixed32Extension , 0));
- assertEqualsExactType(208L , message.getExtension(repeatedFixed64Extension , 0));
- assertEqualsExactType(209 , message.getExtension(repeatedSfixed32Extension, 0));
- assertEqualsExactType(210L , message.getExtension(repeatedSfixed64Extension, 0));
- assertEqualsExactType(211F , message.getExtension(repeatedFloatExtension , 0));
- assertEqualsExactType(212D , message.getExtension(repeatedDoubleExtension , 0));
- assertEqualsExactType(true , message.getExtension(repeatedBoolExtension , 0));
- assertEqualsExactType("215", message.getExtension(repeatedStringExtension , 0));
+ assertEqualsExactType(201, message.getExtension(repeatedInt32Extension, 0));
+ assertEqualsExactType(202L, message.getExtension(repeatedInt64Extension, 0));
+ assertEqualsExactType(203, message.getExtension(repeatedUint32Extension, 0));
+ assertEqualsExactType(204L, message.getExtension(repeatedUint64Extension, 0));
+ assertEqualsExactType(205, message.getExtension(repeatedSint32Extension, 0));
+ assertEqualsExactType(206L, message.getExtension(repeatedSint64Extension, 0));
+ assertEqualsExactType(207, message.getExtension(repeatedFixed32Extension, 0));
+ assertEqualsExactType(208L, message.getExtension(repeatedFixed64Extension, 0));
+ assertEqualsExactType(209, message.getExtension(repeatedSfixed32Extension, 0));
+ assertEqualsExactType(210L, message.getExtension(repeatedSfixed64Extension, 0));
+ assertEqualsExactType(211F, message.getExtension(repeatedFloatExtension, 0));
+ assertEqualsExactType(212D, message.getExtension(repeatedDoubleExtension, 0));
+ assertEqualsExactType(true, message.getExtension(repeatedBoolExtension, 0));
+ assertEqualsExactType("215", message.getExtension(repeatedStringExtension, 0));
assertEqualsExactType(toBytes("216"), message.getExtension(repeatedBytesExtension, 0));
- assertEqualsExactType(217, message.getExtension(repeatedGroupExtension , 0).getA());
- assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtension , 0).getBb());
+ assertEqualsExactType(217, message.getExtension(repeatedGroupExtension, 0).getA());
+ assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtension, 0).getBb());
assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtension, 0).getC());
- assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtension , 0).getD());
- assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtension , 0).getBb());
+ assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtension, 0).getD());
+ assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtension, 0).getBb());
- assertEqualsExactType(TestAllTypes.NestedEnum.BAR,
- message.getExtension(repeatedNestedEnumExtension, 0));
- assertEqualsExactType(ForeignEnum.FOREIGN_BAR,
- message.getExtension(repeatedForeignEnumExtension, 0));
- assertEqualsExactType(ImportEnum.IMPORT_BAR,
- message.getExtension(repeatedImportEnumExtension, 0));
+ assertEqualsExactType(
+ TestAllTypes.NestedEnum.BAR, message.getExtension(repeatedNestedEnumExtension, 0));
+ assertEqualsExactType(
+ ForeignEnum.FOREIGN_BAR, message.getExtension(repeatedForeignEnumExtension, 0));
+ assertEqualsExactType(
+ ImportEnum.IMPORT_BAR, message.getExtension(repeatedImportEnumExtension, 0));
assertEqualsExactType("224", message.getExtension(repeatedStringPieceExtension, 0));
assertEqualsExactType("225", message.getExtension(repeatedCordExtension, 0));
- assertEqualsExactType(301 , message.getExtension(repeatedInt32Extension , 1));
- assertEqualsExactType(302L , message.getExtension(repeatedInt64Extension , 1));
- assertEqualsExactType(303 , message.getExtension(repeatedUint32Extension , 1));
- assertEqualsExactType(304L , message.getExtension(repeatedUint64Extension , 1));
- assertEqualsExactType(305 , message.getExtension(repeatedSint32Extension , 1));
- assertEqualsExactType(306L , message.getExtension(repeatedSint64Extension , 1));
- assertEqualsExactType(307 , message.getExtension(repeatedFixed32Extension , 1));
- assertEqualsExactType(308L , message.getExtension(repeatedFixed64Extension , 1));
- assertEqualsExactType(309 , message.getExtension(repeatedSfixed32Extension, 1));
- assertEqualsExactType(310L , message.getExtension(repeatedSfixed64Extension, 1));
- assertEqualsExactType(311F , message.getExtension(repeatedFloatExtension , 1));
- assertEqualsExactType(312D , message.getExtension(repeatedDoubleExtension , 1));
- assertEqualsExactType(false, message.getExtension(repeatedBoolExtension , 1));
- assertEqualsExactType("315", message.getExtension(repeatedStringExtension , 1));
+ assertEqualsExactType(301, message.getExtension(repeatedInt32Extension, 1));
+ assertEqualsExactType(302L, message.getExtension(repeatedInt64Extension, 1));
+ assertEqualsExactType(303, message.getExtension(repeatedUint32Extension, 1));
+ assertEqualsExactType(304L, message.getExtension(repeatedUint64Extension, 1));
+ assertEqualsExactType(305, message.getExtension(repeatedSint32Extension, 1));
+ assertEqualsExactType(306L, message.getExtension(repeatedSint64Extension, 1));
+ assertEqualsExactType(307, message.getExtension(repeatedFixed32Extension, 1));
+ assertEqualsExactType(308L, message.getExtension(repeatedFixed64Extension, 1));
+ assertEqualsExactType(309, message.getExtension(repeatedSfixed32Extension, 1));
+ assertEqualsExactType(310L, message.getExtension(repeatedSfixed64Extension, 1));
+ assertEqualsExactType(311F, message.getExtension(repeatedFloatExtension, 1));
+ assertEqualsExactType(312D, message.getExtension(repeatedDoubleExtension, 1));
+ assertEqualsExactType(false, message.getExtension(repeatedBoolExtension, 1));
+ assertEqualsExactType("315", message.getExtension(repeatedStringExtension, 1));
assertEqualsExactType(toBytes("316"), message.getExtension(repeatedBytesExtension, 1));
- assertEqualsExactType(317, message.getExtension(repeatedGroupExtension , 1).getA());
- assertEqualsExactType(318, message.getExtension(repeatedNestedMessageExtension , 1).getBb());
+ assertEqualsExactType(317, message.getExtension(repeatedGroupExtension, 1).getA());
+ assertEqualsExactType(318, message.getExtension(repeatedNestedMessageExtension, 1).getBb());
assertEqualsExactType(319, message.getExtension(repeatedForeignMessageExtension, 1).getC());
- assertEqualsExactType(320, message.getExtension(repeatedImportMessageExtension , 1).getD());
- assertEqualsExactType(327, message.getExtension(repeatedLazyMessageExtension , 1).getBb());
+ assertEqualsExactType(320, message.getExtension(repeatedImportMessageExtension, 1).getD());
+ assertEqualsExactType(327, message.getExtension(repeatedLazyMessageExtension, 1).getBb());
- assertEqualsExactType(TestAllTypes.NestedEnum.BAZ,
- message.getExtension(repeatedNestedEnumExtension, 1));
- assertEqualsExactType(ForeignEnum.FOREIGN_BAZ,
- message.getExtension(repeatedForeignEnumExtension, 1));
- assertEqualsExactType(ImportEnum.IMPORT_BAZ,
- message.getExtension(repeatedImportEnumExtension, 1));
+ assertEqualsExactType(
+ TestAllTypes.NestedEnum.BAZ, message.getExtension(repeatedNestedEnumExtension, 1));
+ assertEqualsExactType(
+ ForeignEnum.FOREIGN_BAZ, message.getExtension(repeatedForeignEnumExtension, 1));
+ assertEqualsExactType(
+ ImportEnum.IMPORT_BAZ, message.getExtension(repeatedImportEnumExtension, 1));
assertEqualsExactType("324", message.getExtension(repeatedStringPieceExtension, 1));
assertEqualsExactType("325", message.getExtension(repeatedCordExtension, 1));
// -----------------------------------------------------------------
- Assert.assertTrue(message.hasExtension(defaultInt32Extension ));
- Assert.assertTrue(message.hasExtension(defaultInt64Extension ));
- Assert.assertTrue(message.hasExtension(defaultUint32Extension ));
- Assert.assertTrue(message.hasExtension(defaultUint64Extension ));
- Assert.assertTrue(message.hasExtension(defaultSint32Extension ));
- Assert.assertTrue(message.hasExtension(defaultSint64Extension ));
- Assert.assertTrue(message.hasExtension(defaultFixed32Extension ));
- Assert.assertTrue(message.hasExtension(defaultFixed64Extension ));
+ Assert.assertTrue(message.hasExtension(defaultInt32Extension));
+ Assert.assertTrue(message.hasExtension(defaultInt64Extension));
+ Assert.assertTrue(message.hasExtension(defaultUint32Extension));
+ Assert.assertTrue(message.hasExtension(defaultUint64Extension));
+ Assert.assertTrue(message.hasExtension(defaultSint32Extension));
+ Assert.assertTrue(message.hasExtension(defaultSint64Extension));
+ Assert.assertTrue(message.hasExtension(defaultFixed32Extension));
+ Assert.assertTrue(message.hasExtension(defaultFixed64Extension));
Assert.assertTrue(message.hasExtension(defaultSfixed32Extension));
Assert.assertTrue(message.hasExtension(defaultSfixed64Extension));
- Assert.assertTrue(message.hasExtension(defaultFloatExtension ));
- Assert.assertTrue(message.hasExtension(defaultDoubleExtension ));
- Assert.assertTrue(message.hasExtension(defaultBoolExtension ));
- Assert.assertTrue(message.hasExtension(defaultStringExtension ));
- Assert.assertTrue(message.hasExtension(defaultBytesExtension ));
+ Assert.assertTrue(message.hasExtension(defaultFloatExtension));
+ Assert.assertTrue(message.hasExtension(defaultDoubleExtension));
+ Assert.assertTrue(message.hasExtension(defaultBoolExtension));
+ Assert.assertTrue(message.hasExtension(defaultStringExtension));
+ Assert.assertTrue(message.hasExtension(defaultBytesExtension));
- Assert.assertTrue(message.hasExtension(defaultNestedEnumExtension ));
+ Assert.assertTrue(message.hasExtension(defaultNestedEnumExtension));
Assert.assertTrue(message.hasExtension(defaultForeignEnumExtension));
- Assert.assertTrue(message.hasExtension(defaultImportEnumExtension ));
+ Assert.assertTrue(message.hasExtension(defaultImportEnumExtension));
Assert.assertTrue(message.hasExtension(defaultStringPieceExtension));
Assert.assertTrue(message.hasExtension(defaultCordExtension));
- assertEqualsExactType(401 , message.getExtension(defaultInt32Extension ));
- assertEqualsExactType(402L , message.getExtension(defaultInt64Extension ));
- assertEqualsExactType(403 , message.getExtension(defaultUint32Extension ));
- assertEqualsExactType(404L , message.getExtension(defaultUint64Extension ));
- assertEqualsExactType(405 , message.getExtension(defaultSint32Extension ));
- assertEqualsExactType(406L , message.getExtension(defaultSint64Extension ));
- assertEqualsExactType(407 , message.getExtension(defaultFixed32Extension ));
- assertEqualsExactType(408L , message.getExtension(defaultFixed64Extension ));
- assertEqualsExactType(409 , message.getExtension(defaultSfixed32Extension));
- assertEqualsExactType(410L , message.getExtension(defaultSfixed64Extension));
- assertEqualsExactType(411F , message.getExtension(defaultFloatExtension ));
- assertEqualsExactType(412D , message.getExtension(defaultDoubleExtension ));
- assertEqualsExactType(false, message.getExtension(defaultBoolExtension ));
- assertEqualsExactType("415", message.getExtension(defaultStringExtension ));
+ assertEqualsExactType(401, message.getExtension(defaultInt32Extension));
+ assertEqualsExactType(402L, message.getExtension(defaultInt64Extension));
+ assertEqualsExactType(403, message.getExtension(defaultUint32Extension));
+ assertEqualsExactType(404L, message.getExtension(defaultUint64Extension));
+ assertEqualsExactType(405, message.getExtension(defaultSint32Extension));
+ assertEqualsExactType(406L, message.getExtension(defaultSint64Extension));
+ assertEqualsExactType(407, message.getExtension(defaultFixed32Extension));
+ assertEqualsExactType(408L, message.getExtension(defaultFixed64Extension));
+ assertEqualsExactType(409, message.getExtension(defaultSfixed32Extension));
+ assertEqualsExactType(410L, message.getExtension(defaultSfixed64Extension));
+ assertEqualsExactType(411F, message.getExtension(defaultFloatExtension));
+ assertEqualsExactType(412D, message.getExtension(defaultDoubleExtension));
+ assertEqualsExactType(false, message.getExtension(defaultBoolExtension));
+ assertEqualsExactType("415", message.getExtension(defaultStringExtension));
assertEqualsExactType(toBytes("416"), message.getExtension(defaultBytesExtension));
- assertEqualsExactType(TestAllTypes.NestedEnum.FOO,
- message.getExtension(defaultNestedEnumExtension ));
- assertEqualsExactType(ForeignEnum.FOREIGN_FOO,
- message.getExtension(defaultForeignEnumExtension));
- assertEqualsExactType(ImportEnum.IMPORT_FOO,
- message.getExtension(defaultImportEnumExtension));
+ assertEqualsExactType(
+ TestAllTypes.NestedEnum.FOO, message.getExtension(defaultNestedEnumExtension));
+ assertEqualsExactType(
+ ForeignEnum.FOREIGN_FOO, message.getExtension(defaultForeignEnumExtension));
+ assertEqualsExactType(ImportEnum.IMPORT_FOO, message.getExtension(defaultImportEnumExtension));
assertEqualsExactType("424", message.getExtension(defaultStringPieceExtension));
assertEqualsExactType("425", message.getExtension(defaultCordExtension));
@@ -1642,184 +1616,181 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all extensions of
- * {@code message} are cleared, and that getting the extensions returns their
- * default values.
+ * Assert (using {@code junit.framework.Assert}} that all extensions of {@code message} are
+ * cleared, and that getting the extensions returns their default values.
*/
public static void assertExtensionsClear(TestAllExtensionsOrBuilder message) {
// hasBlah() should initially be false for all optional fields.
- Assert.assertFalse(message.hasExtension(optionalInt32Extension ));
- Assert.assertFalse(message.hasExtension(optionalInt64Extension ));
- Assert.assertFalse(message.hasExtension(optionalUint32Extension ));
- Assert.assertFalse(message.hasExtension(optionalUint64Extension ));
- Assert.assertFalse(message.hasExtension(optionalSint32Extension ));
- Assert.assertFalse(message.hasExtension(optionalSint64Extension ));
- Assert.assertFalse(message.hasExtension(optionalFixed32Extension ));
- Assert.assertFalse(message.hasExtension(optionalFixed64Extension ));
+ Assert.assertFalse(message.hasExtension(optionalInt32Extension));
+ Assert.assertFalse(message.hasExtension(optionalInt64Extension));
+ Assert.assertFalse(message.hasExtension(optionalUint32Extension));
+ Assert.assertFalse(message.hasExtension(optionalUint64Extension));
+ Assert.assertFalse(message.hasExtension(optionalSint32Extension));
+ Assert.assertFalse(message.hasExtension(optionalSint64Extension));
+ Assert.assertFalse(message.hasExtension(optionalFixed32Extension));
+ Assert.assertFalse(message.hasExtension(optionalFixed64Extension));
Assert.assertFalse(message.hasExtension(optionalSfixed32Extension));
Assert.assertFalse(message.hasExtension(optionalSfixed64Extension));
- Assert.assertFalse(message.hasExtension(optionalFloatExtension ));
- Assert.assertFalse(message.hasExtension(optionalDoubleExtension ));
- Assert.assertFalse(message.hasExtension(optionalBoolExtension ));
- Assert.assertFalse(message.hasExtension(optionalStringExtension ));
- Assert.assertFalse(message.hasExtension(optionalBytesExtension ));
-
- Assert.assertFalse(message.hasExtension(optionalGroupExtension ));
- Assert.assertFalse(message.hasExtension(optionalNestedMessageExtension ));
+ Assert.assertFalse(message.hasExtension(optionalFloatExtension));
+ Assert.assertFalse(message.hasExtension(optionalDoubleExtension));
+ Assert.assertFalse(message.hasExtension(optionalBoolExtension));
+ Assert.assertFalse(message.hasExtension(optionalStringExtension));
+ Assert.assertFalse(message.hasExtension(optionalBytesExtension));
+
+ Assert.assertFalse(message.hasExtension(optionalGroupExtension));
+ Assert.assertFalse(message.hasExtension(optionalNestedMessageExtension));
Assert.assertFalse(message.hasExtension(optionalForeignMessageExtension));
- Assert.assertFalse(message.hasExtension(optionalImportMessageExtension ));
+ Assert.assertFalse(message.hasExtension(optionalImportMessageExtension));
- Assert.assertFalse(message.hasExtension(optionalNestedEnumExtension ));
+ Assert.assertFalse(message.hasExtension(optionalNestedEnumExtension));
Assert.assertFalse(message.hasExtension(optionalForeignEnumExtension));
- Assert.assertFalse(message.hasExtension(optionalImportEnumExtension ));
+ Assert.assertFalse(message.hasExtension(optionalImportEnumExtension));
Assert.assertFalse(message.hasExtension(optionalStringPieceExtension));
Assert.assertFalse(message.hasExtension(optionalCordExtension));
// Optional fields without defaults are set to zero or something like it.
- assertEqualsExactType(0 , message.getExtension(optionalInt32Extension ));
- assertEqualsExactType(0L , message.getExtension(optionalInt64Extension ));
- assertEqualsExactType(0 , message.getExtension(optionalUint32Extension ));
- assertEqualsExactType(0L , message.getExtension(optionalUint64Extension ));
- assertEqualsExactType(0 , message.getExtension(optionalSint32Extension ));
- assertEqualsExactType(0L , message.getExtension(optionalSint64Extension ));
- assertEqualsExactType(0 , message.getExtension(optionalFixed32Extension ));
- assertEqualsExactType(0L , message.getExtension(optionalFixed64Extension ));
- assertEqualsExactType(0 , message.getExtension(optionalSfixed32Extension));
- assertEqualsExactType(0L , message.getExtension(optionalSfixed64Extension));
- assertEqualsExactType(0F , message.getExtension(optionalFloatExtension ));
- assertEqualsExactType(0D , message.getExtension(optionalDoubleExtension ));
- assertEqualsExactType(false, message.getExtension(optionalBoolExtension ));
- assertEqualsExactType("" , message.getExtension(optionalStringExtension ));
+ assertEqualsExactType(0, message.getExtension(optionalInt32Extension));
+ assertEqualsExactType(0L, message.getExtension(optionalInt64Extension));
+ assertEqualsExactType(0, message.getExtension(optionalUint32Extension));
+ assertEqualsExactType(0L, message.getExtension(optionalUint64Extension));
+ assertEqualsExactType(0, message.getExtension(optionalSint32Extension));
+ assertEqualsExactType(0L, message.getExtension(optionalSint64Extension));
+ assertEqualsExactType(0, message.getExtension(optionalFixed32Extension));
+ assertEqualsExactType(0L, message.getExtension(optionalFixed64Extension));
+ assertEqualsExactType(0, message.getExtension(optionalSfixed32Extension));
+ assertEqualsExactType(0L, message.getExtension(optionalSfixed64Extension));
+ assertEqualsExactType(0F, message.getExtension(optionalFloatExtension));
+ assertEqualsExactType(0D, message.getExtension(optionalDoubleExtension));
+ assertEqualsExactType(false, message.getExtension(optionalBoolExtension));
+ assertEqualsExactType("", message.getExtension(optionalStringExtension));
assertEqualsExactType(ByteString.EMPTY, message.getExtension(optionalBytesExtension));
// Embedded messages should also be clear.
- Assert.assertFalse(message.getExtension(optionalGroupExtension ).hasA());
- Assert.assertFalse(message.getExtension(optionalNestedMessageExtension ).hasBb());
+ Assert.assertFalse(message.getExtension(optionalGroupExtension).hasA());
+ Assert.assertFalse(message.getExtension(optionalNestedMessageExtension).hasBb());
Assert.assertFalse(message.getExtension(optionalForeignMessageExtension).hasC());
- Assert.assertFalse(message.getExtension(optionalImportMessageExtension ).hasD());
+ Assert.assertFalse(message.getExtension(optionalImportMessageExtension).hasD());
- assertEqualsExactType(0, message.getExtension(optionalGroupExtension ).getA());
- assertEqualsExactType(0, message.getExtension(optionalNestedMessageExtension ).getBb());
+ assertEqualsExactType(0, message.getExtension(optionalGroupExtension).getA());
+ assertEqualsExactType(0, message.getExtension(optionalNestedMessageExtension).getBb());
assertEqualsExactType(0, message.getExtension(optionalForeignMessageExtension).getC());
- assertEqualsExactType(0, message.getExtension(optionalImportMessageExtension ).getD());
+ assertEqualsExactType(0, message.getExtension(optionalImportMessageExtension).getD());
// Enums without defaults are set to the first value in the enum.
- assertEqualsExactType(TestAllTypes.NestedEnum.FOO,
- message.getExtension(optionalNestedEnumExtension ));
- assertEqualsExactType(ForeignEnum.FOREIGN_FOO,
- message.getExtension(optionalForeignEnumExtension));
- assertEqualsExactType(ImportEnum.IMPORT_FOO,
- message.getExtension(optionalImportEnumExtension));
+ assertEqualsExactType(
+ TestAllTypes.NestedEnum.FOO, message.getExtension(optionalNestedEnumExtension));
+ assertEqualsExactType(
+ ForeignEnum.FOREIGN_FOO, message.getExtension(optionalForeignEnumExtension));
+ assertEqualsExactType(ImportEnum.IMPORT_FOO, message.getExtension(optionalImportEnumExtension));
assertEqualsExactType("", message.getExtension(optionalStringPieceExtension));
assertEqualsExactType("", message.getExtension(optionalCordExtension));
// Repeated fields are empty.
- Assert.assertEquals(0, message.getExtensionCount(repeatedInt32Extension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedInt64Extension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedUint32Extension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedUint64Extension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedSint32Extension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedSint64Extension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedFixed32Extension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedFixed64Extension ));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedInt32Extension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedInt64Extension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedUint32Extension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedUint64Extension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedSint32Extension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedSint64Extension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedFixed32Extension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedFixed64Extension));
Assert.assertEquals(0, message.getExtensionCount(repeatedSfixed32Extension));
Assert.assertEquals(0, message.getExtensionCount(repeatedSfixed64Extension));
- Assert.assertEquals(0, message.getExtensionCount(repeatedFloatExtension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedDoubleExtension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedBoolExtension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedStringExtension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedBytesExtension ));
-
- Assert.assertEquals(0, message.getExtensionCount(repeatedGroupExtension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedNestedMessageExtension ));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedFloatExtension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedDoubleExtension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedBoolExtension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedStringExtension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedBytesExtension));
+
+ Assert.assertEquals(0, message.getExtensionCount(repeatedGroupExtension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedNestedMessageExtension));
Assert.assertEquals(0, message.getExtensionCount(repeatedForeignMessageExtension));
- Assert.assertEquals(0, message.getExtensionCount(repeatedImportMessageExtension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedLazyMessageExtension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedNestedEnumExtension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedForeignEnumExtension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedImportEnumExtension ));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedImportMessageExtension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedLazyMessageExtension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedNestedEnumExtension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedForeignEnumExtension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedImportEnumExtension));
Assert.assertEquals(0, message.getExtensionCount(repeatedStringPieceExtension));
Assert.assertEquals(0, message.getExtensionCount(repeatedCordExtension));
// Repeated fields are empty via getExtension().size().
- Assert.assertEquals(0, message.getExtension(repeatedInt32Extension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedInt64Extension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedUint32Extension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedUint64Extension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedSint32Extension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedSint64Extension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedFixed32Extension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedFixed64Extension ).size());
+ Assert.assertEquals(0, message.getExtension(repeatedInt32Extension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedInt64Extension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedUint32Extension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedUint64Extension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedSint32Extension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedSint64Extension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedFixed32Extension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedFixed64Extension).size());
Assert.assertEquals(0, message.getExtension(repeatedSfixed32Extension).size());
Assert.assertEquals(0, message.getExtension(repeatedSfixed64Extension).size());
- Assert.assertEquals(0, message.getExtension(repeatedFloatExtension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedDoubleExtension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedBoolExtension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedStringExtension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedBytesExtension ).size());
-
- Assert.assertEquals(0, message.getExtension(repeatedGroupExtension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedNestedMessageExtension ).size());
+ Assert.assertEquals(0, message.getExtension(repeatedFloatExtension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedDoubleExtension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedBoolExtension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedStringExtension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedBytesExtension).size());
+
+ Assert.assertEquals(0, message.getExtension(repeatedGroupExtension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedNestedMessageExtension).size());
Assert.assertEquals(0, message.getExtension(repeatedForeignMessageExtension).size());
- Assert.assertEquals(0, message.getExtension(repeatedImportMessageExtension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedLazyMessageExtension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedNestedEnumExtension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedForeignEnumExtension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedImportEnumExtension ).size());
+ Assert.assertEquals(0, message.getExtension(repeatedImportMessageExtension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedLazyMessageExtension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedNestedEnumExtension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedForeignEnumExtension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedImportEnumExtension).size());
Assert.assertEquals(0, message.getExtension(repeatedStringPieceExtension).size());
Assert.assertEquals(0, message.getExtension(repeatedCordExtension).size());
// hasBlah() should also be false for all default fields.
- Assert.assertFalse(message.hasExtension(defaultInt32Extension ));
- Assert.assertFalse(message.hasExtension(defaultInt64Extension ));
- Assert.assertFalse(message.hasExtension(defaultUint32Extension ));
- Assert.assertFalse(message.hasExtension(defaultUint64Extension ));
- Assert.assertFalse(message.hasExtension(defaultSint32Extension ));
- Assert.assertFalse(message.hasExtension(defaultSint64Extension ));
- Assert.assertFalse(message.hasExtension(defaultFixed32Extension ));
- Assert.assertFalse(message.hasExtension(defaultFixed64Extension ));
+ Assert.assertFalse(message.hasExtension(defaultInt32Extension));
+ Assert.assertFalse(message.hasExtension(defaultInt64Extension));
+ Assert.assertFalse(message.hasExtension(defaultUint32Extension));
+ Assert.assertFalse(message.hasExtension(defaultUint64Extension));
+ Assert.assertFalse(message.hasExtension(defaultSint32Extension));
+ Assert.assertFalse(message.hasExtension(defaultSint64Extension));
+ Assert.assertFalse(message.hasExtension(defaultFixed32Extension));
+ Assert.assertFalse(message.hasExtension(defaultFixed64Extension));
Assert.assertFalse(message.hasExtension(defaultSfixed32Extension));
Assert.assertFalse(message.hasExtension(defaultSfixed64Extension));
- Assert.assertFalse(message.hasExtension(defaultFloatExtension ));
- Assert.assertFalse(message.hasExtension(defaultDoubleExtension ));
- Assert.assertFalse(message.hasExtension(defaultBoolExtension ));
- Assert.assertFalse(message.hasExtension(defaultStringExtension ));
- Assert.assertFalse(message.hasExtension(defaultBytesExtension ));
+ Assert.assertFalse(message.hasExtension(defaultFloatExtension));
+ Assert.assertFalse(message.hasExtension(defaultDoubleExtension));
+ Assert.assertFalse(message.hasExtension(defaultBoolExtension));
+ Assert.assertFalse(message.hasExtension(defaultStringExtension));
+ Assert.assertFalse(message.hasExtension(defaultBytesExtension));
- Assert.assertFalse(message.hasExtension(defaultNestedEnumExtension ));
+ Assert.assertFalse(message.hasExtension(defaultNestedEnumExtension));
Assert.assertFalse(message.hasExtension(defaultForeignEnumExtension));
- Assert.assertFalse(message.hasExtension(defaultImportEnumExtension ));
+ Assert.assertFalse(message.hasExtension(defaultImportEnumExtension));
Assert.assertFalse(message.hasExtension(defaultStringPieceExtension));
Assert.assertFalse(message.hasExtension(defaultCordExtension));
// Fields with defaults have their default values (duh).
- assertEqualsExactType( 41 , message.getExtension(defaultInt32Extension ));
- assertEqualsExactType( 42L , message.getExtension(defaultInt64Extension ));
- assertEqualsExactType( 43 , message.getExtension(defaultUint32Extension ));
- assertEqualsExactType( 44L , message.getExtension(defaultUint64Extension ));
- assertEqualsExactType(-45 , message.getExtension(defaultSint32Extension ));
- assertEqualsExactType( 46L , message.getExtension(defaultSint64Extension ));
- assertEqualsExactType( 47 , message.getExtension(defaultFixed32Extension ));
- assertEqualsExactType( 48L , message.getExtension(defaultFixed64Extension ));
- assertEqualsExactType( 49 , message.getExtension(defaultSfixed32Extension));
- assertEqualsExactType(-50L , message.getExtension(defaultSfixed64Extension));
- assertEqualsExactType( 51.5F , message.getExtension(defaultFloatExtension ));
- assertEqualsExactType( 52e3D , message.getExtension(defaultDoubleExtension ));
- assertEqualsExactType(true , message.getExtension(defaultBoolExtension ));
- assertEqualsExactType("hello", message.getExtension(defaultStringExtension ));
+ assertEqualsExactType(41, message.getExtension(defaultInt32Extension));
+ assertEqualsExactType(42L, message.getExtension(defaultInt64Extension));
+ assertEqualsExactType(43, message.getExtension(defaultUint32Extension));
+ assertEqualsExactType(44L, message.getExtension(defaultUint64Extension));
+ assertEqualsExactType(-45, message.getExtension(defaultSint32Extension));
+ assertEqualsExactType(46L, message.getExtension(defaultSint64Extension));
+ assertEqualsExactType(47, message.getExtension(defaultFixed32Extension));
+ assertEqualsExactType(48L, message.getExtension(defaultFixed64Extension));
+ assertEqualsExactType(49, message.getExtension(defaultSfixed32Extension));
+ assertEqualsExactType(-50L, message.getExtension(defaultSfixed64Extension));
+ assertEqualsExactType(51.5F, message.getExtension(defaultFloatExtension));
+ assertEqualsExactType(52e3D, message.getExtension(defaultDoubleExtension));
+ assertEqualsExactType(true, message.getExtension(defaultBoolExtension));
+ assertEqualsExactType("hello", message.getExtension(defaultStringExtension));
assertEqualsExactType(toBytes("world"), message.getExtension(defaultBytesExtension));
- assertEqualsExactType(TestAllTypes.NestedEnum.BAR,
- message.getExtension(defaultNestedEnumExtension ));
- assertEqualsExactType(ForeignEnum.FOREIGN_BAR,
- message.getExtension(defaultForeignEnumExtension));
- assertEqualsExactType(ImportEnum.IMPORT_BAR,
- message.getExtension(defaultImportEnumExtension));
+ assertEqualsExactType(
+ TestAllTypes.NestedEnum.BAR, message.getExtension(defaultNestedEnumExtension));
+ assertEqualsExactType(
+ ForeignEnum.FOREIGN_BAR, message.getExtension(defaultForeignEnumExtension));
+ assertEqualsExactType(ImportEnum.IMPORT_BAR, message.getExtension(defaultImportEnumExtension));
assertEqualsExactType("abc", message.getExtension(defaultStringPieceExtension));
assertEqualsExactType("123", message.getExtension(defaultCordExtension));
@@ -1833,405 +1804,402 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all extensions of
- * {@code message} are set to the values assigned by {@code setAllExtensions}
- * followed by {@code modifyRepeatedExtensions}.
+ * Assert (using {@code junit.framework.Assert}} that all extensions of {@code message} are set to
+ * the values assigned by {@code setAllExtensions} followed by {@code modifyRepeatedExtensions}.
*/
- public static void assertRepeatedExtensionsModified(
- TestAllExtensionsOrBuilder message) {
+ public static void assertRepeatedExtensionsModified(TestAllExtensionsOrBuilder message) {
// ModifyRepeatedFields only sets the second repeated element of each
// field. In addition to verifying this, we also verify that the first
// element and size were *not* modified.
- Assert.assertEquals(2, message.getExtensionCount(repeatedInt32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedInt64Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedUint32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedUint64Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedSint32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedSint64Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64Extension ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedInt32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedInt64Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedUint32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedUint64Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedSint32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedSint64Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64Extension));
Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed32Extension));
Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed64Extension));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtension ));
-
- Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtension ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtension));
+
+ Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtension));
Assert.assertEquals(2, message.getExtensionCount(repeatedForeignMessageExtension));
- Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtension ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtension));
Assert.assertEquals(2, message.getExtensionCount(repeatedStringPieceExtension));
Assert.assertEquals(2, message.getExtensionCount(repeatedCordExtension));
- assertEqualsExactType(201 , message.getExtension(repeatedInt32Extension , 0));
- assertEqualsExactType(202L , message.getExtension(repeatedInt64Extension , 0));
- assertEqualsExactType(203 , message.getExtension(repeatedUint32Extension , 0));
- assertEqualsExactType(204L , message.getExtension(repeatedUint64Extension , 0));
- assertEqualsExactType(205 , message.getExtension(repeatedSint32Extension , 0));
- assertEqualsExactType(206L , message.getExtension(repeatedSint64Extension , 0));
- assertEqualsExactType(207 , message.getExtension(repeatedFixed32Extension , 0));
- assertEqualsExactType(208L , message.getExtension(repeatedFixed64Extension , 0));
- assertEqualsExactType(209 , message.getExtension(repeatedSfixed32Extension, 0));
- assertEqualsExactType(210L , message.getExtension(repeatedSfixed64Extension, 0));
- assertEqualsExactType(211F , message.getExtension(repeatedFloatExtension , 0));
- assertEqualsExactType(212D , message.getExtension(repeatedDoubleExtension , 0));
- assertEqualsExactType(true , message.getExtension(repeatedBoolExtension , 0));
- assertEqualsExactType("215", message.getExtension(repeatedStringExtension , 0));
+ assertEqualsExactType(201, message.getExtension(repeatedInt32Extension, 0));
+ assertEqualsExactType(202L, message.getExtension(repeatedInt64Extension, 0));
+ assertEqualsExactType(203, message.getExtension(repeatedUint32Extension, 0));
+ assertEqualsExactType(204L, message.getExtension(repeatedUint64Extension, 0));
+ assertEqualsExactType(205, message.getExtension(repeatedSint32Extension, 0));
+ assertEqualsExactType(206L, message.getExtension(repeatedSint64Extension, 0));
+ assertEqualsExactType(207, message.getExtension(repeatedFixed32Extension, 0));
+ assertEqualsExactType(208L, message.getExtension(repeatedFixed64Extension, 0));
+ assertEqualsExactType(209, message.getExtension(repeatedSfixed32Extension, 0));
+ assertEqualsExactType(210L, message.getExtension(repeatedSfixed64Extension, 0));
+ assertEqualsExactType(211F, message.getExtension(repeatedFloatExtension, 0));
+ assertEqualsExactType(212D, message.getExtension(repeatedDoubleExtension, 0));
+ assertEqualsExactType(true, message.getExtension(repeatedBoolExtension, 0));
+ assertEqualsExactType("215", message.getExtension(repeatedStringExtension, 0));
assertEqualsExactType(toBytes("216"), message.getExtension(repeatedBytesExtension, 0));
- assertEqualsExactType(217, message.getExtension(repeatedGroupExtension , 0).getA());
- assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtension , 0).getBb());
+ assertEqualsExactType(217, message.getExtension(repeatedGroupExtension, 0).getA());
+ assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtension, 0).getBb());
assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtension, 0).getC());
- assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtension , 0).getD());
- assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtension , 0).getBb());
+ assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtension, 0).getD());
+ assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtension, 0).getBb());
- assertEqualsExactType(TestAllTypes.NestedEnum.BAR,
- message.getExtension(repeatedNestedEnumExtension, 0));
- assertEqualsExactType(ForeignEnum.FOREIGN_BAR,
- message.getExtension(repeatedForeignEnumExtension, 0));
- assertEqualsExactType(ImportEnum.IMPORT_BAR,
- message.getExtension(repeatedImportEnumExtension, 0));
+ assertEqualsExactType(
+ TestAllTypes.NestedEnum.BAR, message.getExtension(repeatedNestedEnumExtension, 0));
+ assertEqualsExactType(
+ ForeignEnum.FOREIGN_BAR, message.getExtension(repeatedForeignEnumExtension, 0));
+ assertEqualsExactType(
+ ImportEnum.IMPORT_BAR, message.getExtension(repeatedImportEnumExtension, 0));
assertEqualsExactType("224", message.getExtension(repeatedStringPieceExtension, 0));
assertEqualsExactType("225", message.getExtension(repeatedCordExtension, 0));
// Actually verify the second (modified) elements now.
- assertEqualsExactType(501 , message.getExtension(repeatedInt32Extension , 1));
- assertEqualsExactType(502L , message.getExtension(repeatedInt64Extension , 1));
- assertEqualsExactType(503 , message.getExtension(repeatedUint32Extension , 1));
- assertEqualsExactType(504L , message.getExtension(repeatedUint64Extension , 1));
- assertEqualsExactType(505 , message.getExtension(repeatedSint32Extension , 1));
- assertEqualsExactType(506L , message.getExtension(repeatedSint64Extension , 1));
- assertEqualsExactType(507 , message.getExtension(repeatedFixed32Extension , 1));
- assertEqualsExactType(508L , message.getExtension(repeatedFixed64Extension , 1));
- assertEqualsExactType(509 , message.getExtension(repeatedSfixed32Extension, 1));
- assertEqualsExactType(510L , message.getExtension(repeatedSfixed64Extension, 1));
- assertEqualsExactType(511F , message.getExtension(repeatedFloatExtension , 1));
- assertEqualsExactType(512D , message.getExtension(repeatedDoubleExtension , 1));
- assertEqualsExactType(true , message.getExtension(repeatedBoolExtension , 1));
- assertEqualsExactType("515", message.getExtension(repeatedStringExtension , 1));
+ assertEqualsExactType(501, message.getExtension(repeatedInt32Extension, 1));
+ assertEqualsExactType(502L, message.getExtension(repeatedInt64Extension, 1));
+ assertEqualsExactType(503, message.getExtension(repeatedUint32Extension, 1));
+ assertEqualsExactType(504L, message.getExtension(repeatedUint64Extension, 1));
+ assertEqualsExactType(505, message.getExtension(repeatedSint32Extension, 1));
+ assertEqualsExactType(506L, message.getExtension(repeatedSint64Extension, 1));
+ assertEqualsExactType(507, message.getExtension(repeatedFixed32Extension, 1));
+ assertEqualsExactType(508L, message.getExtension(repeatedFixed64Extension, 1));
+ assertEqualsExactType(509, message.getExtension(repeatedSfixed32Extension, 1));
+ assertEqualsExactType(510L, message.getExtension(repeatedSfixed64Extension, 1));
+ assertEqualsExactType(511F, message.getExtension(repeatedFloatExtension, 1));
+ assertEqualsExactType(512D, message.getExtension(repeatedDoubleExtension, 1));
+ assertEqualsExactType(true, message.getExtension(repeatedBoolExtension, 1));
+ assertEqualsExactType("515", message.getExtension(repeatedStringExtension, 1));
assertEqualsExactType(toBytes("516"), message.getExtension(repeatedBytesExtension, 1));
- assertEqualsExactType(517, message.getExtension(repeatedGroupExtension , 1).getA());
- assertEqualsExactType(518, message.getExtension(repeatedNestedMessageExtension , 1).getBb());
+ assertEqualsExactType(517, message.getExtension(repeatedGroupExtension, 1).getA());
+ assertEqualsExactType(518, message.getExtension(repeatedNestedMessageExtension, 1).getBb());
assertEqualsExactType(519, message.getExtension(repeatedForeignMessageExtension, 1).getC());
- assertEqualsExactType(520, message.getExtension(repeatedImportMessageExtension , 1).getD());
- assertEqualsExactType(527, message.getExtension(repeatedLazyMessageExtension , 1).getBb());
+ assertEqualsExactType(520, message.getExtension(repeatedImportMessageExtension, 1).getD());
+ assertEqualsExactType(527, message.getExtension(repeatedLazyMessageExtension, 1).getBb());
- assertEqualsExactType(TestAllTypes.NestedEnum.FOO,
- message.getExtension(repeatedNestedEnumExtension, 1));
- assertEqualsExactType(ForeignEnum.FOREIGN_FOO,
- message.getExtension(repeatedForeignEnumExtension, 1));
- assertEqualsExactType(ImportEnum.IMPORT_FOO,
- message.getExtension(repeatedImportEnumExtension, 1));
+ assertEqualsExactType(
+ TestAllTypes.NestedEnum.FOO, message.getExtension(repeatedNestedEnumExtension, 1));
+ assertEqualsExactType(
+ ForeignEnum.FOREIGN_FOO, message.getExtension(repeatedForeignEnumExtension, 1));
+ assertEqualsExactType(
+ ImportEnum.IMPORT_FOO, message.getExtension(repeatedImportEnumExtension, 1));
assertEqualsExactType("524", message.getExtension(repeatedStringPieceExtension, 1));
assertEqualsExactType("525", message.getExtension(repeatedCordExtension, 1));
}
public static void setPackedExtensions(TestPackedExtensions.Builder message) {
- message.addExtension(packedInt32Extension , 601);
- message.addExtension(packedInt64Extension , 602L);
- message.addExtension(packedUint32Extension , 603);
- message.addExtension(packedUint64Extension , 604L);
- message.addExtension(packedSint32Extension , 605);
- message.addExtension(packedSint64Extension , 606L);
- message.addExtension(packedFixed32Extension , 607);
- message.addExtension(packedFixed64Extension , 608L);
+ message.addExtension(packedInt32Extension, 601);
+ message.addExtension(packedInt64Extension, 602L);
+ message.addExtension(packedUint32Extension, 603);
+ message.addExtension(packedUint64Extension, 604L);
+ message.addExtension(packedSint32Extension, 605);
+ message.addExtension(packedSint64Extension, 606L);
+ message.addExtension(packedFixed32Extension, 607);
+ message.addExtension(packedFixed64Extension, 608L);
message.addExtension(packedSfixed32Extension, 609);
message.addExtension(packedSfixed64Extension, 610L);
- message.addExtension(packedFloatExtension , 611F);
- message.addExtension(packedDoubleExtension , 612D);
- message.addExtension(packedBoolExtension , true);
+ message.addExtension(packedFloatExtension, 611F);
+ message.addExtension(packedDoubleExtension, 612D);
+ message.addExtension(packedBoolExtension, true);
message.addExtension(packedEnumExtension, ForeignEnum.FOREIGN_BAR);
// Add a second one of each field.
- message.addExtension(packedInt32Extension , 701);
- message.addExtension(packedInt64Extension , 702L);
- message.addExtension(packedUint32Extension , 703);
- message.addExtension(packedUint64Extension , 704L);
- message.addExtension(packedSint32Extension , 705);
- message.addExtension(packedSint64Extension , 706L);
- message.addExtension(packedFixed32Extension , 707);
- message.addExtension(packedFixed64Extension , 708L);
+ message.addExtension(packedInt32Extension, 701);
+ message.addExtension(packedInt64Extension, 702L);
+ message.addExtension(packedUint32Extension, 703);
+ message.addExtension(packedUint64Extension, 704L);
+ message.addExtension(packedSint32Extension, 705);
+ message.addExtension(packedSint64Extension, 706L);
+ message.addExtension(packedFixed32Extension, 707);
+ message.addExtension(packedFixed64Extension, 708L);
message.addExtension(packedSfixed32Extension, 709);
message.addExtension(packedSfixed64Extension, 710L);
- message.addExtension(packedFloatExtension , 711F);
- message.addExtension(packedDoubleExtension , 712D);
- message.addExtension(packedBoolExtension , false);
+ message.addExtension(packedFloatExtension, 711F);
+ message.addExtension(packedDoubleExtension, 712D);
+ message.addExtension(packedBoolExtension, false);
message.addExtension(packedEnumExtension, ForeignEnum.FOREIGN_BAZ);
}
public static void assertPackedExtensionsSet(TestPackedExtensions message) {
- Assert.assertEquals(2, message.getExtensionCount(packedInt32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(packedInt64Extension ));
- Assert.assertEquals(2, message.getExtensionCount(packedUint32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(packedUint64Extension ));
- Assert.assertEquals(2, message.getExtensionCount(packedSint32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(packedSint64Extension ));
- Assert.assertEquals(2, message.getExtensionCount(packedFixed32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(packedFixed64Extension ));
+ Assert.assertEquals(2, message.getExtensionCount(packedInt32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(packedInt64Extension));
+ Assert.assertEquals(2, message.getExtensionCount(packedUint32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(packedUint64Extension));
+ Assert.assertEquals(2, message.getExtensionCount(packedSint32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(packedSint64Extension));
+ Assert.assertEquals(2, message.getExtensionCount(packedFixed32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(packedFixed64Extension));
Assert.assertEquals(2, message.getExtensionCount(packedSfixed32Extension));
Assert.assertEquals(2, message.getExtensionCount(packedSfixed64Extension));
- Assert.assertEquals(2, message.getExtensionCount(packedFloatExtension ));
- Assert.assertEquals(2, message.getExtensionCount(packedDoubleExtension ));
- Assert.assertEquals(2, message.getExtensionCount(packedBoolExtension ));
+ Assert.assertEquals(2, message.getExtensionCount(packedFloatExtension));
+ Assert.assertEquals(2, message.getExtensionCount(packedDoubleExtension));
+ Assert.assertEquals(2, message.getExtensionCount(packedBoolExtension));
Assert.assertEquals(2, message.getExtensionCount(packedEnumExtension));
- assertEqualsExactType(601 , message.getExtension(packedInt32Extension , 0));
- assertEqualsExactType(602L , message.getExtension(packedInt64Extension , 0));
- assertEqualsExactType(603 , message.getExtension(packedUint32Extension , 0));
- assertEqualsExactType(604L , message.getExtension(packedUint64Extension , 0));
- assertEqualsExactType(605 , message.getExtension(packedSint32Extension , 0));
- assertEqualsExactType(606L , message.getExtension(packedSint64Extension , 0));
- assertEqualsExactType(607 , message.getExtension(packedFixed32Extension , 0));
- assertEqualsExactType(608L , message.getExtension(packedFixed64Extension , 0));
- assertEqualsExactType(609 , message.getExtension(packedSfixed32Extension, 0));
- assertEqualsExactType(610L , message.getExtension(packedSfixed64Extension, 0));
- assertEqualsExactType(611F , message.getExtension(packedFloatExtension , 0));
- assertEqualsExactType(612D , message.getExtension(packedDoubleExtension , 0));
- assertEqualsExactType(true , message.getExtension(packedBoolExtension , 0));
- assertEqualsExactType(ForeignEnum.FOREIGN_BAR,
- message.getExtension(packedEnumExtension, 0));
- assertEqualsExactType(701 , message.getExtension(packedInt32Extension , 1));
- assertEqualsExactType(702L , message.getExtension(packedInt64Extension , 1));
- assertEqualsExactType(703 , message.getExtension(packedUint32Extension , 1));
- assertEqualsExactType(704L , message.getExtension(packedUint64Extension , 1));
- assertEqualsExactType(705 , message.getExtension(packedSint32Extension , 1));
- assertEqualsExactType(706L , message.getExtension(packedSint64Extension , 1));
- assertEqualsExactType(707 , message.getExtension(packedFixed32Extension , 1));
- assertEqualsExactType(708L , message.getExtension(packedFixed64Extension , 1));
- assertEqualsExactType(709 , message.getExtension(packedSfixed32Extension, 1));
- assertEqualsExactType(710L , message.getExtension(packedSfixed64Extension, 1));
- assertEqualsExactType(711F , message.getExtension(packedFloatExtension , 1));
- assertEqualsExactType(712D , message.getExtension(packedDoubleExtension , 1));
- assertEqualsExactType(false, message.getExtension(packedBoolExtension , 1));
- assertEqualsExactType(ForeignEnum.FOREIGN_BAZ,
- message.getExtension(packedEnumExtension, 1));
+ assertEqualsExactType(601, message.getExtension(packedInt32Extension, 0));
+ assertEqualsExactType(602L, message.getExtension(packedInt64Extension, 0));
+ assertEqualsExactType(603, message.getExtension(packedUint32Extension, 0));
+ assertEqualsExactType(604L, message.getExtension(packedUint64Extension, 0));
+ assertEqualsExactType(605, message.getExtension(packedSint32Extension, 0));
+ assertEqualsExactType(606L, message.getExtension(packedSint64Extension, 0));
+ assertEqualsExactType(607, message.getExtension(packedFixed32Extension, 0));
+ assertEqualsExactType(608L, message.getExtension(packedFixed64Extension, 0));
+ assertEqualsExactType(609, message.getExtension(packedSfixed32Extension, 0));
+ assertEqualsExactType(610L, message.getExtension(packedSfixed64Extension, 0));
+ assertEqualsExactType(611F, message.getExtension(packedFloatExtension, 0));
+ assertEqualsExactType(612D, message.getExtension(packedDoubleExtension, 0));
+ assertEqualsExactType(true, message.getExtension(packedBoolExtension, 0));
+ assertEqualsExactType(ForeignEnum.FOREIGN_BAR, message.getExtension(packedEnumExtension, 0));
+ assertEqualsExactType(701, message.getExtension(packedInt32Extension, 1));
+ assertEqualsExactType(702L, message.getExtension(packedInt64Extension, 1));
+ assertEqualsExactType(703, message.getExtension(packedUint32Extension, 1));
+ assertEqualsExactType(704L, message.getExtension(packedUint64Extension, 1));
+ assertEqualsExactType(705, message.getExtension(packedSint32Extension, 1));
+ assertEqualsExactType(706L, message.getExtension(packedSint64Extension, 1));
+ assertEqualsExactType(707, message.getExtension(packedFixed32Extension, 1));
+ assertEqualsExactType(708L, message.getExtension(packedFixed64Extension, 1));
+ assertEqualsExactType(709, message.getExtension(packedSfixed32Extension, 1));
+ assertEqualsExactType(710L, message.getExtension(packedSfixed64Extension, 1));
+ assertEqualsExactType(711F, message.getExtension(packedFloatExtension, 1));
+ assertEqualsExactType(712D, message.getExtension(packedDoubleExtension, 1));
+ assertEqualsExactType(false, message.getExtension(packedBoolExtension, 1));
+ assertEqualsExactType(ForeignEnum.FOREIGN_BAZ, message.getExtension(packedEnumExtension, 1));
}
// ===================================================================
// Lite extensions
/**
- * Assert (using {@code junit.framework.Assert}} that all extensions of
- * {@code message} are set to the values assigned by {@code setAllExtensions}.
+ * Assert (using {@code junit.framework.Assert}} that all extensions of {@code message} are set to
+ * the values assigned by {@code setAllExtensions}.
*/
- public static void assertAllExtensionsSet(
- TestAllExtensionsLiteOrBuilder message) {
- Assert.assertTrue(message.hasExtension(optionalInt32ExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalInt64ExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalUint32ExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalUint64ExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalSint32ExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalSint64ExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalFixed32ExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalFixed64ExtensionLite ));
+ public static void assertAllExtensionsSet(TestAllExtensionsLiteOrBuilder message) {
+ Assert.assertTrue(message.hasExtension(optionalInt32ExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalInt64ExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalUint32ExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalUint64ExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalSint32ExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalSint64ExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalFixed32ExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalFixed64ExtensionLite));
Assert.assertTrue(message.hasExtension(optionalSfixed32ExtensionLite));
Assert.assertTrue(message.hasExtension(optionalSfixed64ExtensionLite));
- Assert.assertTrue(message.hasExtension(optionalFloatExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalDoubleExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalBoolExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalStringExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalBytesExtensionLite ));
-
- Assert.assertTrue(message.hasExtension(optionalGroupExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalNestedMessageExtensionLite ));
+ Assert.assertTrue(message.hasExtension(optionalFloatExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalDoubleExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalBoolExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalStringExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalBytesExtensionLite));
+
+ Assert.assertTrue(message.hasExtension(optionalGroupExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalNestedMessageExtensionLite));
Assert.assertTrue(message.hasExtension(optionalForeignMessageExtensionLite));
- Assert.assertTrue(message.hasExtension(optionalImportMessageExtensionLite ));
+ Assert.assertTrue(message.hasExtension(optionalImportMessageExtensionLite));
- Assert.assertTrue(message.getExtension(optionalGroupExtensionLite ).hasA());
- Assert.assertTrue(message.getExtension(optionalNestedMessageExtensionLite ).hasBb());
+ Assert.assertTrue(message.getExtension(optionalGroupExtensionLite).hasA());
+ Assert.assertTrue(message.getExtension(optionalNestedMessageExtensionLite).hasBb());
Assert.assertTrue(message.getExtension(optionalForeignMessageExtensionLite).hasC());
- Assert.assertTrue(message.getExtension(optionalImportMessageExtensionLite ).hasD());
+ Assert.assertTrue(message.getExtension(optionalImportMessageExtensionLite).hasD());
- Assert.assertTrue(message.hasExtension(optionalNestedEnumExtensionLite ));
+ Assert.assertTrue(message.hasExtension(optionalNestedEnumExtensionLite));
Assert.assertTrue(message.hasExtension(optionalForeignEnumExtensionLite));
- Assert.assertTrue(message.hasExtension(optionalImportEnumExtensionLite ));
+ Assert.assertTrue(message.hasExtension(optionalImportEnumExtensionLite));
Assert.assertTrue(message.hasExtension(optionalStringPieceExtensionLite));
Assert.assertTrue(message.hasExtension(optionalCordExtensionLite));
- assertEqualsExactType(101 , message.getExtension(optionalInt32ExtensionLite ));
- assertEqualsExactType(102L , message.getExtension(optionalInt64ExtensionLite ));
- assertEqualsExactType(103 , message.getExtension(optionalUint32ExtensionLite ));
- assertEqualsExactType(104L , message.getExtension(optionalUint64ExtensionLite ));
- assertEqualsExactType(105 , message.getExtension(optionalSint32ExtensionLite ));
- assertEqualsExactType(106L , message.getExtension(optionalSint64ExtensionLite ));
- assertEqualsExactType(107 , message.getExtension(optionalFixed32ExtensionLite ));
- assertEqualsExactType(108L , message.getExtension(optionalFixed64ExtensionLite ));
- assertEqualsExactType(109 , message.getExtension(optionalSfixed32ExtensionLite));
- assertEqualsExactType(110L , message.getExtension(optionalSfixed64ExtensionLite));
- assertEqualsExactType(111F , message.getExtension(optionalFloatExtensionLite ));
- assertEqualsExactType(112D , message.getExtension(optionalDoubleExtensionLite ));
- assertEqualsExactType(true , message.getExtension(optionalBoolExtensionLite ));
- assertEqualsExactType("115", message.getExtension(optionalStringExtensionLite ));
+ assertEqualsExactType(101, message.getExtension(optionalInt32ExtensionLite));
+ assertEqualsExactType(102L, message.getExtension(optionalInt64ExtensionLite));
+ assertEqualsExactType(103, message.getExtension(optionalUint32ExtensionLite));
+ assertEqualsExactType(104L, message.getExtension(optionalUint64ExtensionLite));
+ assertEqualsExactType(105, message.getExtension(optionalSint32ExtensionLite));
+ assertEqualsExactType(106L, message.getExtension(optionalSint64ExtensionLite));
+ assertEqualsExactType(107, message.getExtension(optionalFixed32ExtensionLite));
+ assertEqualsExactType(108L, message.getExtension(optionalFixed64ExtensionLite));
+ assertEqualsExactType(109, message.getExtension(optionalSfixed32ExtensionLite));
+ assertEqualsExactType(110L, message.getExtension(optionalSfixed64ExtensionLite));
+ assertEqualsExactType(111F, message.getExtension(optionalFloatExtensionLite));
+ assertEqualsExactType(112D, message.getExtension(optionalDoubleExtensionLite));
+ assertEqualsExactType(true, message.getExtension(optionalBoolExtensionLite));
+ assertEqualsExactType("115", message.getExtension(optionalStringExtensionLite));
assertEqualsExactType(toBytes("116"), message.getExtension(optionalBytesExtensionLite));
- assertEqualsExactType(117, message.getExtension(optionalGroupExtensionLite ).getA());
- assertEqualsExactType(118, message.getExtension(optionalNestedMessageExtensionLite ).getBb());
+ assertEqualsExactType(117, message.getExtension(optionalGroupExtensionLite).getA());
+ assertEqualsExactType(118, message.getExtension(optionalNestedMessageExtensionLite).getBb());
assertEqualsExactType(119, message.getExtension(optionalForeignMessageExtensionLite).getC());
- assertEqualsExactType(120, message.getExtension(optionalImportMessageExtensionLite ).getD());
- assertEqualsExactType(126, message.getExtension(
- optionalPublicImportMessageExtensionLite).getE());
+ assertEqualsExactType(120, message.getExtension(optionalImportMessageExtensionLite).getD());
+ assertEqualsExactType(
+ 126, message.getExtension(optionalPublicImportMessageExtensionLite).getE());
assertEqualsExactType(127, message.getExtension(optionalLazyMessageExtensionLite).getBb());
- assertEqualsExactType(TestAllTypesLite.NestedEnum.BAZ,
- message.getExtension(optionalNestedEnumExtensionLite));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAZ,
- message.getExtension(optionalForeignEnumExtensionLite));
- assertEqualsExactType(ImportEnumLite.IMPORT_LITE_BAZ,
- message.getExtension(optionalImportEnumExtensionLite));
+ assertEqualsExactType(
+ TestAllTypesLite.NestedEnum.BAZ, message.getExtension(optionalNestedEnumExtensionLite));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_BAZ, message.getExtension(optionalForeignEnumExtensionLite));
+ assertEqualsExactType(
+ ImportEnumLite.IMPORT_LITE_BAZ, message.getExtension(optionalImportEnumExtensionLite));
assertEqualsExactType("124", message.getExtension(optionalStringPieceExtensionLite));
assertEqualsExactType("125", message.getExtension(optionalCordExtensionLite));
// -----------------------------------------------------------------
- Assert.assertEquals(2, message.getExtensionCount(repeatedInt32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedInt64ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedUint32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedUint64ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedSint32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedSint64ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64ExtensionLite ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedInt32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedInt64ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedUint32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedUint64ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedSint32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedSint64ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64ExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed32ExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed64ExtensionLite));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtensionLite ));
-
- Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtensionLite ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtensionLite));
+
+ Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedForeignMessageExtensionLite));
- Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtensionLite ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedStringPieceExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedCordExtensionLite));
- assertEqualsExactType(201 , message.getExtension(repeatedInt32ExtensionLite , 0));
- assertEqualsExactType(202L , message.getExtension(repeatedInt64ExtensionLite , 0));
- assertEqualsExactType(203 , message.getExtension(repeatedUint32ExtensionLite , 0));
- assertEqualsExactType(204L , message.getExtension(repeatedUint64ExtensionLite , 0));
- assertEqualsExactType(205 , message.getExtension(repeatedSint32ExtensionLite , 0));
- assertEqualsExactType(206L , message.getExtension(repeatedSint64ExtensionLite , 0));
- assertEqualsExactType(207 , message.getExtension(repeatedFixed32ExtensionLite , 0));
- assertEqualsExactType(208L , message.getExtension(repeatedFixed64ExtensionLite , 0));
- assertEqualsExactType(209 , message.getExtension(repeatedSfixed32ExtensionLite, 0));
- assertEqualsExactType(210L , message.getExtension(repeatedSfixed64ExtensionLite, 0));
- assertEqualsExactType(211F , message.getExtension(repeatedFloatExtensionLite , 0));
- assertEqualsExactType(212D , message.getExtension(repeatedDoubleExtensionLite , 0));
- assertEqualsExactType(true , message.getExtension(repeatedBoolExtensionLite , 0));
- assertEqualsExactType("215", message.getExtension(repeatedStringExtensionLite , 0));
+ assertEqualsExactType(201, message.getExtension(repeatedInt32ExtensionLite, 0));
+ assertEqualsExactType(202L, message.getExtension(repeatedInt64ExtensionLite, 0));
+ assertEqualsExactType(203, message.getExtension(repeatedUint32ExtensionLite, 0));
+ assertEqualsExactType(204L, message.getExtension(repeatedUint64ExtensionLite, 0));
+ assertEqualsExactType(205, message.getExtension(repeatedSint32ExtensionLite, 0));
+ assertEqualsExactType(206L, message.getExtension(repeatedSint64ExtensionLite, 0));
+ assertEqualsExactType(207, message.getExtension(repeatedFixed32ExtensionLite, 0));
+ assertEqualsExactType(208L, message.getExtension(repeatedFixed64ExtensionLite, 0));
+ assertEqualsExactType(209, message.getExtension(repeatedSfixed32ExtensionLite, 0));
+ assertEqualsExactType(210L, message.getExtension(repeatedSfixed64ExtensionLite, 0));
+ assertEqualsExactType(211F, message.getExtension(repeatedFloatExtensionLite, 0));
+ assertEqualsExactType(212D, message.getExtension(repeatedDoubleExtensionLite, 0));
+ assertEqualsExactType(true, message.getExtension(repeatedBoolExtensionLite, 0));
+ assertEqualsExactType("215", message.getExtension(repeatedStringExtensionLite, 0));
assertEqualsExactType(toBytes("216"), message.getExtension(repeatedBytesExtensionLite, 0));
- assertEqualsExactType(217, message.getExtension(repeatedGroupExtensionLite ,0).getA());
- assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtensionLite ,0).getBb());
- assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtensionLite,0).getC());
- assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtensionLite ,0).getD());
- assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtensionLite ,0).getBb());
+ assertEqualsExactType(217, message.getExtension(repeatedGroupExtensionLite, 0).getA());
+ assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtensionLite, 0).getBb());
+ assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtensionLite, 0).getC());
+ assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtensionLite, 0).getD());
+ assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtensionLite, 0).getBb());
- assertEqualsExactType(TestAllTypesLite.NestedEnum.BAR,
- message.getExtension(repeatedNestedEnumExtensionLite, 0));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAR,
- message.getExtension(repeatedForeignEnumExtensionLite, 0));
- assertEqualsExactType(ImportEnumLite.IMPORT_LITE_BAR,
- message.getExtension(repeatedImportEnumExtensionLite, 0));
+ assertEqualsExactType(
+ TestAllTypesLite.NestedEnum.BAR, message.getExtension(repeatedNestedEnumExtensionLite, 0));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_BAR,
+ message.getExtension(repeatedForeignEnumExtensionLite, 0));
+ assertEqualsExactType(
+ ImportEnumLite.IMPORT_LITE_BAR, message.getExtension(repeatedImportEnumExtensionLite, 0));
assertEqualsExactType("224", message.getExtension(repeatedStringPieceExtensionLite, 0));
assertEqualsExactType("225", message.getExtension(repeatedCordExtensionLite, 0));
- assertEqualsExactType(301 , message.getExtension(repeatedInt32ExtensionLite , 1));
- assertEqualsExactType(302L , message.getExtension(repeatedInt64ExtensionLite , 1));
- assertEqualsExactType(303 , message.getExtension(repeatedUint32ExtensionLite , 1));
- assertEqualsExactType(304L , message.getExtension(repeatedUint64ExtensionLite , 1));
- assertEqualsExactType(305 , message.getExtension(repeatedSint32ExtensionLite , 1));
- assertEqualsExactType(306L , message.getExtension(repeatedSint64ExtensionLite , 1));
- assertEqualsExactType(307 , message.getExtension(repeatedFixed32ExtensionLite , 1));
- assertEqualsExactType(308L , message.getExtension(repeatedFixed64ExtensionLite , 1));
- assertEqualsExactType(309 , message.getExtension(repeatedSfixed32ExtensionLite, 1));
- assertEqualsExactType(310L , message.getExtension(repeatedSfixed64ExtensionLite, 1));
- assertEqualsExactType(311F , message.getExtension(repeatedFloatExtensionLite , 1));
- assertEqualsExactType(312D , message.getExtension(repeatedDoubleExtensionLite , 1));
- assertEqualsExactType(false, message.getExtension(repeatedBoolExtensionLite , 1));
- assertEqualsExactType("315", message.getExtension(repeatedStringExtensionLite , 1));
+ assertEqualsExactType(301, message.getExtension(repeatedInt32ExtensionLite, 1));
+ assertEqualsExactType(302L, message.getExtension(repeatedInt64ExtensionLite, 1));
+ assertEqualsExactType(303, message.getExtension(repeatedUint32ExtensionLite, 1));
+ assertEqualsExactType(304L, message.getExtension(repeatedUint64ExtensionLite, 1));
+ assertEqualsExactType(305, message.getExtension(repeatedSint32ExtensionLite, 1));
+ assertEqualsExactType(306L, message.getExtension(repeatedSint64ExtensionLite, 1));
+ assertEqualsExactType(307, message.getExtension(repeatedFixed32ExtensionLite, 1));
+ assertEqualsExactType(308L, message.getExtension(repeatedFixed64ExtensionLite, 1));
+ assertEqualsExactType(309, message.getExtension(repeatedSfixed32ExtensionLite, 1));
+ assertEqualsExactType(310L, message.getExtension(repeatedSfixed64ExtensionLite, 1));
+ assertEqualsExactType(311F, message.getExtension(repeatedFloatExtensionLite, 1));
+ assertEqualsExactType(312D, message.getExtension(repeatedDoubleExtensionLite, 1));
+ assertEqualsExactType(false, message.getExtension(repeatedBoolExtensionLite, 1));
+ assertEqualsExactType("315", message.getExtension(repeatedStringExtensionLite, 1));
assertEqualsExactType(toBytes("316"), message.getExtension(repeatedBytesExtensionLite, 1));
- assertEqualsExactType(317, message.getExtension(repeatedGroupExtensionLite ,1).getA());
- assertEqualsExactType(318, message.getExtension(repeatedNestedMessageExtensionLite ,1).getBb());
- assertEqualsExactType(319, message.getExtension(repeatedForeignMessageExtensionLite,1).getC());
- assertEqualsExactType(320, message.getExtension(repeatedImportMessageExtensionLite ,1).getD());
- assertEqualsExactType(327, message.getExtension(repeatedLazyMessageExtensionLite ,1).getBb());
+ assertEqualsExactType(317, message.getExtension(repeatedGroupExtensionLite, 1).getA());
+ assertEqualsExactType(318, message.getExtension(repeatedNestedMessageExtensionLite, 1).getBb());
+ assertEqualsExactType(319, message.getExtension(repeatedForeignMessageExtensionLite, 1).getC());
+ assertEqualsExactType(320, message.getExtension(repeatedImportMessageExtensionLite, 1).getD());
+ assertEqualsExactType(327, message.getExtension(repeatedLazyMessageExtensionLite, 1).getBb());
- assertEqualsExactType(TestAllTypesLite.NestedEnum.BAZ,
- message.getExtension(repeatedNestedEnumExtensionLite, 1));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAZ,
- message.getExtension(repeatedForeignEnumExtensionLite, 1));
- assertEqualsExactType(ImportEnumLite.IMPORT_LITE_BAZ,
- message.getExtension(repeatedImportEnumExtensionLite, 1));
+ assertEqualsExactType(
+ TestAllTypesLite.NestedEnum.BAZ, message.getExtension(repeatedNestedEnumExtensionLite, 1));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_BAZ,
+ message.getExtension(repeatedForeignEnumExtensionLite, 1));
+ assertEqualsExactType(
+ ImportEnumLite.IMPORT_LITE_BAZ, message.getExtension(repeatedImportEnumExtensionLite, 1));
assertEqualsExactType("324", message.getExtension(repeatedStringPieceExtensionLite, 1));
assertEqualsExactType("325", message.getExtension(repeatedCordExtensionLite, 1));
// -----------------------------------------------------------------
- Assert.assertTrue(message.hasExtension(defaultInt32ExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultInt64ExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultUint32ExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultUint64ExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultSint32ExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultSint64ExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultFixed32ExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultFixed64ExtensionLite ));
+ Assert.assertTrue(message.hasExtension(defaultInt32ExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultInt64ExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultUint32ExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultUint64ExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultSint32ExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultSint64ExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultFixed32ExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultFixed64ExtensionLite));
Assert.assertTrue(message.hasExtension(defaultSfixed32ExtensionLite));
Assert.assertTrue(message.hasExtension(defaultSfixed64ExtensionLite));
- Assert.assertTrue(message.hasExtension(defaultFloatExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultDoubleExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultBoolExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultStringExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultBytesExtensionLite ));
+ Assert.assertTrue(message.hasExtension(defaultFloatExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultDoubleExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultBoolExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultStringExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultBytesExtensionLite));
- Assert.assertTrue(message.hasExtension(defaultNestedEnumExtensionLite ));
+ Assert.assertTrue(message.hasExtension(defaultNestedEnumExtensionLite));
Assert.assertTrue(message.hasExtension(defaultForeignEnumExtensionLite));
- Assert.assertTrue(message.hasExtension(defaultImportEnumExtensionLite ));
+ Assert.assertTrue(message.hasExtension(defaultImportEnumExtensionLite));
Assert.assertTrue(message.hasExtension(defaultStringPieceExtensionLite));
Assert.assertTrue(message.hasExtension(defaultCordExtensionLite));
- assertEqualsExactType(401 , message.getExtension(defaultInt32ExtensionLite ));
- assertEqualsExactType(402L , message.getExtension(defaultInt64ExtensionLite ));
- assertEqualsExactType(403 , message.getExtension(defaultUint32ExtensionLite ));
- assertEqualsExactType(404L , message.getExtension(defaultUint64ExtensionLite ));
- assertEqualsExactType(405 , message.getExtension(defaultSint32ExtensionLite ));
- assertEqualsExactType(406L , message.getExtension(defaultSint64ExtensionLite ));
- assertEqualsExactType(407 , message.getExtension(defaultFixed32ExtensionLite ));
- assertEqualsExactType(408L , message.getExtension(defaultFixed64ExtensionLite ));
- assertEqualsExactType(409 , message.getExtension(defaultSfixed32ExtensionLite));
- assertEqualsExactType(410L , message.getExtension(defaultSfixed64ExtensionLite));
- assertEqualsExactType(411F , message.getExtension(defaultFloatExtensionLite ));
- assertEqualsExactType(412D , message.getExtension(defaultDoubleExtensionLite ));
- assertEqualsExactType(false, message.getExtension(defaultBoolExtensionLite ));
- assertEqualsExactType("415", message.getExtension(defaultStringExtensionLite ));
+ assertEqualsExactType(401, message.getExtension(defaultInt32ExtensionLite));
+ assertEqualsExactType(402L, message.getExtension(defaultInt64ExtensionLite));
+ assertEqualsExactType(403, message.getExtension(defaultUint32ExtensionLite));
+ assertEqualsExactType(404L, message.getExtension(defaultUint64ExtensionLite));
+ assertEqualsExactType(405, message.getExtension(defaultSint32ExtensionLite));
+ assertEqualsExactType(406L, message.getExtension(defaultSint64ExtensionLite));
+ assertEqualsExactType(407, message.getExtension(defaultFixed32ExtensionLite));
+ assertEqualsExactType(408L, message.getExtension(defaultFixed64ExtensionLite));
+ assertEqualsExactType(409, message.getExtension(defaultSfixed32ExtensionLite));
+ assertEqualsExactType(410L, message.getExtension(defaultSfixed64ExtensionLite));
+ assertEqualsExactType(411F, message.getExtension(defaultFloatExtensionLite));
+ assertEqualsExactType(412D, message.getExtension(defaultDoubleExtensionLite));
+ assertEqualsExactType(false, message.getExtension(defaultBoolExtensionLite));
+ assertEqualsExactType("415", message.getExtension(defaultStringExtensionLite));
assertEqualsExactType(toBytes("416"), message.getExtension(defaultBytesExtensionLite));
- assertEqualsExactType(TestAllTypesLite.NestedEnum.FOO,
- message.getExtension(defaultNestedEnumExtensionLite ));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_FOO,
- message.getExtension(defaultForeignEnumExtensionLite));
- assertEqualsExactType(ImportEnumLite.IMPORT_LITE_FOO,
- message.getExtension(defaultImportEnumExtensionLite));
+ assertEqualsExactType(
+ TestAllTypesLite.NestedEnum.FOO, message.getExtension(defaultNestedEnumExtensionLite));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_FOO, message.getExtension(defaultForeignEnumExtensionLite));
+ assertEqualsExactType(
+ ImportEnumLite.IMPORT_LITE_FOO, message.getExtension(defaultImportEnumExtensionLite));
assertEqualsExactType("424", message.getExtension(defaultStringPieceExtensionLite));
assertEqualsExactType("425", message.getExtension(defaultCordExtensionLite));
@@ -2244,163 +2212,160 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all extensions of
- * {@code message} are cleared, and that getting the extensions returns their
- * default values.
+ * Assert (using {@code junit.framework.Assert}} that all extensions of {@code message} are
+ * cleared, and that getting the extensions returns their default values.
*/
- public static void assertExtensionsClear(
- TestAllExtensionsLiteOrBuilder message) {
+ public static void assertExtensionsClear(TestAllExtensionsLiteOrBuilder message) {
// hasBlah() should initially be false for all optional fields.
- Assert.assertFalse(message.hasExtension(optionalInt32ExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalInt64ExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalUint32ExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalUint64ExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalSint32ExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalSint64ExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalFixed32ExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalFixed64ExtensionLite ));
+ Assert.assertFalse(message.hasExtension(optionalInt32ExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalInt64ExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalUint32ExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalUint64ExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalSint32ExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalSint64ExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalFixed32ExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalFixed64ExtensionLite));
Assert.assertFalse(message.hasExtension(optionalSfixed32ExtensionLite));
Assert.assertFalse(message.hasExtension(optionalSfixed64ExtensionLite));
- Assert.assertFalse(message.hasExtension(optionalFloatExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalDoubleExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalBoolExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalStringExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalBytesExtensionLite ));
-
- Assert.assertFalse(message.hasExtension(optionalGroupExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalNestedMessageExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalForeignMessageExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalImportMessageExtensionLite ));
+ Assert.assertFalse(message.hasExtension(optionalFloatExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalDoubleExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalBoolExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalStringExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalBytesExtensionLite));
+
+ Assert.assertFalse(message.hasExtension(optionalGroupExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalNestedMessageExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalForeignMessageExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalImportMessageExtensionLite));
Assert.assertFalse(message.hasExtension(optionalPublicImportMessageExtensionLite));
- Assert.assertFalse(message.hasExtension(optionalLazyMessageExtensionLite ));
+ Assert.assertFalse(message.hasExtension(optionalLazyMessageExtensionLite));
- Assert.assertFalse(message.hasExtension(optionalNestedEnumExtensionLite ));
+ Assert.assertFalse(message.hasExtension(optionalNestedEnumExtensionLite));
Assert.assertFalse(message.hasExtension(optionalForeignEnumExtensionLite));
- Assert.assertFalse(message.hasExtension(optionalImportEnumExtensionLite ));
+ Assert.assertFalse(message.hasExtension(optionalImportEnumExtensionLite));
Assert.assertFalse(message.hasExtension(optionalStringPieceExtensionLite));
Assert.assertFalse(message.hasExtension(optionalCordExtensionLite));
// Optional fields without defaults are set to zero or something like it.
- assertEqualsExactType(0 , message.getExtension(optionalInt32ExtensionLite ));
- assertEqualsExactType(0L , message.getExtension(optionalInt64ExtensionLite ));
- assertEqualsExactType(0 , message.getExtension(optionalUint32ExtensionLite ));
- assertEqualsExactType(0L , message.getExtension(optionalUint64ExtensionLite ));
- assertEqualsExactType(0 , message.getExtension(optionalSint32ExtensionLite ));
- assertEqualsExactType(0L , message.getExtension(optionalSint64ExtensionLite ));
- assertEqualsExactType(0 , message.getExtension(optionalFixed32ExtensionLite ));
- assertEqualsExactType(0L , message.getExtension(optionalFixed64ExtensionLite ));
- assertEqualsExactType(0 , message.getExtension(optionalSfixed32ExtensionLite));
- assertEqualsExactType(0L , message.getExtension(optionalSfixed64ExtensionLite));
- assertEqualsExactType(0F , message.getExtension(optionalFloatExtensionLite ));
- assertEqualsExactType(0D , message.getExtension(optionalDoubleExtensionLite ));
- assertEqualsExactType(false, message.getExtension(optionalBoolExtensionLite ));
- assertEqualsExactType("" , message.getExtension(optionalStringExtensionLite ));
+ assertEqualsExactType(0, message.getExtension(optionalInt32ExtensionLite));
+ assertEqualsExactType(0L, message.getExtension(optionalInt64ExtensionLite));
+ assertEqualsExactType(0, message.getExtension(optionalUint32ExtensionLite));
+ assertEqualsExactType(0L, message.getExtension(optionalUint64ExtensionLite));
+ assertEqualsExactType(0, message.getExtension(optionalSint32ExtensionLite));
+ assertEqualsExactType(0L, message.getExtension(optionalSint64ExtensionLite));
+ assertEqualsExactType(0, message.getExtension(optionalFixed32ExtensionLite));
+ assertEqualsExactType(0L, message.getExtension(optionalFixed64ExtensionLite));
+ assertEqualsExactType(0, message.getExtension(optionalSfixed32ExtensionLite));
+ assertEqualsExactType(0L, message.getExtension(optionalSfixed64ExtensionLite));
+ assertEqualsExactType(0F, message.getExtension(optionalFloatExtensionLite));
+ assertEqualsExactType(0D, message.getExtension(optionalDoubleExtensionLite));
+ assertEqualsExactType(false, message.getExtension(optionalBoolExtensionLite));
+ assertEqualsExactType("", message.getExtension(optionalStringExtensionLite));
assertEqualsExactType(ByteString.EMPTY, message.getExtension(optionalBytesExtensionLite));
// Embedded messages should also be clear.
- Assert.assertFalse(message.getExtension(optionalGroupExtensionLite ).hasA());
- Assert.assertFalse(message.getExtension(optionalNestedMessageExtensionLite ).hasBb());
- Assert.assertFalse(message.getExtension(optionalForeignMessageExtensionLite ).hasC());
- Assert.assertFalse(message.getExtension(optionalImportMessageExtensionLite ).hasD());
+ Assert.assertFalse(message.getExtension(optionalGroupExtensionLite).hasA());
+ Assert.assertFalse(message.getExtension(optionalNestedMessageExtensionLite).hasBb());
+ Assert.assertFalse(message.getExtension(optionalForeignMessageExtensionLite).hasC());
+ Assert.assertFalse(message.getExtension(optionalImportMessageExtensionLite).hasD());
Assert.assertFalse(message.getExtension(optionalPublicImportMessageExtensionLite).hasE());
- Assert.assertFalse(message.getExtension(optionalLazyMessageExtensionLite ).hasBb());
+ Assert.assertFalse(message.getExtension(optionalLazyMessageExtensionLite).hasBb());
- assertEqualsExactType(0, message.getExtension(optionalGroupExtensionLite ).getA());
- assertEqualsExactType(0, message.getExtension(optionalNestedMessageExtensionLite ).getBb());
+ assertEqualsExactType(0, message.getExtension(optionalGroupExtensionLite).getA());
+ assertEqualsExactType(0, message.getExtension(optionalNestedMessageExtensionLite).getBb());
assertEqualsExactType(0, message.getExtension(optionalForeignMessageExtensionLite).getC());
- assertEqualsExactType(0, message.getExtension(optionalImportMessageExtensionLite ).getD());
- assertEqualsExactType(0, message.getExtension(
- optionalPublicImportMessageExtensionLite).getE());
- assertEqualsExactType(0, message.getExtension(optionalLazyMessageExtensionLite ).getBb());
+ assertEqualsExactType(0, message.getExtension(optionalImportMessageExtensionLite).getD());
+ assertEqualsExactType(0, message.getExtension(optionalPublicImportMessageExtensionLite).getE());
+ assertEqualsExactType(0, message.getExtension(optionalLazyMessageExtensionLite).getBb());
// Enums without defaults are set to the first value in the enum.
- assertEqualsExactType(TestAllTypesLite.NestedEnum.FOO,
- message.getExtension(optionalNestedEnumExtensionLite ));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_FOO,
- message.getExtension(optionalForeignEnumExtensionLite));
- assertEqualsExactType(ImportEnumLite.IMPORT_LITE_FOO,
- message.getExtension(optionalImportEnumExtensionLite));
+ assertEqualsExactType(
+ TestAllTypesLite.NestedEnum.FOO, message.getExtension(optionalNestedEnumExtensionLite));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_FOO, message.getExtension(optionalForeignEnumExtensionLite));
+ assertEqualsExactType(
+ ImportEnumLite.IMPORT_LITE_FOO, message.getExtension(optionalImportEnumExtensionLite));
assertEqualsExactType("", message.getExtension(optionalStringPieceExtensionLite));
assertEqualsExactType("", message.getExtension(optionalCordExtensionLite));
// Repeated fields are empty.
- Assert.assertEquals(0, message.getExtensionCount(repeatedInt32ExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedInt64ExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedUint32ExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedUint64ExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedSint32ExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedSint64ExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedFixed32ExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedFixed64ExtensionLite ));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedInt32ExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedInt64ExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedUint32ExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedUint64ExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedSint32ExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedSint64ExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedFixed32ExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedFixed64ExtensionLite));
Assert.assertEquals(0, message.getExtensionCount(repeatedSfixed32ExtensionLite));
Assert.assertEquals(0, message.getExtensionCount(repeatedSfixed64ExtensionLite));
- Assert.assertEquals(0, message.getExtensionCount(repeatedFloatExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedDoubleExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedBoolExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedStringExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedBytesExtensionLite ));
-
- Assert.assertEquals(0, message.getExtensionCount(repeatedGroupExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedNestedMessageExtensionLite ));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedFloatExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedDoubleExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedBoolExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedStringExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedBytesExtensionLite));
+
+ Assert.assertEquals(0, message.getExtensionCount(repeatedGroupExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedNestedMessageExtensionLite));
Assert.assertEquals(0, message.getExtensionCount(repeatedForeignMessageExtensionLite));
- Assert.assertEquals(0, message.getExtensionCount(repeatedImportMessageExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedLazyMessageExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedNestedEnumExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedForeignEnumExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedImportEnumExtensionLite ));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedImportMessageExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedLazyMessageExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedNestedEnumExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedForeignEnumExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedImportEnumExtensionLite));
Assert.assertEquals(0, message.getExtensionCount(repeatedStringPieceExtensionLite));
Assert.assertEquals(0, message.getExtensionCount(repeatedCordExtensionLite));
// hasBlah() should also be false for all default fields.
- Assert.assertFalse(message.hasExtension(defaultInt32ExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultInt64ExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultUint32ExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultUint64ExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultSint32ExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultSint64ExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultFixed32ExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultFixed64ExtensionLite ));
+ Assert.assertFalse(message.hasExtension(defaultInt32ExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultInt64ExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultUint32ExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultUint64ExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultSint32ExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultSint64ExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultFixed32ExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultFixed64ExtensionLite));
Assert.assertFalse(message.hasExtension(defaultSfixed32ExtensionLite));
Assert.assertFalse(message.hasExtension(defaultSfixed64ExtensionLite));
- Assert.assertFalse(message.hasExtension(defaultFloatExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultDoubleExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultBoolExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultStringExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultBytesExtensionLite ));
+ Assert.assertFalse(message.hasExtension(defaultFloatExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultDoubleExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultBoolExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultStringExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultBytesExtensionLite));
- Assert.assertFalse(message.hasExtension(defaultNestedEnumExtensionLite ));
+ Assert.assertFalse(message.hasExtension(defaultNestedEnumExtensionLite));
Assert.assertFalse(message.hasExtension(defaultForeignEnumExtensionLite));
- Assert.assertFalse(message.hasExtension(defaultImportEnumExtensionLite ));
+ Assert.assertFalse(message.hasExtension(defaultImportEnumExtensionLite));
Assert.assertFalse(message.hasExtension(defaultStringPieceExtensionLite));
Assert.assertFalse(message.hasExtension(defaultCordExtensionLite));
// Fields with defaults have their default values (duh).
- assertEqualsExactType( 41 , message.getExtension(defaultInt32ExtensionLite ));
- assertEqualsExactType( 42L , message.getExtension(defaultInt64ExtensionLite ));
- assertEqualsExactType( 43 , message.getExtension(defaultUint32ExtensionLite ));
- assertEqualsExactType( 44L , message.getExtension(defaultUint64ExtensionLite ));
- assertEqualsExactType(-45 , message.getExtension(defaultSint32ExtensionLite ));
- assertEqualsExactType( 46L , message.getExtension(defaultSint64ExtensionLite ));
- assertEqualsExactType( 47 , message.getExtension(defaultFixed32ExtensionLite ));
- assertEqualsExactType( 48L , message.getExtension(defaultFixed64ExtensionLite ));
- assertEqualsExactType( 49 , message.getExtension(defaultSfixed32ExtensionLite));
- assertEqualsExactType(-50L , message.getExtension(defaultSfixed64ExtensionLite));
- assertEqualsExactType( 51.5F , message.getExtension(defaultFloatExtensionLite ));
- assertEqualsExactType( 52e3D , message.getExtension(defaultDoubleExtensionLite ));
- assertEqualsExactType(true , message.getExtension(defaultBoolExtensionLite ));
- assertEqualsExactType("hello", message.getExtension(defaultStringExtensionLite ));
+ assertEqualsExactType(41, message.getExtension(defaultInt32ExtensionLite));
+ assertEqualsExactType(42L, message.getExtension(defaultInt64ExtensionLite));
+ assertEqualsExactType(43, message.getExtension(defaultUint32ExtensionLite));
+ assertEqualsExactType(44L, message.getExtension(defaultUint64ExtensionLite));
+ assertEqualsExactType(-45, message.getExtension(defaultSint32ExtensionLite));
+ assertEqualsExactType(46L, message.getExtension(defaultSint64ExtensionLite));
+ assertEqualsExactType(47, message.getExtension(defaultFixed32ExtensionLite));
+ assertEqualsExactType(48L, message.getExtension(defaultFixed64ExtensionLite));
+ assertEqualsExactType(49, message.getExtension(defaultSfixed32ExtensionLite));
+ assertEqualsExactType(-50L, message.getExtension(defaultSfixed64ExtensionLite));
+ assertEqualsExactType(51.5F, message.getExtension(defaultFloatExtensionLite));
+ assertEqualsExactType(52e3D, message.getExtension(defaultDoubleExtensionLite));
+ assertEqualsExactType(true, message.getExtension(defaultBoolExtensionLite));
+ assertEqualsExactType("hello", message.getExtension(defaultStringExtensionLite));
assertEqualsExactType(toBytes("world"), message.getExtension(defaultBytesExtensionLite));
- assertEqualsExactType(TestAllTypesLite.NestedEnum.BAR,
- message.getExtension(defaultNestedEnumExtensionLite ));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAR,
- message.getExtension(defaultForeignEnumExtensionLite));
- assertEqualsExactType(ImportEnumLite.IMPORT_LITE_BAR,
- message.getExtension(defaultImportEnumExtensionLite));
+ assertEqualsExactType(
+ TestAllTypesLite.NestedEnum.BAR, message.getExtension(defaultNestedEnumExtensionLite));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_BAR, message.getExtension(defaultForeignEnumExtensionLite));
+ assertEqualsExactType(
+ ImportEnumLite.IMPORT_LITE_BAR, message.getExtension(defaultImportEnumExtensionLite));
assertEqualsExactType("abc", message.getExtension(defaultStringPieceExtensionLite));
assertEqualsExactType("123", message.getExtension(defaultCordExtensionLite));
@@ -2414,200 +2379,229 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all extensions of
- * {@code message} are set to the values assigned by {@code setAllExtensions}
- * followed by {@code modifyRepeatedExtensions}.
+ * Assert (using {@code junit.framework.Assert}} that all extensions of {@code message} are set to
+ * the values assigned by {@code setAllExtensions} followed by {@code modifyRepeatedExtensions}.
*/
- public static void assertRepeatedExtensionsModified(
- TestAllExtensionsLiteOrBuilder message) {
+ public static void assertRepeatedExtensionsModified(TestAllExtensionsLiteOrBuilder message) {
// ModifyRepeatedFields only sets the second repeated element of each
// field. In addition to verifying this, we also verify that the first
// element and size were *not* modified.
- Assert.assertEquals(2, message.getExtensionCount(repeatedInt32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedInt64ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedUint32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedUint64ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedSint32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedSint64ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64ExtensionLite ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedInt32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedInt64ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedUint32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedUint64ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedSint32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedSint64ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64ExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed32ExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed64ExtensionLite));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtensionLite ));
-
- Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtensionLite ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtensionLite));
+
+ Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedForeignMessageExtensionLite));
- Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtensionLite ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedStringPieceExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedCordExtensionLite));
- assertEqualsExactType(201 , message.getExtension(repeatedInt32ExtensionLite , 0));
- assertEqualsExactType(202L , message.getExtension(repeatedInt64ExtensionLite , 0));
- assertEqualsExactType(203 , message.getExtension(repeatedUint32ExtensionLite , 0));
- assertEqualsExactType(204L , message.getExtension(repeatedUint64ExtensionLite , 0));
- assertEqualsExactType(205 , message.getExtension(repeatedSint32ExtensionLite , 0));
- assertEqualsExactType(206L , message.getExtension(repeatedSint64ExtensionLite , 0));
- assertEqualsExactType(207 , message.getExtension(repeatedFixed32ExtensionLite , 0));
- assertEqualsExactType(208L , message.getExtension(repeatedFixed64ExtensionLite , 0));
- assertEqualsExactType(209 , message.getExtension(repeatedSfixed32ExtensionLite, 0));
- assertEqualsExactType(210L , message.getExtension(repeatedSfixed64ExtensionLite, 0));
- assertEqualsExactType(211F , message.getExtension(repeatedFloatExtensionLite , 0));
- assertEqualsExactType(212D , message.getExtension(repeatedDoubleExtensionLite , 0));
- assertEqualsExactType(true , message.getExtension(repeatedBoolExtensionLite , 0));
- assertEqualsExactType("215", message.getExtension(repeatedStringExtensionLite , 0));
+ assertEqualsExactType(201, message.getExtension(repeatedInt32ExtensionLite, 0));
+ assertEqualsExactType(202L, message.getExtension(repeatedInt64ExtensionLite, 0));
+ assertEqualsExactType(203, message.getExtension(repeatedUint32ExtensionLite, 0));
+ assertEqualsExactType(204L, message.getExtension(repeatedUint64ExtensionLite, 0));
+ assertEqualsExactType(205, message.getExtension(repeatedSint32ExtensionLite, 0));
+ assertEqualsExactType(206L, message.getExtension(repeatedSint64ExtensionLite, 0));
+ assertEqualsExactType(207, message.getExtension(repeatedFixed32ExtensionLite, 0));
+ assertEqualsExactType(208L, message.getExtension(repeatedFixed64ExtensionLite, 0));
+ assertEqualsExactType(209, message.getExtension(repeatedSfixed32ExtensionLite, 0));
+ assertEqualsExactType(210L, message.getExtension(repeatedSfixed64ExtensionLite, 0));
+ assertEqualsExactType(211F, message.getExtension(repeatedFloatExtensionLite, 0));
+ assertEqualsExactType(212D, message.getExtension(repeatedDoubleExtensionLite, 0));
+ assertEqualsExactType(true, message.getExtension(repeatedBoolExtensionLite, 0));
+ assertEqualsExactType("215", message.getExtension(repeatedStringExtensionLite, 0));
assertEqualsExactType(toBytes("216"), message.getExtension(repeatedBytesExtensionLite, 0));
- assertEqualsExactType(217, message.getExtension(repeatedGroupExtensionLite ,0).getA());
- assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtensionLite ,0).getBb());
- assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtensionLite,0).getC());
- assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtensionLite ,0).getD());
- assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtensionLite ,0).getBb());
+ assertEqualsExactType(217, message.getExtension(repeatedGroupExtensionLite, 0).getA());
+ assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtensionLite, 0).getBb());
+ assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtensionLite, 0).getC());
+ assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtensionLite, 0).getD());
+ assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtensionLite, 0).getBb());
- assertEqualsExactType(TestAllTypesLite.NestedEnum.BAR,
- message.getExtension(repeatedNestedEnumExtensionLite, 0));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAR,
- message.getExtension(repeatedForeignEnumExtensionLite, 0));
- assertEqualsExactType(ImportEnumLite.IMPORT_LITE_BAR,
- message.getExtension(repeatedImportEnumExtensionLite, 0));
+ assertEqualsExactType(
+ TestAllTypesLite.NestedEnum.BAR, message.getExtension(repeatedNestedEnumExtensionLite, 0));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_BAR,
+ message.getExtension(repeatedForeignEnumExtensionLite, 0));
+ assertEqualsExactType(
+ ImportEnumLite.IMPORT_LITE_BAR, message.getExtension(repeatedImportEnumExtensionLite, 0));
assertEqualsExactType("224", message.getExtension(repeatedStringPieceExtensionLite, 0));
assertEqualsExactType("225", message.getExtension(repeatedCordExtensionLite, 0));
// Actually verify the second (modified) elements now.
- assertEqualsExactType(501 , message.getExtension(repeatedInt32ExtensionLite , 1));
- assertEqualsExactType(502L , message.getExtension(repeatedInt64ExtensionLite , 1));
- assertEqualsExactType(503 , message.getExtension(repeatedUint32ExtensionLite , 1));
- assertEqualsExactType(504L , message.getExtension(repeatedUint64ExtensionLite , 1));
- assertEqualsExactType(505 , message.getExtension(repeatedSint32ExtensionLite , 1));
- assertEqualsExactType(506L , message.getExtension(repeatedSint64ExtensionLite , 1));
- assertEqualsExactType(507 , message.getExtension(repeatedFixed32ExtensionLite , 1));
- assertEqualsExactType(508L , message.getExtension(repeatedFixed64ExtensionLite , 1));
- assertEqualsExactType(509 , message.getExtension(repeatedSfixed32ExtensionLite, 1));
- assertEqualsExactType(510L , message.getExtension(repeatedSfixed64ExtensionLite, 1));
- assertEqualsExactType(511F , message.getExtension(repeatedFloatExtensionLite , 1));
- assertEqualsExactType(512D , message.getExtension(repeatedDoubleExtensionLite , 1));
- assertEqualsExactType(true , message.getExtension(repeatedBoolExtensionLite , 1));
- assertEqualsExactType("515", message.getExtension(repeatedStringExtensionLite , 1));
+ assertEqualsExactType(501, message.getExtension(repeatedInt32ExtensionLite, 1));
+ assertEqualsExactType(502L, message.getExtension(repeatedInt64ExtensionLite, 1));
+ assertEqualsExactType(503, message.getExtension(repeatedUint32ExtensionLite, 1));
+ assertEqualsExactType(504L, message.getExtension(repeatedUint64ExtensionLite, 1));
+ assertEqualsExactType(505, message.getExtension(repeatedSint32ExtensionLite, 1));
+ assertEqualsExactType(506L, message.getExtension(repeatedSint64ExtensionLite, 1));
+ assertEqualsExactType(507, message.getExtension(repeatedFixed32ExtensionLite, 1));
+ assertEqualsExactType(508L, message.getExtension(repeatedFixed64ExtensionLite, 1));
+ assertEqualsExactType(509, message.getExtension(repeatedSfixed32ExtensionLite, 1));
+ assertEqualsExactType(510L, message.getExtension(repeatedSfixed64ExtensionLite, 1));
+ assertEqualsExactType(511F, message.getExtension(repeatedFloatExtensionLite, 1));
+ assertEqualsExactType(512D, message.getExtension(repeatedDoubleExtensionLite, 1));
+ assertEqualsExactType(true, message.getExtension(repeatedBoolExtensionLite, 1));
+ assertEqualsExactType("515", message.getExtension(repeatedStringExtensionLite, 1));
assertEqualsExactType(toBytes("516"), message.getExtension(repeatedBytesExtensionLite, 1));
- assertEqualsExactType(517, message.getExtension(repeatedGroupExtensionLite ,1).getA());
- assertEqualsExactType(518, message.getExtension(repeatedNestedMessageExtensionLite ,1).getBb());
- assertEqualsExactType(519, message.getExtension(repeatedForeignMessageExtensionLite,1).getC());
- assertEqualsExactType(520, message.getExtension(repeatedImportMessageExtensionLite ,1).getD());
- assertEqualsExactType(527, message.getExtension(repeatedLazyMessageExtensionLite ,1).getBb());
+ assertEqualsExactType(517, message.getExtension(repeatedGroupExtensionLite, 1).getA());
+ assertEqualsExactType(518, message.getExtension(repeatedNestedMessageExtensionLite, 1).getBb());
+ assertEqualsExactType(519, message.getExtension(repeatedForeignMessageExtensionLite, 1).getC());
+ assertEqualsExactType(520, message.getExtension(repeatedImportMessageExtensionLite, 1).getD());
+ assertEqualsExactType(527, message.getExtension(repeatedLazyMessageExtensionLite, 1).getBb());
- assertEqualsExactType(TestAllTypesLite.NestedEnum.FOO,
- message.getExtension(repeatedNestedEnumExtensionLite, 1));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_FOO,
- message.getExtension(repeatedForeignEnumExtensionLite, 1));
- assertEqualsExactType(ImportEnumLite.IMPORT_LITE_FOO,
- message.getExtension(repeatedImportEnumExtensionLite, 1));
+ assertEqualsExactType(
+ TestAllTypesLite.NestedEnum.FOO, message.getExtension(repeatedNestedEnumExtensionLite, 1));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_FOO,
+ message.getExtension(repeatedForeignEnumExtensionLite, 1));
+ assertEqualsExactType(
+ ImportEnumLite.IMPORT_LITE_FOO, message.getExtension(repeatedImportEnumExtensionLite, 1));
assertEqualsExactType("524", message.getExtension(repeatedStringPieceExtensionLite, 1));
assertEqualsExactType("525", message.getExtension(repeatedCordExtensionLite, 1));
}
public static void assertPackedExtensionsSet(TestPackedExtensionsLite message) {
- Assert.assertEquals(2, message.getExtensionCount(packedInt32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(packedInt64ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(packedUint32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(packedUint64ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(packedSint32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(packedSint64ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(packedFixed32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(packedFixed64ExtensionLite ));
+ Assert.assertEquals(2, message.getExtensionCount(packedInt32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(packedInt64ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(packedUint32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(packedUint64ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(packedSint32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(packedSint64ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(packedFixed32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(packedFixed64ExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(packedSfixed32ExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(packedSfixed64ExtensionLite));
- Assert.assertEquals(2, message.getExtensionCount(packedFloatExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(packedDoubleExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(packedBoolExtensionLite ));
+ Assert.assertEquals(2, message.getExtensionCount(packedFloatExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(packedDoubleExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(packedBoolExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(packedEnumExtensionLite));
- assertEqualsExactType(601 , message.getExtension(packedInt32ExtensionLite , 0));
- assertEqualsExactType(602L , message.getExtension(packedInt64ExtensionLite , 0));
- assertEqualsExactType(603 , message.getExtension(packedUint32ExtensionLite , 0));
- assertEqualsExactType(604L , message.getExtension(packedUint64ExtensionLite , 0));
- assertEqualsExactType(605 , message.getExtension(packedSint32ExtensionLite , 0));
- assertEqualsExactType(606L , message.getExtension(packedSint64ExtensionLite , 0));
- assertEqualsExactType(607 , message.getExtension(packedFixed32ExtensionLite , 0));
- assertEqualsExactType(608L , message.getExtension(packedFixed64ExtensionLite , 0));
- assertEqualsExactType(609 , message.getExtension(packedSfixed32ExtensionLite, 0));
- assertEqualsExactType(610L , message.getExtension(packedSfixed64ExtensionLite, 0));
- assertEqualsExactType(611F , message.getExtension(packedFloatExtensionLite , 0));
- assertEqualsExactType(612D , message.getExtension(packedDoubleExtensionLite , 0));
- assertEqualsExactType(true , message.getExtension(packedBoolExtensionLite , 0));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAR,
- message.getExtension(packedEnumExtensionLite, 0));
- assertEqualsExactType(701 , message.getExtension(packedInt32ExtensionLite , 1));
- assertEqualsExactType(702L , message.getExtension(packedInt64ExtensionLite , 1));
- assertEqualsExactType(703 , message.getExtension(packedUint32ExtensionLite , 1));
- assertEqualsExactType(704L , message.getExtension(packedUint64ExtensionLite , 1));
- assertEqualsExactType(705 , message.getExtension(packedSint32ExtensionLite , 1));
- assertEqualsExactType(706L , message.getExtension(packedSint64ExtensionLite , 1));
- assertEqualsExactType(707 , message.getExtension(packedFixed32ExtensionLite , 1));
- assertEqualsExactType(708L , message.getExtension(packedFixed64ExtensionLite , 1));
- assertEqualsExactType(709 , message.getExtension(packedSfixed32ExtensionLite, 1));
- assertEqualsExactType(710L , message.getExtension(packedSfixed64ExtensionLite, 1));
- assertEqualsExactType(711F , message.getExtension(packedFloatExtensionLite , 1));
- assertEqualsExactType(712D , message.getExtension(packedDoubleExtensionLite , 1));
- assertEqualsExactType(false, message.getExtension(packedBoolExtensionLite , 1));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAZ,
- message.getExtension(packedEnumExtensionLite, 1));
+ assertEqualsExactType(601, message.getExtension(packedInt32ExtensionLite, 0));
+ assertEqualsExactType(602L, message.getExtension(packedInt64ExtensionLite, 0));
+ assertEqualsExactType(603, message.getExtension(packedUint32ExtensionLite, 0));
+ assertEqualsExactType(604L, message.getExtension(packedUint64ExtensionLite, 0));
+ assertEqualsExactType(605, message.getExtension(packedSint32ExtensionLite, 0));
+ assertEqualsExactType(606L, message.getExtension(packedSint64ExtensionLite, 0));
+ assertEqualsExactType(607, message.getExtension(packedFixed32ExtensionLite, 0));
+ assertEqualsExactType(608L, message.getExtension(packedFixed64ExtensionLite, 0));
+ assertEqualsExactType(609, message.getExtension(packedSfixed32ExtensionLite, 0));
+ assertEqualsExactType(610L, message.getExtension(packedSfixed64ExtensionLite, 0));
+ assertEqualsExactType(611F, message.getExtension(packedFloatExtensionLite, 0));
+ assertEqualsExactType(612D, message.getExtension(packedDoubleExtensionLite, 0));
+ assertEqualsExactType(true, message.getExtension(packedBoolExtensionLite, 0));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_BAR, message.getExtension(packedEnumExtensionLite, 0));
+ assertEqualsExactType(701, message.getExtension(packedInt32ExtensionLite, 1));
+ assertEqualsExactType(702L, message.getExtension(packedInt64ExtensionLite, 1));
+ assertEqualsExactType(703, message.getExtension(packedUint32ExtensionLite, 1));
+ assertEqualsExactType(704L, message.getExtension(packedUint64ExtensionLite, 1));
+ assertEqualsExactType(705, message.getExtension(packedSint32ExtensionLite, 1));
+ assertEqualsExactType(706L, message.getExtension(packedSint64ExtensionLite, 1));
+ assertEqualsExactType(707, message.getExtension(packedFixed32ExtensionLite, 1));
+ assertEqualsExactType(708L, message.getExtension(packedFixed64ExtensionLite, 1));
+ assertEqualsExactType(709, message.getExtension(packedSfixed32ExtensionLite, 1));
+ assertEqualsExactType(710L, message.getExtension(packedSfixed64ExtensionLite, 1));
+ assertEqualsExactType(711F, message.getExtension(packedFloatExtensionLite, 1));
+ assertEqualsExactType(712D, message.getExtension(packedDoubleExtensionLite, 1));
+ assertEqualsExactType(false, message.getExtension(packedBoolExtensionLite, 1));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_BAZ, message.getExtension(packedEnumExtensionLite, 1));
}
// ===================================================================
// oneof
public static void setOneof(TestOneof2.Builder message) {
- message.setFooLazyMessage(
- TestOneof2.NestedMessage.newBuilder().setQuxInt(100).build());
+ message.setFooLazyMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(100).build());
message.setBarString("101");
message.setBazInt(102);
message.setBazString("103");
}
public static void assertOneofSet(TestOneof2 message) {
- Assert.assertTrue(message.hasFooLazyMessage ());
+ Assert.assertTrue(message.hasFooLazyMessage());
Assert.assertTrue(message.getFooLazyMessage().hasQuxInt());
Assert.assertTrue(message.hasBarString());
- Assert.assertTrue(message.hasBazInt ());
+ Assert.assertTrue(message.hasBazInt());
Assert.assertTrue(message.hasBazString());
- Assert.assertEquals(100 , message.getFooLazyMessage().getQuxInt());
- Assert.assertEquals("101", message.getBarString ());
- Assert.assertEquals(102 , message.getBazInt ());
- Assert.assertEquals("103", message.getBazString ());
+ Assert.assertEquals(100, message.getFooLazyMessage().getQuxInt());
+ Assert.assertEquals("101", message.getBarString());
+ Assert.assertEquals(102, message.getBazInt());
+ Assert.assertEquals("103", message.getBazString());
}
public static void assertAtMostOneFieldSetOneof(TestOneof2 message) {
int count = 0;
- if (message.hasFooInt()) { ++count; }
- if (message.hasFooString()) { ++count; }
- if (message.hasFooCord()) { ++count; }
- if (message.hasFooStringPiece()) { ++count; }
- if (message.hasFooBytes()) { ++count; }
- if (message.hasFooEnum()) { ++count; }
- if (message.hasFooMessage()) { ++count; }
- if (message.hasFooGroup()) { ++count; }
- if (message.hasFooLazyMessage()) { ++count; }
+ if (message.hasFooInt()) {
+ ++count;
+ }
+ if (message.hasFooString()) {
+ ++count;
+ }
+ if (message.hasFooCord()) {
+ ++count;
+ }
+ if (message.hasFooStringPiece()) {
+ ++count;
+ }
+ if (message.hasFooBytes()) {
+ ++count;
+ }
+ if (message.hasFooEnum()) {
+ ++count;
+ }
+ if (message.hasFooMessage()) {
+ ++count;
+ }
+ if (message.hasFooGroup()) {
+ ++count;
+ }
+ if (message.hasFooLazyMessage()) {
+ ++count;
+ }
Assert.assertTrue(count <= 1);
count = 0;
- if (message.hasBarInt()) { ++count; }
- if (message.hasBarString()) { ++count; }
- if (message.hasBarCord()) { ++count; }
- if (message.hasBarStringPiece()) { ++count; }
- if (message.hasBarBytes()) { ++count; }
- if (message.hasBarEnum()) { ++count; }
+ if (message.hasBarInt()) {
+ ++count;
+ }
+ if (message.hasBarString()) {
+ ++count;
+ }
+ if (message.hasBarCord()) {
+ ++count;
+ }
+ if (message.hasBarStringPiece()) {
+ ++count;
+ }
+ if (message.hasBarBytes()) {
+ ++count;
+ }
+ if (message.hasBarEnum()) {
+ ++count;
+ }
Assert.assertTrue(count <= 1);
switch (message.getFooCase()) {
@@ -2649,9 +2643,8 @@ public final class TestUtil {
// BEGIN FULL-RUNTIME
/**
- * Performs the same things that the methods of {@code TestUtil} do, but
- * via the reflection interface. This is its own class because it needs
- * to know what descriptor to use.
+ * Performs the same things that the methods of {@code TestUtil} do, but via the reflection
+ * interface. This is its own class because it needs to know what descriptor to use.
*/
public static class ReflectionTester {
private final Descriptors.Descriptor baseDescriptor;
@@ -2690,20 +2683,16 @@ public final class TestUtil {
private final Descriptors.EnumValueDescriptor importBaz;
/**
- * Construct a {@code ReflectionTester} that will expect messages using
- * the given descriptor.
+ * Construct a {@code ReflectionTester} that will expect messages using the given descriptor.
*
- * Normally {@code baseDescriptor} should be a descriptor for the type
- * {@code TestAllTypes}, defined in
- * {@code google/protobuf/unittest.proto}. However, if
- * {@code extensionRegistry} is non-null, then {@code baseDescriptor} should
- * be for {@code TestAllExtensions} instead, and instead of reading and
- * writing normal fields, the tester will read and write extensions.
- * All of {@code TestAllExtensions}' extensions must be registered in the
- * registry.
+ * <p>Normally {@code baseDescriptor} should be a descriptor for the type {@code TestAllTypes},
+ * defined in {@code google/protobuf/unittest.proto}. However, if {@code extensionRegistry}
+ * is non-null, then {@code baseDescriptor} should be for {@code TestAllExtensions} instead, and
+ * instead of reading and writing normal fields, the tester will read and write extensions. All
+ * of {@code TestAllExtensions}' extensions must be registered in the registry.
*/
- public ReflectionTester(Descriptors.Descriptor baseDescriptor,
- ExtensionRegistry extensionRegistry) {
+ public ReflectionTester(
+ Descriptors.Descriptor baseDescriptor, ExtensionRegistry extensionRegistry) {
this.baseDescriptor = baseDescriptor;
this.extensionRegistry = extensionRegistry;
@@ -2724,39 +2713,34 @@ public final class TestUtil {
// Use testAllTypes, rather than baseDescriptor, to allow
// initialization using TestPackedTypes descriptors. These objects
// won't be used by the methods for packed fields.
- this.optionalGroup =
- testAllTypes.findNestedTypeByName("OptionalGroup");
- this.repeatedGroup =
- testAllTypes.findNestedTypeByName("RepeatedGroup");
+ this.optionalGroup = testAllTypes.findNestedTypeByName("OptionalGroup");
+ this.repeatedGroup = testAllTypes.findNestedTypeByName("RepeatedGroup");
} else {
- this.optionalGroup =
- file.findMessageTypeByName("OptionalGroup_extension");
- this.repeatedGroup =
- file.findMessageTypeByName("RepeatedGroup_extension");
+ this.optionalGroup = file.findMessageTypeByName("OptionalGroup_extension");
+ this.repeatedGroup = file.findMessageTypeByName("RepeatedGroup_extension");
}
this.nestedMessage = testAllTypes.findNestedTypeByName("NestedMessage");
this.foreignMessage = file.findMessageTypeByName("ForeignMessage");
this.importMessage = importFile.findMessageTypeByName("ImportMessage");
- this.publicImportMessage = publicImportFile.findMessageTypeByName(
- "PublicImportMessage");
+ this.publicImportMessage = publicImportFile.findMessageTypeByName("PublicImportMessage");
this.nestedEnum = testAllTypes.findEnumTypeByName("NestedEnum");
this.foreignEnum = file.findEnumTypeByName("ForeignEnum");
this.importEnum = importFile.findEnumTypeByName("ImportEnum");
- Assert.assertNotNull(optionalGroup );
- Assert.assertNotNull(repeatedGroup );
- Assert.assertNotNull(nestedMessage );
+ Assert.assertNotNull(optionalGroup);
+ Assert.assertNotNull(repeatedGroup);
+ Assert.assertNotNull(nestedMessage);
Assert.assertNotNull(foreignMessage);
- Assert.assertNotNull(importMessage );
- Assert.assertNotNull(nestedEnum );
- Assert.assertNotNull(foreignEnum );
- Assert.assertNotNull(importEnum );
+ Assert.assertNotNull(importMessage);
+ Assert.assertNotNull(nestedEnum);
+ Assert.assertNotNull(foreignEnum);
+ Assert.assertNotNull(importEnum);
- this.nestedB = nestedMessage .findFieldByName("bb");
+ this.nestedB = nestedMessage.findFieldByName("bb");
this.foreignC = foreignMessage.findFieldByName("c");
- this.importD = importMessage .findFieldByName("d");
- this.importE = publicImportMessage.findFieldByName("e");
+ this.importD = importMessage.findFieldByName("d");
+ this.importE = publicImportMessage.findFieldByName("e");
this.nestedFoo = nestedEnum.findValueByName("FOO");
this.nestedBar = nestedEnum.findValueByName("BAR");
this.nestedBaz = nestedEnum.findValueByName("BAZ");
@@ -2770,26 +2754,24 @@ public final class TestUtil {
this.groupA = optionalGroup.findFieldByName("a");
this.repeatedGroupA = repeatedGroup.findFieldByName("a");
- Assert.assertNotNull(groupA );
+ Assert.assertNotNull(groupA);
Assert.assertNotNull(repeatedGroupA);
- Assert.assertNotNull(nestedB );
- Assert.assertNotNull(foreignC );
- Assert.assertNotNull(importD );
- Assert.assertNotNull(importE );
- Assert.assertNotNull(nestedFoo );
- Assert.assertNotNull(nestedBar );
- Assert.assertNotNull(nestedBaz );
- Assert.assertNotNull(foreignFoo );
- Assert.assertNotNull(foreignBar );
- Assert.assertNotNull(foreignBaz );
- Assert.assertNotNull(importFoo );
- Assert.assertNotNull(importBar );
- Assert.assertNotNull(importBaz );
+ Assert.assertNotNull(nestedB);
+ Assert.assertNotNull(foreignC);
+ Assert.assertNotNull(importD);
+ Assert.assertNotNull(importE);
+ Assert.assertNotNull(nestedFoo);
+ Assert.assertNotNull(nestedBar);
+ Assert.assertNotNull(nestedBaz);
+ Assert.assertNotNull(foreignFoo);
+ Assert.assertNotNull(foreignBar);
+ Assert.assertNotNull(foreignBaz);
+ Assert.assertNotNull(importFoo);
+ Assert.assertNotNull(importBar);
+ Assert.assertNotNull(importBaz);
}
- /**
- * Shorthand to get a FieldDescriptor for a field of unittest::TestAllTypes.
- */
+ /** Shorthand to get a FieldDescriptor for a field of unittest::TestAllTypes. */
private Descriptors.FieldDescriptor f(String name) {
Descriptors.FieldDescriptor result;
if (extensionRegistry == null) {
@@ -2802,9 +2784,8 @@ public final class TestUtil {
}
/**
- * Calls {@code parent.newBuilderForField()} or uses the
- * {@code ExtensionRegistry} to find an appropriate builder, depending
- * on what type is being tested.
+ * Calls {@code parent.newBuilderForField()} or uses the {@code ExtensionRegistry} to find an
+ * appropriate builder, depending on what type is being tested.
*/
private Message.Builder newBuilderForField(
Message.Builder parent, Descriptors.FieldDescriptor field) {
@@ -2812,8 +2793,8 @@ public final class TestUtil {
return parent.newBuilderForField(field);
} else {
ExtensionRegistry.ExtensionInfo extension =
- extensionRegistry.findImmutableExtensionByNumber(
- field.getContainingType(), field.getNumber());
+ extensionRegistry.findImmutableExtensionByNumber(
+ field.getContainingType(), field.getNumber());
Assert.assertNotNull(extension);
Assert.assertNotNull(extension.defaultInstance);
return extension.defaultInstance.newBuilderForType();
@@ -2823,210 +2804,223 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Set every field of {@code message} to the values expected by
- * {@code assertAllFieldsSet()}, using the {@link Message.Builder}
- * reflection interface.
+ * Set every field of {@code message} to the values expected by {@code assertAllFieldsSet()},
+ * using the {@link Message.Builder} reflection interface.
*/
void setAllFieldsViaReflection(Message.Builder message) {
- message.setField(f("optional_int32" ), 101 );
- message.setField(f("optional_int64" ), 102L);
- message.setField(f("optional_uint32" ), 103 );
- message.setField(f("optional_uint64" ), 104L);
- message.setField(f("optional_sint32" ), 105 );
- message.setField(f("optional_sint64" ), 106L);
- message.setField(f("optional_fixed32" ), 107 );
- message.setField(f("optional_fixed64" ), 108L);
- message.setField(f("optional_sfixed32"), 109 );
+ message.setField(f("optional_int32"), 101);
+ message.setField(f("optional_int64"), 102L);
+ message.setField(f("optional_uint32"), 103);
+ message.setField(f("optional_uint64"), 104L);
+ message.setField(f("optional_sint32"), 105);
+ message.setField(f("optional_sint64"), 106L);
+ message.setField(f("optional_fixed32"), 107);
+ message.setField(f("optional_fixed64"), 108L);
+ message.setField(f("optional_sfixed32"), 109);
message.setField(f("optional_sfixed64"), 110L);
- message.setField(f("optional_float" ), 111F);
- message.setField(f("optional_double" ), 112D);
- message.setField(f("optional_bool" ), true);
- message.setField(f("optional_string" ), "115");
- message.setField(f("optional_bytes" ), toBytes("116"));
-
- message.setField(f("optionalgroup"),
- newBuilderForField(message, f("optionalgroup"))
- .setField(groupA, 117).build());
- message.setField(f("optional_nested_message"),
- newBuilderForField(message, f("optional_nested_message"))
- .setField(nestedB, 118).build());
- message.setField(f("optional_foreign_message"),
- newBuilderForField(message, f("optional_foreign_message"))
- .setField(foreignC, 119).build());
- message.setField(f("optional_import_message"),
- newBuilderForField(message, f("optional_import_message"))
- .setField(importD, 120).build());
- message.setField(f("optional_public_import_message"),
- newBuilderForField(message, f("optional_public_import_message"))
- .setField(importE, 126).build());
- message.setField(f("optional_lazy_message"),
- newBuilderForField(message, f("optional_lazy_message"))
- .setField(nestedB, 127).build());
-
- message.setField(f("optional_nested_enum" ), nestedBaz);
+ message.setField(f("optional_float"), 111F);
+ message.setField(f("optional_double"), 112D);
+ message.setField(f("optional_bool"), true);
+ message.setField(f("optional_string"), "115");
+ message.setField(f("optional_bytes"), toBytes("116"));
+
+ message.setField(
+ f("optionalgroup"),
+ newBuilderForField(message, f("optionalgroup")).setField(groupA, 117).build());
+ message.setField(
+ f("optional_nested_message"),
+ newBuilderForField(message, f("optional_nested_message")).setField(nestedB, 118).build());
+ message.setField(
+ f("optional_foreign_message"),
+ newBuilderForField(message, f("optional_foreign_message"))
+ .setField(foreignC, 119)
+ .build());
+ message.setField(
+ f("optional_import_message"),
+ newBuilderForField(message, f("optional_import_message")).setField(importD, 120).build());
+ message.setField(
+ f("optional_public_import_message"),
+ newBuilderForField(message, f("optional_public_import_message"))
+ .setField(importE, 126)
+ .build());
+ message.setField(
+ f("optional_lazy_message"),
+ newBuilderForField(message, f("optional_lazy_message")).setField(nestedB, 127).build());
+
+ message.setField(f("optional_nested_enum"), nestedBaz);
message.setField(f("optional_foreign_enum"), foreignBaz);
- message.setField(f("optional_import_enum" ), importBaz);
+ message.setField(f("optional_import_enum"), importBaz);
- message.setField(f("optional_string_piece" ), "124");
- message.setField(f("optional_cord" ), "125");
+ message.setField(f("optional_string_piece"), "124");
+ message.setField(f("optional_cord"), "125");
// -----------------------------------------------------------------
- message.addRepeatedField(f("repeated_int32" ), 201 );
- message.addRepeatedField(f("repeated_int64" ), 202L);
- message.addRepeatedField(f("repeated_uint32" ), 203 );
- message.addRepeatedField(f("repeated_uint64" ), 204L);
- message.addRepeatedField(f("repeated_sint32" ), 205 );
- message.addRepeatedField(f("repeated_sint64" ), 206L);
- message.addRepeatedField(f("repeated_fixed32" ), 207 );
- message.addRepeatedField(f("repeated_fixed64" ), 208L);
- message.addRepeatedField(f("repeated_sfixed32"), 209 );
+ message.addRepeatedField(f("repeated_int32"), 201);
+ message.addRepeatedField(f("repeated_int64"), 202L);
+ message.addRepeatedField(f("repeated_uint32"), 203);
+ message.addRepeatedField(f("repeated_uint64"), 204L);
+ message.addRepeatedField(f("repeated_sint32"), 205);
+ message.addRepeatedField(f("repeated_sint64"), 206L);
+ message.addRepeatedField(f("repeated_fixed32"), 207);
+ message.addRepeatedField(f("repeated_fixed64"), 208L);
+ message.addRepeatedField(f("repeated_sfixed32"), 209);
message.addRepeatedField(f("repeated_sfixed64"), 210L);
- message.addRepeatedField(f("repeated_float" ), 211F);
- message.addRepeatedField(f("repeated_double" ), 212D);
- message.addRepeatedField(f("repeated_bool" ), true);
- message.addRepeatedField(f("repeated_string" ), "215");
- message.addRepeatedField(f("repeated_bytes" ), toBytes("216"));
-
- message.addRepeatedField(f("repeatedgroup"),
- newBuilderForField(message, f("repeatedgroup"))
- .setField(repeatedGroupA, 217).build());
- message.addRepeatedField(f("repeated_nested_message"),
- newBuilderForField(message, f("repeated_nested_message"))
- .setField(nestedB, 218).build());
- message.addRepeatedField(f("repeated_foreign_message"),
- newBuilderForField(message, f("repeated_foreign_message"))
- .setField(foreignC, 219).build());
- message.addRepeatedField(f("repeated_import_message"),
- newBuilderForField(message, f("repeated_import_message"))
- .setField(importD, 220).build());
- message.addRepeatedField(f("repeated_lazy_message"),
- newBuilderForField(message, f("repeated_lazy_message"))
- .setField(nestedB, 227).build());
-
- message.addRepeatedField(f("repeated_nested_enum" ), nestedBar);
+ message.addRepeatedField(f("repeated_float"), 211F);
+ message.addRepeatedField(f("repeated_double"), 212D);
+ message.addRepeatedField(f("repeated_bool"), true);
+ message.addRepeatedField(f("repeated_string"), "215");
+ message.addRepeatedField(f("repeated_bytes"), toBytes("216"));
+
+ message.addRepeatedField(
+ f("repeatedgroup"),
+ newBuilderForField(message, f("repeatedgroup")).setField(repeatedGroupA, 217).build());
+ message.addRepeatedField(
+ f("repeated_nested_message"),
+ newBuilderForField(message, f("repeated_nested_message")).setField(nestedB, 218).build());
+ message.addRepeatedField(
+ f("repeated_foreign_message"),
+ newBuilderForField(message, f("repeated_foreign_message"))
+ .setField(foreignC, 219)
+ .build());
+ message.addRepeatedField(
+ f("repeated_import_message"),
+ newBuilderForField(message, f("repeated_import_message")).setField(importD, 220).build());
+ message.addRepeatedField(
+ f("repeated_lazy_message"),
+ newBuilderForField(message, f("repeated_lazy_message")).setField(nestedB, 227).build());
+
+ message.addRepeatedField(f("repeated_nested_enum"), nestedBar);
message.addRepeatedField(f("repeated_foreign_enum"), foreignBar);
- message.addRepeatedField(f("repeated_import_enum" ), importBar);
+ message.addRepeatedField(f("repeated_import_enum"), importBar);
- message.addRepeatedField(f("repeated_string_piece" ), "224");
- message.addRepeatedField(f("repeated_cord" ), "225");
+ message.addRepeatedField(f("repeated_string_piece"), "224");
+ message.addRepeatedField(f("repeated_cord"), "225");
// Add a second one of each field.
- message.addRepeatedField(f("repeated_int32" ), 301 );
- message.addRepeatedField(f("repeated_int64" ), 302L);
- message.addRepeatedField(f("repeated_uint32" ), 303 );
- message.addRepeatedField(f("repeated_uint64" ), 304L);
- message.addRepeatedField(f("repeated_sint32" ), 305 );
- message.addRepeatedField(f("repeated_sint64" ), 306L);
- message.addRepeatedField(f("repeated_fixed32" ), 307 );
- message.addRepeatedField(f("repeated_fixed64" ), 308L);
- message.addRepeatedField(f("repeated_sfixed32"), 309 );
+ message.addRepeatedField(f("repeated_int32"), 301);
+ message.addRepeatedField(f("repeated_int64"), 302L);
+ message.addRepeatedField(f("repeated_uint32"), 303);
+ message.addRepeatedField(f("repeated_uint64"), 304L);
+ message.addRepeatedField(f("repeated_sint32"), 305);
+ message.addRepeatedField(f("repeated_sint64"), 306L);
+ message.addRepeatedField(f("repeated_fixed32"), 307);
+ message.addRepeatedField(f("repeated_fixed64"), 308L);
+ message.addRepeatedField(f("repeated_sfixed32"), 309);
message.addRepeatedField(f("repeated_sfixed64"), 310L);
- message.addRepeatedField(f("repeated_float" ), 311F);
- message.addRepeatedField(f("repeated_double" ), 312D);
- message.addRepeatedField(f("repeated_bool" ), false);
- message.addRepeatedField(f("repeated_string" ), "315");
- message.addRepeatedField(f("repeated_bytes" ), toBytes("316"));
-
- message.addRepeatedField(f("repeatedgroup"),
- newBuilderForField(message, f("repeatedgroup"))
- .setField(repeatedGroupA, 317).build());
- message.addRepeatedField(f("repeated_nested_message"),
- newBuilderForField(message, f("repeated_nested_message"))
- .setField(nestedB, 318).build());
- message.addRepeatedField(f("repeated_foreign_message"),
- newBuilderForField(message, f("repeated_foreign_message"))
- .setField(foreignC, 319).build());
- message.addRepeatedField(f("repeated_import_message"),
- newBuilderForField(message, f("repeated_import_message"))
- .setField(importD, 320).build());
- message.addRepeatedField(f("repeated_lazy_message"),
- newBuilderForField(message, f("repeated_lazy_message"))
- .setField(nestedB, 327).build());
-
- message.addRepeatedField(f("repeated_nested_enum" ), nestedBaz);
+ message.addRepeatedField(f("repeated_float"), 311F);
+ message.addRepeatedField(f("repeated_double"), 312D);
+ message.addRepeatedField(f("repeated_bool"), false);
+ message.addRepeatedField(f("repeated_string"), "315");
+ message.addRepeatedField(f("repeated_bytes"), toBytes("316"));
+
+ message.addRepeatedField(
+ f("repeatedgroup"),
+ newBuilderForField(message, f("repeatedgroup")).setField(repeatedGroupA, 317).build());
+ message.addRepeatedField(
+ f("repeated_nested_message"),
+ newBuilderForField(message, f("repeated_nested_message")).setField(nestedB, 318).build());
+ message.addRepeatedField(
+ f("repeated_foreign_message"),
+ newBuilderForField(message, f("repeated_foreign_message"))
+ .setField(foreignC, 319)
+ .build());
+ message.addRepeatedField(
+ f("repeated_import_message"),
+ newBuilderForField(message, f("repeated_import_message")).setField(importD, 320).build());
+ message.addRepeatedField(
+ f("repeated_lazy_message"),
+ newBuilderForField(message, f("repeated_lazy_message")).setField(nestedB, 327).build());
+
+ message.addRepeatedField(f("repeated_nested_enum"), nestedBaz);
message.addRepeatedField(f("repeated_foreign_enum"), foreignBaz);
- message.addRepeatedField(f("repeated_import_enum" ), importBaz);
+ message.addRepeatedField(f("repeated_import_enum"), importBaz);
- message.addRepeatedField(f("repeated_string_piece" ), "324");
- message.addRepeatedField(f("repeated_cord" ), "325");
+ message.addRepeatedField(f("repeated_string_piece"), "324");
+ message.addRepeatedField(f("repeated_cord"), "325");
// -----------------------------------------------------------------
- message.setField(f("default_int32" ), 401 );
- message.setField(f("default_int64" ), 402L);
- message.setField(f("default_uint32" ), 403 );
- message.setField(f("default_uint64" ), 404L);
- message.setField(f("default_sint32" ), 405 );
- message.setField(f("default_sint64" ), 406L);
- message.setField(f("default_fixed32" ), 407 );
- message.setField(f("default_fixed64" ), 408L);
- message.setField(f("default_sfixed32"), 409 );
+ message.setField(f("default_int32"), 401);
+ message.setField(f("default_int64"), 402L);
+ message.setField(f("default_uint32"), 403);
+ message.setField(f("default_uint64"), 404L);
+ message.setField(f("default_sint32"), 405);
+ message.setField(f("default_sint64"), 406L);
+ message.setField(f("default_fixed32"), 407);
+ message.setField(f("default_fixed64"), 408L);
+ message.setField(f("default_sfixed32"), 409);
message.setField(f("default_sfixed64"), 410L);
- message.setField(f("default_float" ), 411F);
- message.setField(f("default_double" ), 412D);
- message.setField(f("default_bool" ), false);
- message.setField(f("default_string" ), "415");
- message.setField(f("default_bytes" ), toBytes("416"));
+ message.setField(f("default_float"), 411F);
+ message.setField(f("default_double"), 412D);
+ message.setField(f("default_bool"), false);
+ message.setField(f("default_string"), "415");
+ message.setField(f("default_bytes"), toBytes("416"));
- message.setField(f("default_nested_enum" ), nestedFoo);
+ message.setField(f("default_nested_enum"), nestedFoo);
message.setField(f("default_foreign_enum"), foreignFoo);
- message.setField(f("default_import_enum" ), importFoo);
+ message.setField(f("default_import_enum"), importFoo);
- message.setField(f("default_string_piece" ), "424");
- message.setField(f("default_cord" ), "425");
+ message.setField(f("default_string_piece"), "424");
+ message.setField(f("default_cord"), "425");
- message.setField(f("oneof_uint32" ), 601);
- message.setField(f("oneof_nested_message"),
- newBuilderForField(message, f("oneof_nested_message"))
- .setField(nestedB, 602).build());
- message.setField(f("oneof_string" ), "603");
- message.setField(f("oneof_bytes" ), toBytes("604"));
+ message.setField(f("oneof_uint32"), 601);
+ message.setField(
+ f("oneof_nested_message"),
+ newBuilderForField(message, f("oneof_nested_message")).setField(nestedB, 602).build());
+ message.setField(f("oneof_string"), "603");
+ message.setField(f("oneof_bytes"), toBytes("604"));
}
// -------------------------------------------------------------------
/**
- * Modify the repeated fields of {@code message} to contain the values
- * expected by {@code assertRepeatedFieldsModified()}, using the
- * {@link Message.Builder} reflection interface.
+ * Modify the repeated fields of {@code message} to contain the values expected by {@code
+ * assertRepeatedFieldsModified()}, using the {@link Message.Builder} reflection interface.
*/
void modifyRepeatedFieldsViaReflection(Message.Builder message) {
- message.setRepeatedField(f("repeated_int32" ), 1, 501 );
- message.setRepeatedField(f("repeated_int64" ), 1, 502L);
- message.setRepeatedField(f("repeated_uint32" ), 1, 503 );
- message.setRepeatedField(f("repeated_uint64" ), 1, 504L);
- message.setRepeatedField(f("repeated_sint32" ), 1, 505 );
- message.setRepeatedField(f("repeated_sint64" ), 1, 506L);
- message.setRepeatedField(f("repeated_fixed32" ), 1, 507 );
- message.setRepeatedField(f("repeated_fixed64" ), 1, 508L);
- message.setRepeatedField(f("repeated_sfixed32"), 1, 509 );
+ message.setRepeatedField(f("repeated_int32"), 1, 501);
+ message.setRepeatedField(f("repeated_int64"), 1, 502L);
+ message.setRepeatedField(f("repeated_uint32"), 1, 503);
+ message.setRepeatedField(f("repeated_uint64"), 1, 504L);
+ message.setRepeatedField(f("repeated_sint32"), 1, 505);
+ message.setRepeatedField(f("repeated_sint64"), 1, 506L);
+ message.setRepeatedField(f("repeated_fixed32"), 1, 507);
+ message.setRepeatedField(f("repeated_fixed64"), 1, 508L);
+ message.setRepeatedField(f("repeated_sfixed32"), 1, 509);
message.setRepeatedField(f("repeated_sfixed64"), 1, 510L);
- message.setRepeatedField(f("repeated_float" ), 1, 511F);
- message.setRepeatedField(f("repeated_double" ), 1, 512D);
- message.setRepeatedField(f("repeated_bool" ), 1, true);
- message.setRepeatedField(f("repeated_string" ), 1, "515");
- message.setRepeatedField(f("repeated_bytes" ), 1, toBytes("516"));
-
- message.setRepeatedField(f("repeatedgroup"), 1,
- newBuilderForField(message, f("repeatedgroup"))
- .setField(repeatedGroupA, 517).build());
- message.setRepeatedField(f("repeated_nested_message"), 1,
- newBuilderForField(message, f("repeated_nested_message"))
- .setField(nestedB, 518).build());
- message.setRepeatedField(f("repeated_foreign_message"), 1,
- newBuilderForField(message, f("repeated_foreign_message"))
- .setField(foreignC, 519).build());
- message.setRepeatedField(f("repeated_import_message"), 1,
- newBuilderForField(message, f("repeated_import_message"))
- .setField(importD, 520).build());
- message.setRepeatedField(f("repeated_lazy_message"), 1,
- newBuilderForField(message, f("repeated_lazy_message"))
- .setField(nestedB, 527).build());
-
- message.setRepeatedField(f("repeated_nested_enum" ), 1, nestedFoo);
+ message.setRepeatedField(f("repeated_float"), 1, 511F);
+ message.setRepeatedField(f("repeated_double"), 1, 512D);
+ message.setRepeatedField(f("repeated_bool"), 1, true);
+ message.setRepeatedField(f("repeated_string"), 1, "515");
+ message.setRepeatedField(f("repeated_bytes"), 1, toBytes("516"));
+
+ message.setRepeatedField(
+ f("repeatedgroup"),
+ 1,
+ newBuilderForField(message, f("repeatedgroup")).setField(repeatedGroupA, 517).build());
+ message.setRepeatedField(
+ f("repeated_nested_message"),
+ 1,
+ newBuilderForField(message, f("repeated_nested_message")).setField(nestedB, 518).build());
+ message.setRepeatedField(
+ f("repeated_foreign_message"),
+ 1,
+ newBuilderForField(message, f("repeated_foreign_message"))
+ .setField(foreignC, 519)
+ .build());
+ message.setRepeatedField(
+ f("repeated_import_message"),
+ 1,
+ newBuilderForField(message, f("repeated_import_message")).setField(importD, 520).build());
+ message.setRepeatedField(
+ f("repeated_lazy_message"),
+ 1,
+ newBuilderForField(message, f("repeated_lazy_message")).setField(nestedB, 527).build());
+
+ message.setRepeatedField(f("repeated_nested_enum"), 1, nestedFoo);
message.setRepeatedField(f("repeated_foreign_enum"), 1, foreignFoo);
- message.setRepeatedField(f("repeated_import_enum" ), 1, importFoo);
+ message.setRepeatedField(f("repeated_import_enum"), 1, importFoo);
message.setRepeatedField(f("repeated_string_piece"), 1, "524");
message.setRepeatedField(f("repeated_cord"), 1, "525");
@@ -3035,244 +3029,235 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all fields of
- * {@code message} are set to the values assigned by {@code setAllFields},
- * using the {@link Message} reflection interface.
+ * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to
+ * the values assigned by {@code setAllFields}, using the {@link Message} reflection interface.
*/
public void assertAllFieldsSetViaReflection(MessageOrBuilder message) {
- Assert.assertTrue(message.hasField(f("optional_int32" )));
- Assert.assertTrue(message.hasField(f("optional_int64" )));
- Assert.assertTrue(message.hasField(f("optional_uint32" )));
- Assert.assertTrue(message.hasField(f("optional_uint64" )));
- Assert.assertTrue(message.hasField(f("optional_sint32" )));
- Assert.assertTrue(message.hasField(f("optional_sint64" )));
- Assert.assertTrue(message.hasField(f("optional_fixed32" )));
- Assert.assertTrue(message.hasField(f("optional_fixed64" )));
+ Assert.assertTrue(message.hasField(f("optional_int32")));
+ Assert.assertTrue(message.hasField(f("optional_int64")));
+ Assert.assertTrue(message.hasField(f("optional_uint32")));
+ Assert.assertTrue(message.hasField(f("optional_uint64")));
+ Assert.assertTrue(message.hasField(f("optional_sint32")));
+ Assert.assertTrue(message.hasField(f("optional_sint64")));
+ Assert.assertTrue(message.hasField(f("optional_fixed32")));
+ Assert.assertTrue(message.hasField(f("optional_fixed64")));
Assert.assertTrue(message.hasField(f("optional_sfixed32")));
Assert.assertTrue(message.hasField(f("optional_sfixed64")));
- Assert.assertTrue(message.hasField(f("optional_float" )));
- Assert.assertTrue(message.hasField(f("optional_double" )));
- Assert.assertTrue(message.hasField(f("optional_bool" )));
- Assert.assertTrue(message.hasField(f("optional_string" )));
- Assert.assertTrue(message.hasField(f("optional_bytes" )));
-
- Assert.assertTrue(message.hasField(f("optionalgroup" )));
- Assert.assertTrue(message.hasField(f("optional_nested_message" )));
+ Assert.assertTrue(message.hasField(f("optional_float")));
+ Assert.assertTrue(message.hasField(f("optional_double")));
+ Assert.assertTrue(message.hasField(f("optional_bool")));
+ Assert.assertTrue(message.hasField(f("optional_string")));
+ Assert.assertTrue(message.hasField(f("optional_bytes")));
+
+ Assert.assertTrue(message.hasField(f("optionalgroup")));
+ Assert.assertTrue(message.hasField(f("optional_nested_message")));
Assert.assertTrue(message.hasField(f("optional_foreign_message")));
- Assert.assertTrue(message.hasField(f("optional_import_message" )));
+ Assert.assertTrue(message.hasField(f("optional_import_message")));
+ Assert.assertTrue(((Message) message.getField(f("optionalgroup"))).hasField(groupA));
Assert.assertTrue(
- ((Message)message.getField(f("optionalgroup"))).hasField(groupA));
+ ((Message) message.getField(f("optional_nested_message"))).hasField(nestedB));
Assert.assertTrue(
- ((Message)message.getField(f("optional_nested_message")))
- .hasField(nestedB));
+ ((Message) message.getField(f("optional_foreign_message"))).hasField(foreignC));
Assert.assertTrue(
- ((Message)message.getField(f("optional_foreign_message")))
- .hasField(foreignC));
- Assert.assertTrue(
- ((Message)message.getField(f("optional_import_message")))
- .hasField(importD));
+ ((Message) message.getField(f("optional_import_message"))).hasField(importD));
- Assert.assertTrue(message.hasField(f("optional_nested_enum" )));
+ Assert.assertTrue(message.hasField(f("optional_nested_enum")));
Assert.assertTrue(message.hasField(f("optional_foreign_enum")));
- Assert.assertTrue(message.hasField(f("optional_import_enum" )));
+ Assert.assertTrue(message.hasField(f("optional_import_enum")));
Assert.assertTrue(message.hasField(f("optional_string_piece")));
Assert.assertTrue(message.hasField(f("optional_cord")));
- Assert.assertEquals(101 , message.getField(f("optional_int32" )));
- Assert.assertEquals(102L , message.getField(f("optional_int64" )));
- Assert.assertEquals(103 , message.getField(f("optional_uint32" )));
- Assert.assertEquals(104L , message.getField(f("optional_uint64" )));
- Assert.assertEquals(105 , message.getField(f("optional_sint32" )));
- Assert.assertEquals(106L , message.getField(f("optional_sint64" )));
- Assert.assertEquals(107 , message.getField(f("optional_fixed32" )));
- Assert.assertEquals(108L , message.getField(f("optional_fixed64" )));
- Assert.assertEquals(109 , message.getField(f("optional_sfixed32")));
- Assert.assertEquals(110L , message.getField(f("optional_sfixed64")));
- Assert.assertEquals(111F , message.getField(f("optional_float" )));
- Assert.assertEquals(112D , message.getField(f("optional_double" )));
- Assert.assertEquals(true , message.getField(f("optional_bool" )));
- Assert.assertEquals("115", message.getField(f("optional_string" )));
+ Assert.assertEquals(101, message.getField(f("optional_int32")));
+ Assert.assertEquals(102L, message.getField(f("optional_int64")));
+ Assert.assertEquals(103, message.getField(f("optional_uint32")));
+ Assert.assertEquals(104L, message.getField(f("optional_uint64")));
+ Assert.assertEquals(105, message.getField(f("optional_sint32")));
+ Assert.assertEquals(106L, message.getField(f("optional_sint64")));
+ Assert.assertEquals(107, message.getField(f("optional_fixed32")));
+ Assert.assertEquals(108L, message.getField(f("optional_fixed64")));
+ Assert.assertEquals(109, message.getField(f("optional_sfixed32")));
+ Assert.assertEquals(110L, message.getField(f("optional_sfixed64")));
+ Assert.assertEquals(111F, message.getField(f("optional_float")));
+ Assert.assertEquals(112D, message.getField(f("optional_double")));
+ Assert.assertEquals(true, message.getField(f("optional_bool")));
+ Assert.assertEquals("115", message.getField(f("optional_string")));
Assert.assertEquals(toBytes("116"), message.getField(f("optional_bytes")));
- Assert.assertEquals(117,
- ((Message)message.getField(f("optionalgroup"))).getField(groupA));
- Assert.assertEquals(118,
- ((Message)message.getField(f("optional_nested_message")))
- .getField(nestedB));
- Assert.assertEquals(119,
- ((Message)message.getField(f("optional_foreign_message")))
- .getField(foreignC));
- Assert.assertEquals(120,
- ((Message)message.getField(f("optional_import_message")))
- .getField(importD));
- Assert.assertEquals(126,
- ((Message)message.getField(f("optional_public_import_message")))
- .getField(importE));
- Assert.assertEquals(127,
- ((Message)message.getField(f("optional_lazy_message")))
- .getField(nestedB));
-
- Assert.assertEquals( nestedBaz, message.getField(f("optional_nested_enum" )));
+ Assert.assertEquals(117, ((Message) message.getField(f("optionalgroup"))).getField(groupA));
+ Assert.assertEquals(
+ 118, ((Message) message.getField(f("optional_nested_message"))).getField(nestedB));
+ Assert.assertEquals(
+ 119, ((Message) message.getField(f("optional_foreign_message"))).getField(foreignC));
+ Assert.assertEquals(
+ 120, ((Message) message.getField(f("optional_import_message"))).getField(importD));
+ Assert.assertEquals(
+ 126, ((Message) message.getField(f("optional_public_import_message"))).getField(importE));
+ Assert.assertEquals(
+ 127, ((Message) message.getField(f("optional_lazy_message"))).getField(nestedB));
+
+ Assert.assertEquals(nestedBaz, message.getField(f("optional_nested_enum")));
Assert.assertEquals(foreignBaz, message.getField(f("optional_foreign_enum")));
- Assert.assertEquals( importBaz, message.getField(f("optional_import_enum" )));
+ Assert.assertEquals(importBaz, message.getField(f("optional_import_enum")));
Assert.assertEquals("124", message.getField(f("optional_string_piece")));
Assert.assertEquals("125", message.getField(f("optional_cord")));
// -----------------------------------------------------------------
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int64" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint64" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint64" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed64" )));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int64")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint64")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint64")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed64")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed32")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed64")));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_float" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_double" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bool" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bytes" )));
-
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeatedgroup" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_message" )));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_float")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_double")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bool")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bytes")));
+
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeatedgroup")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_message")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_message")));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_message" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_lazy_message" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_enum" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_enum" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_enum" )));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_message")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_lazy_message")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_enum")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_enum")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_enum")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string_piece")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_cord")));
- Assert.assertEquals(201 , message.getRepeatedField(f("repeated_int32" ), 0));
- Assert.assertEquals(202L , message.getRepeatedField(f("repeated_int64" ), 0));
- Assert.assertEquals(203 , message.getRepeatedField(f("repeated_uint32" ), 0));
- Assert.assertEquals(204L , message.getRepeatedField(f("repeated_uint64" ), 0));
- Assert.assertEquals(205 , message.getRepeatedField(f("repeated_sint32" ), 0));
- Assert.assertEquals(206L , message.getRepeatedField(f("repeated_sint64" ), 0));
- Assert.assertEquals(207 , message.getRepeatedField(f("repeated_fixed32" ), 0));
- Assert.assertEquals(208L , message.getRepeatedField(f("repeated_fixed64" ), 0));
- Assert.assertEquals(209 , message.getRepeatedField(f("repeated_sfixed32"), 0));
- Assert.assertEquals(210L , message.getRepeatedField(f("repeated_sfixed64"), 0));
- Assert.assertEquals(211F , message.getRepeatedField(f("repeated_float" ), 0));
- Assert.assertEquals(212D , message.getRepeatedField(f("repeated_double" ), 0));
- Assert.assertEquals(true , message.getRepeatedField(f("repeated_bool" ), 0));
- Assert.assertEquals("215", message.getRepeatedField(f("repeated_string" ), 0));
+ Assert.assertEquals(201, message.getRepeatedField(f("repeated_int32"), 0));
+ Assert.assertEquals(202L, message.getRepeatedField(f("repeated_int64"), 0));
+ Assert.assertEquals(203, message.getRepeatedField(f("repeated_uint32"), 0));
+ Assert.assertEquals(204L, message.getRepeatedField(f("repeated_uint64"), 0));
+ Assert.assertEquals(205, message.getRepeatedField(f("repeated_sint32"), 0));
+ Assert.assertEquals(206L, message.getRepeatedField(f("repeated_sint64"), 0));
+ Assert.assertEquals(207, message.getRepeatedField(f("repeated_fixed32"), 0));
+ Assert.assertEquals(208L, message.getRepeatedField(f("repeated_fixed64"), 0));
+ Assert.assertEquals(209, message.getRepeatedField(f("repeated_sfixed32"), 0));
+ Assert.assertEquals(210L, message.getRepeatedField(f("repeated_sfixed64"), 0));
+ Assert.assertEquals(211F, message.getRepeatedField(f("repeated_float"), 0));
+ Assert.assertEquals(212D, message.getRepeatedField(f("repeated_double"), 0));
+ Assert.assertEquals(true, message.getRepeatedField(f("repeated_bool"), 0));
+ Assert.assertEquals("215", message.getRepeatedField(f("repeated_string"), 0));
Assert.assertEquals(toBytes("216"), message.getRepeatedField(f("repeated_bytes"), 0));
- Assert.assertEquals(217,
- ((Message)message.getRepeatedField(f("repeatedgroup"), 0))
- .getField(repeatedGroupA));
- Assert.assertEquals(218,
- ((Message)message.getRepeatedField(f("repeated_nested_message"), 0))
- .getField(nestedB));
- Assert.assertEquals(219,
- ((Message)message.getRepeatedField(f("repeated_foreign_message"), 0))
- .getField(foreignC));
- Assert.assertEquals(220,
- ((Message)message.getRepeatedField(f("repeated_import_message"), 0))
- .getField(importD));
- Assert.assertEquals(227,
- ((Message)message.getRepeatedField(f("repeated_lazy_message"), 0))
- .getField(nestedB));
-
- Assert.assertEquals( nestedBar, message.getRepeatedField(f("repeated_nested_enum" ),0));
- Assert.assertEquals(foreignBar, message.getRepeatedField(f("repeated_foreign_enum"),0));
- Assert.assertEquals( importBar, message.getRepeatedField(f("repeated_import_enum" ),0));
+ Assert.assertEquals(
+ 217,
+ ((Message) message.getRepeatedField(f("repeatedgroup"), 0)).getField(repeatedGroupA));
+ Assert.assertEquals(
+ 218,
+ ((Message) message.getRepeatedField(f("repeated_nested_message"), 0)).getField(nestedB));
+ Assert.assertEquals(
+ 219,
+ ((Message) message.getRepeatedField(f("repeated_foreign_message"), 0))
+ .getField(foreignC));
+ Assert.assertEquals(
+ 220,
+ ((Message) message.getRepeatedField(f("repeated_import_message"), 0)).getField(importD));
+ Assert.assertEquals(
+ 227,
+ ((Message) message.getRepeatedField(f("repeated_lazy_message"), 0)).getField(nestedB));
+
+ Assert.assertEquals(nestedBar, message.getRepeatedField(f("repeated_nested_enum"), 0));
+ Assert.assertEquals(foreignBar, message.getRepeatedField(f("repeated_foreign_enum"), 0));
+ Assert.assertEquals(importBar, message.getRepeatedField(f("repeated_import_enum"), 0));
Assert.assertEquals("224", message.getRepeatedField(f("repeated_string_piece"), 0));
Assert.assertEquals("225", message.getRepeatedField(f("repeated_cord"), 0));
- Assert.assertEquals(301 , message.getRepeatedField(f("repeated_int32" ), 1));
- Assert.assertEquals(302L , message.getRepeatedField(f("repeated_int64" ), 1));
- Assert.assertEquals(303 , message.getRepeatedField(f("repeated_uint32" ), 1));
- Assert.assertEquals(304L , message.getRepeatedField(f("repeated_uint64" ), 1));
- Assert.assertEquals(305 , message.getRepeatedField(f("repeated_sint32" ), 1));
- Assert.assertEquals(306L , message.getRepeatedField(f("repeated_sint64" ), 1));
- Assert.assertEquals(307 , message.getRepeatedField(f("repeated_fixed32" ), 1));
- Assert.assertEquals(308L , message.getRepeatedField(f("repeated_fixed64" ), 1));
- Assert.assertEquals(309 , message.getRepeatedField(f("repeated_sfixed32"), 1));
- Assert.assertEquals(310L , message.getRepeatedField(f("repeated_sfixed64"), 1));
- Assert.assertEquals(311F , message.getRepeatedField(f("repeated_float" ), 1));
- Assert.assertEquals(312D , message.getRepeatedField(f("repeated_double" ), 1));
- Assert.assertEquals(false, message.getRepeatedField(f("repeated_bool" ), 1));
- Assert.assertEquals("315", message.getRepeatedField(f("repeated_string" ), 1));
+ Assert.assertEquals(301, message.getRepeatedField(f("repeated_int32"), 1));
+ Assert.assertEquals(302L, message.getRepeatedField(f("repeated_int64"), 1));
+ Assert.assertEquals(303, message.getRepeatedField(f("repeated_uint32"), 1));
+ Assert.assertEquals(304L, message.getRepeatedField(f("repeated_uint64"), 1));
+ Assert.assertEquals(305, message.getRepeatedField(f("repeated_sint32"), 1));
+ Assert.assertEquals(306L, message.getRepeatedField(f("repeated_sint64"), 1));
+ Assert.assertEquals(307, message.getRepeatedField(f("repeated_fixed32"), 1));
+ Assert.assertEquals(308L, message.getRepeatedField(f("repeated_fixed64"), 1));
+ Assert.assertEquals(309, message.getRepeatedField(f("repeated_sfixed32"), 1));
+ Assert.assertEquals(310L, message.getRepeatedField(f("repeated_sfixed64"), 1));
+ Assert.assertEquals(311F, message.getRepeatedField(f("repeated_float"), 1));
+ Assert.assertEquals(312D, message.getRepeatedField(f("repeated_double"), 1));
+ Assert.assertEquals(false, message.getRepeatedField(f("repeated_bool"), 1));
+ Assert.assertEquals("315", message.getRepeatedField(f("repeated_string"), 1));
Assert.assertEquals(toBytes("316"), message.getRepeatedField(f("repeated_bytes"), 1));
- Assert.assertEquals(317,
- ((Message)message.getRepeatedField(f("repeatedgroup"), 1))
- .getField(repeatedGroupA));
- Assert.assertEquals(318,
- ((Message)message.getRepeatedField(f("repeated_nested_message"), 1))
- .getField(nestedB));
- Assert.assertEquals(319,
- ((Message)message.getRepeatedField(f("repeated_foreign_message"), 1))
- .getField(foreignC));
- Assert.assertEquals(320,
- ((Message)message.getRepeatedField(f("repeated_import_message"), 1))
- .getField(importD));
- Assert.assertEquals(327,
- ((Message)message.getRepeatedField(f("repeated_lazy_message"), 1))
- .getField(nestedB));
-
- Assert.assertEquals( nestedBaz, message.getRepeatedField(f("repeated_nested_enum" ),1));
- Assert.assertEquals(foreignBaz, message.getRepeatedField(f("repeated_foreign_enum"),1));
- Assert.assertEquals( importBaz, message.getRepeatedField(f("repeated_import_enum" ),1));
+ Assert.assertEquals(
+ 317,
+ ((Message) message.getRepeatedField(f("repeatedgroup"), 1)).getField(repeatedGroupA));
+ Assert.assertEquals(
+ 318,
+ ((Message) message.getRepeatedField(f("repeated_nested_message"), 1)).getField(nestedB));
+ Assert.assertEquals(
+ 319,
+ ((Message) message.getRepeatedField(f("repeated_foreign_message"), 1))
+ .getField(foreignC));
+ Assert.assertEquals(
+ 320,
+ ((Message) message.getRepeatedField(f("repeated_import_message"), 1)).getField(importD));
+ Assert.assertEquals(
+ 327,
+ ((Message) message.getRepeatedField(f("repeated_lazy_message"), 1)).getField(nestedB));
+
+ Assert.assertEquals(nestedBaz, message.getRepeatedField(f("repeated_nested_enum"), 1));
+ Assert.assertEquals(foreignBaz, message.getRepeatedField(f("repeated_foreign_enum"), 1));
+ Assert.assertEquals(importBaz, message.getRepeatedField(f("repeated_import_enum"), 1));
Assert.assertEquals("324", message.getRepeatedField(f("repeated_string_piece"), 1));
Assert.assertEquals("325", message.getRepeatedField(f("repeated_cord"), 1));
// -----------------------------------------------------------------
- Assert.assertTrue(message.hasField(f("default_int32" )));
- Assert.assertTrue(message.hasField(f("default_int64" )));
- Assert.assertTrue(message.hasField(f("default_uint32" )));
- Assert.assertTrue(message.hasField(f("default_uint64" )));
- Assert.assertTrue(message.hasField(f("default_sint32" )));
- Assert.assertTrue(message.hasField(f("default_sint64" )));
- Assert.assertTrue(message.hasField(f("default_fixed32" )));
- Assert.assertTrue(message.hasField(f("default_fixed64" )));
+ Assert.assertTrue(message.hasField(f("default_int32")));
+ Assert.assertTrue(message.hasField(f("default_int64")));
+ Assert.assertTrue(message.hasField(f("default_uint32")));
+ Assert.assertTrue(message.hasField(f("default_uint64")));
+ Assert.assertTrue(message.hasField(f("default_sint32")));
+ Assert.assertTrue(message.hasField(f("default_sint64")));
+ Assert.assertTrue(message.hasField(f("default_fixed32")));
+ Assert.assertTrue(message.hasField(f("default_fixed64")));
Assert.assertTrue(message.hasField(f("default_sfixed32")));
Assert.assertTrue(message.hasField(f("default_sfixed64")));
- Assert.assertTrue(message.hasField(f("default_float" )));
- Assert.assertTrue(message.hasField(f("default_double" )));
- Assert.assertTrue(message.hasField(f("default_bool" )));
- Assert.assertTrue(message.hasField(f("default_string" )));
- Assert.assertTrue(message.hasField(f("default_bytes" )));
+ Assert.assertTrue(message.hasField(f("default_float")));
+ Assert.assertTrue(message.hasField(f("default_double")));
+ Assert.assertTrue(message.hasField(f("default_bool")));
+ Assert.assertTrue(message.hasField(f("default_string")));
+ Assert.assertTrue(message.hasField(f("default_bytes")));
- Assert.assertTrue(message.hasField(f("default_nested_enum" )));
+ Assert.assertTrue(message.hasField(f("default_nested_enum")));
Assert.assertTrue(message.hasField(f("default_foreign_enum")));
- Assert.assertTrue(message.hasField(f("default_import_enum" )));
+ Assert.assertTrue(message.hasField(f("default_import_enum")));
Assert.assertTrue(message.hasField(f("default_string_piece")));
Assert.assertTrue(message.hasField(f("default_cord")));
- Assert.assertEquals(401 , message.getField(f("default_int32" )));
- Assert.assertEquals(402L , message.getField(f("default_int64" )));
- Assert.assertEquals(403 , message.getField(f("default_uint32" )));
- Assert.assertEquals(404L , message.getField(f("default_uint64" )));
- Assert.assertEquals(405 , message.getField(f("default_sint32" )));
- Assert.assertEquals(406L , message.getField(f("default_sint64" )));
- Assert.assertEquals(407 , message.getField(f("default_fixed32" )));
- Assert.assertEquals(408L , message.getField(f("default_fixed64" )));
- Assert.assertEquals(409 , message.getField(f("default_sfixed32")));
- Assert.assertEquals(410L , message.getField(f("default_sfixed64")));
- Assert.assertEquals(411F , message.getField(f("default_float" )));
- Assert.assertEquals(412D , message.getField(f("default_double" )));
- Assert.assertEquals(false, message.getField(f("default_bool" )));
- Assert.assertEquals("415", message.getField(f("default_string" )));
+ Assert.assertEquals(401, message.getField(f("default_int32")));
+ Assert.assertEquals(402L, message.getField(f("default_int64")));
+ Assert.assertEquals(403, message.getField(f("default_uint32")));
+ Assert.assertEquals(404L, message.getField(f("default_uint64")));
+ Assert.assertEquals(405, message.getField(f("default_sint32")));
+ Assert.assertEquals(406L, message.getField(f("default_sint64")));
+ Assert.assertEquals(407, message.getField(f("default_fixed32")));
+ Assert.assertEquals(408L, message.getField(f("default_fixed64")));
+ Assert.assertEquals(409, message.getField(f("default_sfixed32")));
+ Assert.assertEquals(410L, message.getField(f("default_sfixed64")));
+ Assert.assertEquals(411F, message.getField(f("default_float")));
+ Assert.assertEquals(412D, message.getField(f("default_double")));
+ Assert.assertEquals(false, message.getField(f("default_bool")));
+ Assert.assertEquals("415", message.getField(f("default_string")));
Assert.assertEquals(toBytes("416"), message.getField(f("default_bytes")));
- Assert.assertEquals( nestedFoo, message.getField(f("default_nested_enum" )));
+ Assert.assertEquals(nestedFoo, message.getField(f("default_nested_enum")));
Assert.assertEquals(foreignFoo, message.getField(f("default_foreign_enum")));
- Assert.assertEquals( importFoo, message.getField(f("default_import_enum" )));
+ Assert.assertEquals(importFoo, message.getField(f("default_import_enum")));
Assert.assertEquals("424", message.getField(f("default_string_piece")));
Assert.assertEquals("425", message.getField(f("default_cord")));
@@ -3289,9 +3274,9 @@ public final class TestUtil {
Assert.assertTrue(message.hasField(f("oneof_nested_message")));
Assert.assertTrue(message.hasField(f("oneof_string")));
Assert.assertEquals(601, message.getField(f("oneof_uint32")));
- Assert.assertEquals(602,
- ((MessageOrBuilder) message.getField(f("oneof_nested_message")))
- .getField(nestedB));
+ Assert.assertEquals(
+ 602,
+ ((MessageOrBuilder) message.getField(f("oneof_nested_message"))).getField(nestedB));
Assert.assertEquals("603", message.getField(f("oneof_string")));
}
}
@@ -3299,175 +3284,163 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all fields of
- * {@code message} are cleared, and that getting the fields returns their
- * default values, using the {@link Message} reflection interface.
+ * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are cleared,
+ * and that getting the fields returns their default values, using the {@link Message}
+ * reflection interface.
*/
public void assertClearViaReflection(MessageOrBuilder message) {
// has_blah() should initially be false for all optional fields.
- Assert.assertFalse(message.hasField(f("optional_int32" )));
- Assert.assertFalse(message.hasField(f("optional_int64" )));
- Assert.assertFalse(message.hasField(f("optional_uint32" )));
- Assert.assertFalse(message.hasField(f("optional_uint64" )));
- Assert.assertFalse(message.hasField(f("optional_sint32" )));
- Assert.assertFalse(message.hasField(f("optional_sint64" )));
- Assert.assertFalse(message.hasField(f("optional_fixed32" )));
- Assert.assertFalse(message.hasField(f("optional_fixed64" )));
+ Assert.assertFalse(message.hasField(f("optional_int32")));
+ Assert.assertFalse(message.hasField(f("optional_int64")));
+ Assert.assertFalse(message.hasField(f("optional_uint32")));
+ Assert.assertFalse(message.hasField(f("optional_uint64")));
+ Assert.assertFalse(message.hasField(f("optional_sint32")));
+ Assert.assertFalse(message.hasField(f("optional_sint64")));
+ Assert.assertFalse(message.hasField(f("optional_fixed32")));
+ Assert.assertFalse(message.hasField(f("optional_fixed64")));
Assert.assertFalse(message.hasField(f("optional_sfixed32")));
Assert.assertFalse(message.hasField(f("optional_sfixed64")));
- Assert.assertFalse(message.hasField(f("optional_float" )));
- Assert.assertFalse(message.hasField(f("optional_double" )));
- Assert.assertFalse(message.hasField(f("optional_bool" )));
- Assert.assertFalse(message.hasField(f("optional_string" )));
- Assert.assertFalse(message.hasField(f("optional_bytes" )));
-
- Assert.assertFalse(message.hasField(f("optionalgroup" )));
- Assert.assertFalse(message.hasField(f("optional_nested_message" )));
+ Assert.assertFalse(message.hasField(f("optional_float")));
+ Assert.assertFalse(message.hasField(f("optional_double")));
+ Assert.assertFalse(message.hasField(f("optional_bool")));
+ Assert.assertFalse(message.hasField(f("optional_string")));
+ Assert.assertFalse(message.hasField(f("optional_bytes")));
+
+ Assert.assertFalse(message.hasField(f("optionalgroup")));
+ Assert.assertFalse(message.hasField(f("optional_nested_message")));
Assert.assertFalse(message.hasField(f("optional_foreign_message")));
- Assert.assertFalse(message.hasField(f("optional_import_message" )));
+ Assert.assertFalse(message.hasField(f("optional_import_message")));
- Assert.assertFalse(message.hasField(f("optional_nested_enum" )));
+ Assert.assertFalse(message.hasField(f("optional_nested_enum")));
Assert.assertFalse(message.hasField(f("optional_foreign_enum")));
- Assert.assertFalse(message.hasField(f("optional_import_enum" )));
+ Assert.assertFalse(message.hasField(f("optional_import_enum")));
Assert.assertFalse(message.hasField(f("optional_string_piece")));
Assert.assertFalse(message.hasField(f("optional_cord")));
// Optional fields without defaults are set to zero or something like it.
- Assert.assertEquals(0 , message.getField(f("optional_int32" )));
- Assert.assertEquals(0L , message.getField(f("optional_int64" )));
- Assert.assertEquals(0 , message.getField(f("optional_uint32" )));
- Assert.assertEquals(0L , message.getField(f("optional_uint64" )));
- Assert.assertEquals(0 , message.getField(f("optional_sint32" )));
- Assert.assertEquals(0L , message.getField(f("optional_sint64" )));
- Assert.assertEquals(0 , message.getField(f("optional_fixed32" )));
- Assert.assertEquals(0L , message.getField(f("optional_fixed64" )));
- Assert.assertEquals(0 , message.getField(f("optional_sfixed32")));
- Assert.assertEquals(0L , message.getField(f("optional_sfixed64")));
- Assert.assertEquals(0F , message.getField(f("optional_float" )));
- Assert.assertEquals(0D , message.getField(f("optional_double" )));
- Assert.assertEquals(false, message.getField(f("optional_bool" )));
- Assert.assertEquals("" , message.getField(f("optional_string" )));
+ Assert.assertEquals(0, message.getField(f("optional_int32")));
+ Assert.assertEquals(0L, message.getField(f("optional_int64")));
+ Assert.assertEquals(0, message.getField(f("optional_uint32")));
+ Assert.assertEquals(0L, message.getField(f("optional_uint64")));
+ Assert.assertEquals(0, message.getField(f("optional_sint32")));
+ Assert.assertEquals(0L, message.getField(f("optional_sint64")));
+ Assert.assertEquals(0, message.getField(f("optional_fixed32")));
+ Assert.assertEquals(0L, message.getField(f("optional_fixed64")));
+ Assert.assertEquals(0, message.getField(f("optional_sfixed32")));
+ Assert.assertEquals(0L, message.getField(f("optional_sfixed64")));
+ Assert.assertEquals(0F, message.getField(f("optional_float")));
+ Assert.assertEquals(0D, message.getField(f("optional_double")));
+ Assert.assertEquals(false, message.getField(f("optional_bool")));
+ Assert.assertEquals("", message.getField(f("optional_string")));
Assert.assertEquals(ByteString.EMPTY, message.getField(f("optional_bytes")));
// Embedded messages should also be clear.
+ Assert.assertFalse(((Message) message.getField(f("optionalgroup"))).hasField(groupA));
Assert.assertFalse(
- ((Message)message.getField(f("optionalgroup"))).hasField(groupA));
+ ((Message) message.getField(f("optional_nested_message"))).hasField(nestedB));
Assert.assertFalse(
- ((Message)message.getField(f("optional_nested_message")))
- .hasField(nestedB));
+ ((Message) message.getField(f("optional_foreign_message"))).hasField(foreignC));
Assert.assertFalse(
- ((Message)message.getField(f("optional_foreign_message")))
- .hasField(foreignC));
+ ((Message) message.getField(f("optional_import_message"))).hasField(importD));
Assert.assertFalse(
- ((Message)message.getField(f("optional_import_message")))
- .hasField(importD));
+ ((Message) message.getField(f("optional_public_import_message"))).hasField(importE));
Assert.assertFalse(
- ((Message)message.getField(f("optional_public_import_message")))
- .hasField(importE));
- Assert.assertFalse(
- ((Message)message.getField(f("optional_lazy_message")))
- .hasField(nestedB));
-
- Assert.assertEquals(0,
- ((Message)message.getField(f("optionalgroup"))).getField(groupA));
- Assert.assertEquals(0,
- ((Message)message.getField(f("optional_nested_message")))
- .getField(nestedB));
- Assert.assertEquals(0,
- ((Message)message.getField(f("optional_foreign_message")))
- .getField(foreignC));
- Assert.assertEquals(0,
- ((Message)message.getField(f("optional_import_message")))
- .getField(importD));
- Assert.assertEquals(0,
- ((Message)message.getField(f("optional_public_import_message")))
- .getField(importE));
- Assert.assertEquals(0,
- ((Message)message.getField(f("optional_lazy_message")))
- .getField(nestedB));
+ ((Message) message.getField(f("optional_lazy_message"))).hasField(nestedB));
+
+ Assert.assertEquals(0, ((Message) message.getField(f("optionalgroup"))).getField(groupA));
+ Assert.assertEquals(
+ 0, ((Message) message.getField(f("optional_nested_message"))).getField(nestedB));
+ Assert.assertEquals(
+ 0, ((Message) message.getField(f("optional_foreign_message"))).getField(foreignC));
+ Assert.assertEquals(
+ 0, ((Message) message.getField(f("optional_import_message"))).getField(importD));
+ Assert.assertEquals(
+ 0, ((Message) message.getField(f("optional_public_import_message"))).getField(importE));
+ Assert.assertEquals(
+ 0, ((Message) message.getField(f("optional_lazy_message"))).getField(nestedB));
// Enums without defaults are set to the first value in the enum.
- Assert.assertEquals( nestedFoo, message.getField(f("optional_nested_enum" )));
+ Assert.assertEquals(nestedFoo, message.getField(f("optional_nested_enum")));
Assert.assertEquals(foreignFoo, message.getField(f("optional_foreign_enum")));
- Assert.assertEquals( importFoo, message.getField(f("optional_import_enum" )));
+ Assert.assertEquals(importFoo, message.getField(f("optional_import_enum")));
Assert.assertEquals("", message.getField(f("optional_string_piece")));
Assert.assertEquals("", message.getField(f("optional_cord")));
// Repeated fields are empty.
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_int32" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_int64" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_uint32" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_uint64" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sint32" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sint64" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_fixed32" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_fixed64" )));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_int32")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_int64")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_uint32")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_uint64")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sint32")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sint64")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_fixed32")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_fixed64")));
Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sfixed32")));
Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sfixed64")));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_float" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_double" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_bool" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_string" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_bytes" )));
-
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeatedgroup" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_nested_message" )));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_float")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_double")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_bool")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_string")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_bytes")));
+
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeatedgroup")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_nested_message")));
Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_foreign_message")));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_import_message" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_lazy_message" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_nested_enum" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_foreign_enum" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_import_enum" )));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_import_message")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_lazy_message")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_nested_enum")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_foreign_enum")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_import_enum")));
Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_string_piece")));
Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_cord")));
// has_blah() should also be false for all default fields.
- Assert.assertFalse(message.hasField(f("default_int32" )));
- Assert.assertFalse(message.hasField(f("default_int64" )));
- Assert.assertFalse(message.hasField(f("default_uint32" )));
- Assert.assertFalse(message.hasField(f("default_uint64" )));
- Assert.assertFalse(message.hasField(f("default_sint32" )));
- Assert.assertFalse(message.hasField(f("default_sint64" )));
- Assert.assertFalse(message.hasField(f("default_fixed32" )));
- Assert.assertFalse(message.hasField(f("default_fixed64" )));
+ Assert.assertFalse(message.hasField(f("default_int32")));
+ Assert.assertFalse(message.hasField(f("default_int64")));
+ Assert.assertFalse(message.hasField(f("default_uint32")));
+ Assert.assertFalse(message.hasField(f("default_uint64")));
+ Assert.assertFalse(message.hasField(f("default_sint32")));
+ Assert.assertFalse(message.hasField(f("default_sint64")));
+ Assert.assertFalse(message.hasField(f("default_fixed32")));
+ Assert.assertFalse(message.hasField(f("default_fixed64")));
Assert.assertFalse(message.hasField(f("default_sfixed32")));
Assert.assertFalse(message.hasField(f("default_sfixed64")));
- Assert.assertFalse(message.hasField(f("default_float" )));
- Assert.assertFalse(message.hasField(f("default_double" )));
- Assert.assertFalse(message.hasField(f("default_bool" )));
- Assert.assertFalse(message.hasField(f("default_string" )));
- Assert.assertFalse(message.hasField(f("default_bytes" )));
+ Assert.assertFalse(message.hasField(f("default_float")));
+ Assert.assertFalse(message.hasField(f("default_double")));
+ Assert.assertFalse(message.hasField(f("default_bool")));
+ Assert.assertFalse(message.hasField(f("default_string")));
+ Assert.assertFalse(message.hasField(f("default_bytes")));
- Assert.assertFalse(message.hasField(f("default_nested_enum" )));
+ Assert.assertFalse(message.hasField(f("default_nested_enum")));
Assert.assertFalse(message.hasField(f("default_foreign_enum")));
- Assert.assertFalse(message.hasField(f("default_import_enum" )));
+ Assert.assertFalse(message.hasField(f("default_import_enum")));
- Assert.assertFalse(message.hasField(f("default_string_piece" )));
- Assert.assertFalse(message.hasField(f("default_cord" )));
+ Assert.assertFalse(message.hasField(f("default_string_piece")));
+ Assert.assertFalse(message.hasField(f("default_cord")));
// Fields with defaults have their default values (duh).
- Assert.assertEquals( 41 , message.getField(f("default_int32" )));
- Assert.assertEquals( 42L , message.getField(f("default_int64" )));
- Assert.assertEquals( 43 , message.getField(f("default_uint32" )));
- Assert.assertEquals( 44L , message.getField(f("default_uint64" )));
- Assert.assertEquals(-45 , message.getField(f("default_sint32" )));
- Assert.assertEquals( 46L , message.getField(f("default_sint64" )));
- Assert.assertEquals( 47 , message.getField(f("default_fixed32" )));
- Assert.assertEquals( 48L , message.getField(f("default_fixed64" )));
- Assert.assertEquals( 49 , message.getField(f("default_sfixed32")));
- Assert.assertEquals(-50L , message.getField(f("default_sfixed64")));
- Assert.assertEquals( 51.5F , message.getField(f("default_float" )));
- Assert.assertEquals( 52e3D , message.getField(f("default_double" )));
- Assert.assertEquals(true , message.getField(f("default_bool" )));
- Assert.assertEquals("hello", message.getField(f("default_string" )));
+ Assert.assertEquals(41, message.getField(f("default_int32")));
+ Assert.assertEquals(42L, message.getField(f("default_int64")));
+ Assert.assertEquals(43, message.getField(f("default_uint32")));
+ Assert.assertEquals(44L, message.getField(f("default_uint64")));
+ Assert.assertEquals(-45, message.getField(f("default_sint32")));
+ Assert.assertEquals(46L, message.getField(f("default_sint64")));
+ Assert.assertEquals(47, message.getField(f("default_fixed32")));
+ Assert.assertEquals(48L, message.getField(f("default_fixed64")));
+ Assert.assertEquals(49, message.getField(f("default_sfixed32")));
+ Assert.assertEquals(-50L, message.getField(f("default_sfixed64")));
+ Assert.assertEquals(51.5F, message.getField(f("default_float")));
+ Assert.assertEquals(52e3D, message.getField(f("default_double")));
+ Assert.assertEquals(true, message.getField(f("default_bool")));
+ Assert.assertEquals("hello", message.getField(f("default_string")));
Assert.assertEquals(toBytes("world"), message.getField(f("default_bytes")));
- Assert.assertEquals( nestedBar, message.getField(f("default_nested_enum" )));
+ Assert.assertEquals(nestedBar, message.getField(f("default_nested_enum")));
Assert.assertEquals(foreignBar, message.getField(f("default_foreign_enum")));
- Assert.assertEquals( importBar, message.getField(f("default_import_enum" )));
+ Assert.assertEquals(importBar, message.getField(f("default_import_enum")));
Assert.assertEquals("abc", message.getField(f("default_string_piece")));
Assert.assertEquals("123", message.getField(f("default_cord")));
@@ -3482,205 +3455,204 @@ public final class TestUtil {
Assert.assertEquals(toBytes(""), message.getField(f("oneof_bytes")));
}
-
// ---------------------------------------------------------------
- public void assertRepeatedFieldsModifiedViaReflection(
- MessageOrBuilder message) {
+ public void assertRepeatedFieldsModifiedViaReflection(MessageOrBuilder message) {
// ModifyRepeatedFields only sets the second repeated element of each
// field. In addition to verifying this, we also verify that the first
// element and size were *not* modified.
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int64" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint64" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint64" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed64" )));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int64")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint64")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint64")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed64")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed32")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed64")));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_float" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_double" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bool" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bytes" )));
-
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeatedgroup" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_message" )));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_float")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_double")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bool")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bytes")));
+
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeatedgroup")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_message")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_message")));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_message" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_lazy_message" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_enum" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_enum" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_enum" )));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_message")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_lazy_message")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_enum")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_enum")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_enum")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string_piece")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_cord")));
- Assert.assertEquals(201 , message.getRepeatedField(f("repeated_int32" ), 0));
- Assert.assertEquals(202L , message.getRepeatedField(f("repeated_int64" ), 0));
- Assert.assertEquals(203 , message.getRepeatedField(f("repeated_uint32" ), 0));
- Assert.assertEquals(204L , message.getRepeatedField(f("repeated_uint64" ), 0));
- Assert.assertEquals(205 , message.getRepeatedField(f("repeated_sint32" ), 0));
- Assert.assertEquals(206L , message.getRepeatedField(f("repeated_sint64" ), 0));
- Assert.assertEquals(207 , message.getRepeatedField(f("repeated_fixed32" ), 0));
- Assert.assertEquals(208L , message.getRepeatedField(f("repeated_fixed64" ), 0));
- Assert.assertEquals(209 , message.getRepeatedField(f("repeated_sfixed32"), 0));
- Assert.assertEquals(210L , message.getRepeatedField(f("repeated_sfixed64"), 0));
- Assert.assertEquals(211F , message.getRepeatedField(f("repeated_float" ), 0));
- Assert.assertEquals(212D , message.getRepeatedField(f("repeated_double" ), 0));
- Assert.assertEquals(true , message.getRepeatedField(f("repeated_bool" ), 0));
- Assert.assertEquals("215", message.getRepeatedField(f("repeated_string" ), 0));
+ Assert.assertEquals(201, message.getRepeatedField(f("repeated_int32"), 0));
+ Assert.assertEquals(202L, message.getRepeatedField(f("repeated_int64"), 0));
+ Assert.assertEquals(203, message.getRepeatedField(f("repeated_uint32"), 0));
+ Assert.assertEquals(204L, message.getRepeatedField(f("repeated_uint64"), 0));
+ Assert.assertEquals(205, message.getRepeatedField(f("repeated_sint32"), 0));
+ Assert.assertEquals(206L, message.getRepeatedField(f("repeated_sint64"), 0));
+ Assert.assertEquals(207, message.getRepeatedField(f("repeated_fixed32"), 0));
+ Assert.assertEquals(208L, message.getRepeatedField(f("repeated_fixed64"), 0));
+ Assert.assertEquals(209, message.getRepeatedField(f("repeated_sfixed32"), 0));
+ Assert.assertEquals(210L, message.getRepeatedField(f("repeated_sfixed64"), 0));
+ Assert.assertEquals(211F, message.getRepeatedField(f("repeated_float"), 0));
+ Assert.assertEquals(212D, message.getRepeatedField(f("repeated_double"), 0));
+ Assert.assertEquals(true, message.getRepeatedField(f("repeated_bool"), 0));
+ Assert.assertEquals("215", message.getRepeatedField(f("repeated_string"), 0));
Assert.assertEquals(toBytes("216"), message.getRepeatedField(f("repeated_bytes"), 0));
- Assert.assertEquals(217,
- ((Message)message.getRepeatedField(f("repeatedgroup"), 0))
- .getField(repeatedGroupA));
- Assert.assertEquals(218,
- ((Message)message.getRepeatedField(f("repeated_nested_message"), 0))
- .getField(nestedB));
- Assert.assertEquals(219,
- ((Message)message.getRepeatedField(f("repeated_foreign_message"), 0))
- .getField(foreignC));
- Assert.assertEquals(220,
- ((Message)message.getRepeatedField(f("repeated_import_message"), 0))
- .getField(importD));
- Assert.assertEquals(227,
- ((Message)message.getRepeatedField(f("repeated_lazy_message"), 0))
- .getField(nestedB));
-
- Assert.assertEquals( nestedBar, message.getRepeatedField(f("repeated_nested_enum" ),0));
- Assert.assertEquals(foreignBar, message.getRepeatedField(f("repeated_foreign_enum"),0));
- Assert.assertEquals( importBar, message.getRepeatedField(f("repeated_import_enum" ),0));
+ Assert.assertEquals(
+ 217,
+ ((Message) message.getRepeatedField(f("repeatedgroup"), 0)).getField(repeatedGroupA));
+ Assert.assertEquals(
+ 218,
+ ((Message) message.getRepeatedField(f("repeated_nested_message"), 0)).getField(nestedB));
+ Assert.assertEquals(
+ 219,
+ ((Message) message.getRepeatedField(f("repeated_foreign_message"), 0))
+ .getField(foreignC));
+ Assert.assertEquals(
+ 220,
+ ((Message) message.getRepeatedField(f("repeated_import_message"), 0)).getField(importD));
+ Assert.assertEquals(
+ 227,
+ ((Message) message.getRepeatedField(f("repeated_lazy_message"), 0)).getField(nestedB));
+
+ Assert.assertEquals(nestedBar, message.getRepeatedField(f("repeated_nested_enum"), 0));
+ Assert.assertEquals(foreignBar, message.getRepeatedField(f("repeated_foreign_enum"), 0));
+ Assert.assertEquals(importBar, message.getRepeatedField(f("repeated_import_enum"), 0));
Assert.assertEquals("224", message.getRepeatedField(f("repeated_string_piece"), 0));
Assert.assertEquals("225", message.getRepeatedField(f("repeated_cord"), 0));
- Assert.assertEquals(501 , message.getRepeatedField(f("repeated_int32" ), 1));
- Assert.assertEquals(502L , message.getRepeatedField(f("repeated_int64" ), 1));
- Assert.assertEquals(503 , message.getRepeatedField(f("repeated_uint32" ), 1));
- Assert.assertEquals(504L , message.getRepeatedField(f("repeated_uint64" ), 1));
- Assert.assertEquals(505 , message.getRepeatedField(f("repeated_sint32" ), 1));
- Assert.assertEquals(506L , message.getRepeatedField(f("repeated_sint64" ), 1));
- Assert.assertEquals(507 , message.getRepeatedField(f("repeated_fixed32" ), 1));
- Assert.assertEquals(508L , message.getRepeatedField(f("repeated_fixed64" ), 1));
- Assert.assertEquals(509 , message.getRepeatedField(f("repeated_sfixed32"), 1));
- Assert.assertEquals(510L , message.getRepeatedField(f("repeated_sfixed64"), 1));
- Assert.assertEquals(511F , message.getRepeatedField(f("repeated_float" ), 1));
- Assert.assertEquals(512D , message.getRepeatedField(f("repeated_double" ), 1));
- Assert.assertEquals(true , message.getRepeatedField(f("repeated_bool" ), 1));
- Assert.assertEquals("515", message.getRepeatedField(f("repeated_string" ), 1));
+ Assert.assertEquals(501, message.getRepeatedField(f("repeated_int32"), 1));
+ Assert.assertEquals(502L, message.getRepeatedField(f("repeated_int64"), 1));
+ Assert.assertEquals(503, message.getRepeatedField(f("repeated_uint32"), 1));
+ Assert.assertEquals(504L, message.getRepeatedField(f("repeated_uint64"), 1));
+ Assert.assertEquals(505, message.getRepeatedField(f("repeated_sint32"), 1));
+ Assert.assertEquals(506L, message.getRepeatedField(f("repeated_sint64"), 1));
+ Assert.assertEquals(507, message.getRepeatedField(f("repeated_fixed32"), 1));
+ Assert.assertEquals(508L, message.getRepeatedField(f("repeated_fixed64"), 1));
+ Assert.assertEquals(509, message.getRepeatedField(f("repeated_sfixed32"), 1));
+ Assert.assertEquals(510L, message.getRepeatedField(f("repeated_sfixed64"), 1));
+ Assert.assertEquals(511F, message.getRepeatedField(f("repeated_float"), 1));
+ Assert.assertEquals(512D, message.getRepeatedField(f("repeated_double"), 1));
+ Assert.assertEquals(true, message.getRepeatedField(f("repeated_bool"), 1));
+ Assert.assertEquals("515", message.getRepeatedField(f("repeated_string"), 1));
Assert.assertEquals(toBytes("516"), message.getRepeatedField(f("repeated_bytes"), 1));
- Assert.assertEquals(517,
- ((Message)message.getRepeatedField(f("repeatedgroup"), 1))
- .getField(repeatedGroupA));
- Assert.assertEquals(518,
- ((Message)message.getRepeatedField(f("repeated_nested_message"), 1))
- .getField(nestedB));
- Assert.assertEquals(519,
- ((Message)message.getRepeatedField(f("repeated_foreign_message"), 1))
- .getField(foreignC));
- Assert.assertEquals(520,
- ((Message)message.getRepeatedField(f("repeated_import_message"), 1))
- .getField(importD));
- Assert.assertEquals(527,
- ((Message)message.getRepeatedField(f("repeated_lazy_message"), 1))
- .getField(nestedB));
-
- Assert.assertEquals( nestedFoo, message.getRepeatedField(f("repeated_nested_enum" ),1));
- Assert.assertEquals(foreignFoo, message.getRepeatedField(f("repeated_foreign_enum"),1));
- Assert.assertEquals( importFoo, message.getRepeatedField(f("repeated_import_enum" ),1));
+ Assert.assertEquals(
+ 517,
+ ((Message) message.getRepeatedField(f("repeatedgroup"), 1)).getField(repeatedGroupA));
+ Assert.assertEquals(
+ 518,
+ ((Message) message.getRepeatedField(f("repeated_nested_message"), 1)).getField(nestedB));
+ Assert.assertEquals(
+ 519,
+ ((Message) message.getRepeatedField(f("repeated_foreign_message"), 1))
+ .getField(foreignC));
+ Assert.assertEquals(
+ 520,
+ ((Message) message.getRepeatedField(f("repeated_import_message"), 1)).getField(importD));
+ Assert.assertEquals(
+ 527,
+ ((Message) message.getRepeatedField(f("repeated_lazy_message"), 1)).getField(nestedB));
+
+ Assert.assertEquals(nestedFoo, message.getRepeatedField(f("repeated_nested_enum"), 1));
+ Assert.assertEquals(foreignFoo, message.getRepeatedField(f("repeated_foreign_enum"), 1));
+ Assert.assertEquals(importFoo, message.getRepeatedField(f("repeated_import_enum"), 1));
Assert.assertEquals("524", message.getRepeatedField(f("repeated_string_piece"), 1));
Assert.assertEquals("525", message.getRepeatedField(f("repeated_cord"), 1));
}
public void setPackedFieldsViaReflection(Message.Builder message) {
- message.addRepeatedField(f("packed_int32" ), 601 );
- message.addRepeatedField(f("packed_int64" ), 602L);
- message.addRepeatedField(f("packed_uint32" ), 603 );
- message.addRepeatedField(f("packed_uint64" ), 604L);
- message.addRepeatedField(f("packed_sint32" ), 605 );
- message.addRepeatedField(f("packed_sint64" ), 606L);
- message.addRepeatedField(f("packed_fixed32" ), 607 );
- message.addRepeatedField(f("packed_fixed64" ), 608L);
- message.addRepeatedField(f("packed_sfixed32"), 609 );
+ message.addRepeatedField(f("packed_int32"), 601);
+ message.addRepeatedField(f("packed_int64"), 602L);
+ message.addRepeatedField(f("packed_uint32"), 603);
+ message.addRepeatedField(f("packed_uint64"), 604L);
+ message.addRepeatedField(f("packed_sint32"), 605);
+ message.addRepeatedField(f("packed_sint64"), 606L);
+ message.addRepeatedField(f("packed_fixed32"), 607);
+ message.addRepeatedField(f("packed_fixed64"), 608L);
+ message.addRepeatedField(f("packed_sfixed32"), 609);
message.addRepeatedField(f("packed_sfixed64"), 610L);
- message.addRepeatedField(f("packed_float" ), 611F);
- message.addRepeatedField(f("packed_double" ), 612D);
- message.addRepeatedField(f("packed_bool" ), true);
- message.addRepeatedField(f("packed_enum" ), foreignBar);
+ message.addRepeatedField(f("packed_float"), 611F);
+ message.addRepeatedField(f("packed_double"), 612D);
+ message.addRepeatedField(f("packed_bool"), true);
+ message.addRepeatedField(f("packed_enum"), foreignBar);
// Add a second one of each field.
- message.addRepeatedField(f("packed_int32" ), 701 );
- message.addRepeatedField(f("packed_int64" ), 702L);
- message.addRepeatedField(f("packed_uint32" ), 703 );
- message.addRepeatedField(f("packed_uint64" ), 704L);
- message.addRepeatedField(f("packed_sint32" ), 705 );
- message.addRepeatedField(f("packed_sint64" ), 706L);
- message.addRepeatedField(f("packed_fixed32" ), 707 );
- message.addRepeatedField(f("packed_fixed64" ), 708L);
- message.addRepeatedField(f("packed_sfixed32"), 709 );
+ message.addRepeatedField(f("packed_int32"), 701);
+ message.addRepeatedField(f("packed_int64"), 702L);
+ message.addRepeatedField(f("packed_uint32"), 703);
+ message.addRepeatedField(f("packed_uint64"), 704L);
+ message.addRepeatedField(f("packed_sint32"), 705);
+ message.addRepeatedField(f("packed_sint64"), 706L);
+ message.addRepeatedField(f("packed_fixed32"), 707);
+ message.addRepeatedField(f("packed_fixed64"), 708L);
+ message.addRepeatedField(f("packed_sfixed32"), 709);
message.addRepeatedField(f("packed_sfixed64"), 710L);
- message.addRepeatedField(f("packed_float" ), 711F);
- message.addRepeatedField(f("packed_double" ), 712D);
- message.addRepeatedField(f("packed_bool" ), false);
- message.addRepeatedField(f("packed_enum" ), foreignBaz);
+ message.addRepeatedField(f("packed_float"), 711F);
+ message.addRepeatedField(f("packed_double"), 712D);
+ message.addRepeatedField(f("packed_bool"), false);
+ message.addRepeatedField(f("packed_enum"), foreignBaz);
}
public void assertPackedFieldsSetViaReflection(MessageOrBuilder message) {
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_int32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_int64" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_uint32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_uint64" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sint32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sint64" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_fixed32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_fixed64" )));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_int32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_int64")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_uint32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_uint64")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sint32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sint64")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_fixed32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_fixed64")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sfixed32")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sfixed64")));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_float" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_double" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_bool" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_enum" )));
- Assert.assertEquals(601 , message.getRepeatedField(f("packed_int32" ), 0));
- Assert.assertEquals(602L , message.getRepeatedField(f("packed_int64" ), 0));
- Assert.assertEquals(603 , message.getRepeatedField(f("packed_uint32" ), 0));
- Assert.assertEquals(604L , message.getRepeatedField(f("packed_uint64" ), 0));
- Assert.assertEquals(605 , message.getRepeatedField(f("packed_sint32" ), 0));
- Assert.assertEquals(606L , message.getRepeatedField(f("packed_sint64" ), 0));
- Assert.assertEquals(607 , message.getRepeatedField(f("packed_fixed32" ), 0));
- Assert.assertEquals(608L , message.getRepeatedField(f("packed_fixed64" ), 0));
- Assert.assertEquals(609 , message.getRepeatedField(f("packed_sfixed32"), 0));
- Assert.assertEquals(610L , message.getRepeatedField(f("packed_sfixed64"), 0));
- Assert.assertEquals(611F , message.getRepeatedField(f("packed_float" ), 0));
- Assert.assertEquals(612D , message.getRepeatedField(f("packed_double" ), 0));
- Assert.assertEquals(true , message.getRepeatedField(f("packed_bool" ), 0));
- Assert.assertEquals(foreignBar, message.getRepeatedField(f("packed_enum" ),0));
- Assert.assertEquals(701 , message.getRepeatedField(f("packed_int32" ), 1));
- Assert.assertEquals(702L , message.getRepeatedField(f("packed_int64" ), 1));
- Assert.assertEquals(703 , message.getRepeatedField(f("packed_uint32" ), 1));
- Assert.assertEquals(704L , message.getRepeatedField(f("packed_uint64" ), 1));
- Assert.assertEquals(705 , message.getRepeatedField(f("packed_sint32" ), 1));
- Assert.assertEquals(706L , message.getRepeatedField(f("packed_sint64" ), 1));
- Assert.assertEquals(707 , message.getRepeatedField(f("packed_fixed32" ), 1));
- Assert.assertEquals(708L , message.getRepeatedField(f("packed_fixed64" ), 1));
- Assert.assertEquals(709 , message.getRepeatedField(f("packed_sfixed32"), 1));
- Assert.assertEquals(710L , message.getRepeatedField(f("packed_sfixed64"), 1));
- Assert.assertEquals(711F , message.getRepeatedField(f("packed_float" ), 1));
- Assert.assertEquals(712D , message.getRepeatedField(f("packed_double" ), 1));
- Assert.assertEquals(false, message.getRepeatedField(f("packed_bool" ), 1));
- Assert.assertEquals(foreignBaz, message.getRepeatedField(f("packed_enum" ),1));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_float")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_double")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_bool")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_enum")));
+ Assert.assertEquals(601, message.getRepeatedField(f("packed_int32"), 0));
+ Assert.assertEquals(602L, message.getRepeatedField(f("packed_int64"), 0));
+ Assert.assertEquals(603, message.getRepeatedField(f("packed_uint32"), 0));
+ Assert.assertEquals(604L, message.getRepeatedField(f("packed_uint64"), 0));
+ Assert.assertEquals(605, message.getRepeatedField(f("packed_sint32"), 0));
+ Assert.assertEquals(606L, message.getRepeatedField(f("packed_sint64"), 0));
+ Assert.assertEquals(607, message.getRepeatedField(f("packed_fixed32"), 0));
+ Assert.assertEquals(608L, message.getRepeatedField(f("packed_fixed64"), 0));
+ Assert.assertEquals(609, message.getRepeatedField(f("packed_sfixed32"), 0));
+ Assert.assertEquals(610L, message.getRepeatedField(f("packed_sfixed64"), 0));
+ Assert.assertEquals(611F, message.getRepeatedField(f("packed_float"), 0));
+ Assert.assertEquals(612D, message.getRepeatedField(f("packed_double"), 0));
+ Assert.assertEquals(true, message.getRepeatedField(f("packed_bool"), 0));
+ Assert.assertEquals(foreignBar, message.getRepeatedField(f("packed_enum"), 0));
+ Assert.assertEquals(701, message.getRepeatedField(f("packed_int32"), 1));
+ Assert.assertEquals(702L, message.getRepeatedField(f("packed_int64"), 1));
+ Assert.assertEquals(703, message.getRepeatedField(f("packed_uint32"), 1));
+ Assert.assertEquals(704L, message.getRepeatedField(f("packed_uint64"), 1));
+ Assert.assertEquals(705, message.getRepeatedField(f("packed_sint32"), 1));
+ Assert.assertEquals(706L, message.getRepeatedField(f("packed_sint64"), 1));
+ Assert.assertEquals(707, message.getRepeatedField(f("packed_fixed32"), 1));
+ Assert.assertEquals(708L, message.getRepeatedField(f("packed_fixed64"), 1));
+ Assert.assertEquals(709, message.getRepeatedField(f("packed_sfixed32"), 1));
+ Assert.assertEquals(710L, message.getRepeatedField(f("packed_sfixed64"), 1));
+ Assert.assertEquals(711F, message.getRepeatedField(f("packed_float"), 1));
+ Assert.assertEquals(712D, message.getRepeatedField(f("packed_double"), 1));
+ Assert.assertEquals(false, message.getRepeatedField(f("packed_bool"), 1));
+ Assert.assertEquals(foreignBaz, message.getRepeatedField(f("packed_enum"), 1));
}
/**
* Verifies that the reflection setters for the given.Builder object throw a
- * NullPointerException if they are passed a null value. Uses Assert to throw an
- * appropriate assertion failure, if the condition is not verified.
+ * NullPointerException if they are passed a null value. Uses Assert to throw an appropriate
+ * assertion failure, if the condition is not verified.
*/
- public void assertReflectionSettersRejectNull(Message.Builder builder)
- throws Exception {
+ public void assertReflectionSettersRejectNull(Message.Builder builder) throws Exception {
try {
builder.setField(f("optional_string"), null);
Assert.fail("Exception was not thrown");
@@ -3700,15 +3672,13 @@ public final class TestUtil {
// We expect this exception.
}
try {
- builder.setField(f("optional_nested_message"),
- (TestAllTypes.NestedMessage) null);
+ builder.setField(f("optional_nested_message"), (TestAllTypes.NestedMessage) null);
Assert.fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
try {
- builder.setField(f("optional_nested_message"),
- (TestAllTypes.NestedMessage.Builder) null);
+ builder.setField(f("optional_nested_message"), (TestAllTypes.NestedMessage.Builder) null);
Assert.fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
@@ -3742,7 +3712,7 @@ public final class TestUtil {
/**
* Verifies that the reflection repeated setters for the given Builder object throw a
- * NullPointerException if they are passed a null value. Uses Assert to throw an appropriate
+ * NullPointerException if they are passed a null value. Uses Assert to throw an appropriate
* assertion failure, if the condition is not verified.
*/
public void assertReflectionRepeatedSettersRejectNull(Message.Builder builder)
@@ -3772,8 +3742,7 @@ public final class TestUtil {
}
builder.addRepeatedField(
- f("repeated_nested_message"),
- TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
+ f("repeated_nested_message"), TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
try {
builder.setRepeatedField(f("repeated_nested_message"), 0, null);
Assert.fail("Exception was not thrown");
@@ -3783,10 +3752,7 @@ public final class TestUtil {
}
}
- /**
- * @param filePath The path relative to
- * {@link #getTestDataDir}.
- */
+ /** @param filePath The path relative to {@link #getTestDataDir}. */
public static String readTextFromFile(String filePath) {
return readBytesFromFile(filePath).toStringUtf8();
}
@@ -3798,8 +3764,7 @@ public final class TestUtil {
try {
ancestor = ancestor.getCanonicalFile();
} catch (IOException e) {
- throw new RuntimeException(
- "Couldn't get canonical name of working directory.", e);
+ throw new RuntimeException("Couldn't get canonical name of working directory.", e);
}
while (ancestor != null && ancestor.exists()) {
if (new File(ancestor, "src/google/protobuf").exists()) {
@@ -3809,15 +3774,13 @@ public final class TestUtil {
}
throw new RuntimeException(
- "Could not find golden files. This test must be run from within the " +
- "protobuf source package so that it can read test data files from the " +
- "C++ source tree: " + initialPath);
+ "Could not find golden files. This test must be run from within the "
+ + "protobuf source package so that it can read test data files from the "
+ + "C++ source tree: "
+ + initialPath);
}
- /**
- * @param filename The path relative to
- * {@link #getTestDataDir}.
- */
+ /** @param filename The path relative to {@link #getTestDataDir}. */
public static ByteString readBytesFromFile(String filename) {
File fullPath = new File(getTestDataDir(), filename);
try {
@@ -3828,8 +3791,7 @@ public final class TestUtil {
} catch (IOException e) {
// Throw a RuntimeException here so that we can call this function from
// static initializers.
- throw new IllegalArgumentException(
- "Couldn't read file: " + fullPath.getPath(), e);
+ throw new IllegalArgumentException("Couldn't read file: " + fullPath.getPath(), e);
}
}
// END FULL-RUNTIME
@@ -3844,27 +3806,26 @@ public final class TestUtil {
}
/**
- * Get the bytes of the "golden message". This is a serialized TestAllTypes
- * with all fields set as they would be by
- * {@link #setAllFields(TestAllTypes.Builder)}, but it is loaded from a file
- * on disk rather than generated dynamically. The file is actually generated
- * by C++ code, so testing against it verifies compatibility with C++.
+ * Get the bytes of the "golden message". This is a serialized TestAllTypes with all fields set as
+ * they would be by {@link #setAllFields(TestAllTypes.Builder)}, but it is loaded from a file on
+ * disk rather than generated dynamically. The file is actually generated by C++ code, so testing
+ * against it verifies compatibility with C++.
*/
public static ByteString getGoldenMessage() {
if (goldenMessage == null) {
- goldenMessage = readBytesFromResource("/google/protobuf/testdata/golden_message_oneof_implemented");
+ goldenMessage =
+ readBytesFromResource("/google/protobuf/testdata/golden_message_oneof_implemented");
}
return goldenMessage;
}
+
private static ByteString goldenMessage = null;
/**
- * Get the bytes of the "golden packed fields message". This is a serialized
- * TestPackedTypes with all fields set as they would be by
- * {@link #setPackedFields(TestPackedTypes.Builder)}, but it is loaded from a
- * file on disk rather than generated dynamically. The file is actually
- * generated by C++ code, so testing against it verifies compatibility with
- * C++.
+ * Get the bytes of the "golden packed fields message". This is a serialized TestPackedTypes with
+ * all fields set as they would be by {@link #setPackedFields(TestPackedTypes.Builder)}, but it is
+ * loaded from a file on disk rather than generated dynamically. The file is actually generated by
+ * C++ code, so testing against it verifies compatibility with C++.
*/
public static ByteString getGoldenPackedFieldsMessage() {
if (goldenPackedFieldsMessage == null) {
@@ -3873,6 +3834,7 @@ public final class TestUtil {
}
return goldenPackedFieldsMessage;
}
+
private static ByteString goldenPackedFieldsMessage = null;
// BEGIN FULL-RUNTIME
@@ -3881,8 +3843,7 @@ public final class TestUtil {
*
* @author jonp@google.com (Jon Perlow)
*/
- public static class MockBuilderParent
- implements GeneratedMessage.BuilderParent {
+ public static class MockBuilderParent implements GeneratedMessage.BuilderParent {
private int invalidations;
diff --git a/java/core/src/test/java/com/google/protobuf/TestUtilLite.java b/java/core/src/test/java/com/google/protobuf/TestUtilLite.java
index 8f33fa14..31565fc4 100644
--- a/java/core/src/test/java/com/google/protobuf/TestUtilLite.java
+++ b/java/core/src/test/java/com/google/protobuf/TestUtilLite.java
@@ -30,8 +30,6 @@
package com.google.protobuf;
-import static com.google.protobuf.UnittestLite.OptionalGroup_extension_lite;
-import static com.google.protobuf.UnittestLite.RepeatedGroup_extension_lite;
import static com.google.protobuf.UnittestLite.defaultBoolExtensionLite;
import static com.google.protobuf.UnittestLite.defaultBytesExtensionLite;
import static com.google.protobuf.UnittestLite.defaultCordExtensionLite;
@@ -127,6 +125,8 @@ import com.google.protobuf.UnittestImportLite.ImportMessageLite;
import com.google.protobuf.UnittestImportPublicLite.PublicImportMessageLite;
import com.google.protobuf.UnittestLite.ForeignEnumLite;
import com.google.protobuf.UnittestLite.ForeignMessageLite;
+import com.google.protobuf.UnittestLite.OptionalGroup_extension_lite;
+import com.google.protobuf.UnittestLite.RepeatedGroup_extension_lite;
import com.google.protobuf.UnittestLite.TestAllExtensionsLite;
import com.google.protobuf.UnittestLite.TestAllTypesLite;
import com.google.protobuf.UnittestLite.TestPackedExtensionsLite;
@@ -136,8 +136,7 @@ import com.google.protobuf.UnittestLite.TestPackedExtensionsLite;
* and {@code TestPackedExtensionsLite}. This is analogous to the functionality in TestUtil.java but
* does not depend on the presence of any non-lite protos.
*
- * <p>This code is not to be used outside of {@code com.google.protobuf} and
- * subpackages.
+ * <p>This code is not to be used outside of {@code com.google.protobuf} and subpackages.
*/
public final class TestUtilLite {
private TestUtilLite() {}
@@ -148,8 +147,8 @@ public final class TestUtilLite {
}
/**
- * Get a {@code TestAllTypesLite.Builder} with all fields set as they would be by
- * {@link #setAllFields(TestAllTypesLite.Builder)}.
+ * Get a {@code TestAllTypesLite.Builder} with all fields set as they would be by {@link
+ * #setAllFields(TestAllTypesLite.Builder)}.
*/
public static TestAllTypesLite.Builder getAllLiteSetBuilder() {
TestAllTypesLite.Builder builder = TestAllTypesLite.newBuilder();
@@ -158,8 +157,8 @@ public final class TestUtilLite {
}
/**
- * Get a {@code TestAllExtensionsLite} with all fields set as they would be by
- * {@link #setAllExtensions(TestAllExtensionsLite.Builder)}.
+ * Get a {@code TestAllExtensionsLite} with all fields set as they would be by {@link
+ * #setAllExtensions(TestAllExtensionsLite.Builder)}.
*/
public static TestAllExtensionsLite getAllLiteExtensionsSet() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.newBuilder();
@@ -172,154 +171,137 @@ public final class TestUtilLite {
setPackedExtensions(builder);
return builder.build();
}
-
- /**
- * Set every field of {@code builder} to the values expected by
- * {@code assertAllFieldsSet()}.
- */
+
+ /** Set every field of {@code builder} to the values expected by {@code assertAllFieldsSet()}. */
public static void setAllFields(TestAllTypesLite.Builder builder) {
- builder.setOptionalInt32 (101);
- builder.setOptionalInt64 (102);
- builder.setOptionalUint32 (103);
- builder.setOptionalUint64 (104);
- builder.setOptionalSint32 (105);
- builder.setOptionalSint64 (106);
- builder.setOptionalFixed32 (107);
- builder.setOptionalFixed64 (108);
+ builder.setOptionalInt32(101);
+ builder.setOptionalInt64(102);
+ builder.setOptionalUint32(103);
+ builder.setOptionalUint64(104);
+ builder.setOptionalSint32(105);
+ builder.setOptionalSint64(106);
+ builder.setOptionalFixed32(107);
+ builder.setOptionalFixed64(108);
builder.setOptionalSfixed32(109);
builder.setOptionalSfixed64(110);
- builder.setOptionalFloat (111);
- builder.setOptionalDouble (112);
- builder.setOptionalBool (true);
- builder.setOptionalString ("115");
- builder.setOptionalBytes (toBytes("116"));
-
- builder.setOptionalGroup(
- TestAllTypesLite.OptionalGroup.newBuilder().setA(117).build());
+ builder.setOptionalFloat(111);
+ builder.setOptionalDouble(112);
+ builder.setOptionalBool(true);
+ builder.setOptionalString("115");
+ builder.setOptionalBytes(toBytes("116"));
+
+ builder.setOptionalGroup(TestAllTypesLite.OptionalGroup.newBuilder().setA(117).build());
builder.setOptionalNestedMessage(
TestAllTypesLite.NestedMessage.newBuilder().setBb(118).build());
- builder.setOptionalForeignMessage(
- ForeignMessageLite.newBuilder().setC(119).build());
- builder.setOptionalImportMessage(
- ImportMessageLite.newBuilder().setD(120).build());
- builder.setOptionalPublicImportMessage(
- PublicImportMessageLite.newBuilder().setE(126).build());
- builder.setOptionalLazyMessage(
- TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build());
+ builder.setOptionalForeignMessage(ForeignMessageLite.newBuilder().setC(119).build());
+ builder.setOptionalImportMessage(ImportMessageLite.newBuilder().setD(120).build());
+ builder.setOptionalPublicImportMessage(PublicImportMessageLite.newBuilder().setE(126).build());
+ builder.setOptionalLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build());
- builder.setOptionalNestedEnum (TestAllTypesLite.NestedEnum.BAZ);
+ builder.setOptionalNestedEnum(TestAllTypesLite.NestedEnum.BAZ);
builder.setOptionalForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAZ);
- builder.setOptionalImportEnum (ImportEnumLite.IMPORT_LITE_BAZ);
+ builder.setOptionalImportEnum(ImportEnumLite.IMPORT_LITE_BAZ);
builder.setOptionalStringPiece("124");
builder.setOptionalCord("125");
// -----------------------------------------------------------------
- builder.addRepeatedInt32 (201);
- builder.addRepeatedInt64 (202);
- builder.addRepeatedUint32 (203);
- builder.addRepeatedUint64 (204);
- builder.addRepeatedSint32 (205);
- builder.addRepeatedSint64 (206);
- builder.addRepeatedFixed32 (207);
- builder.addRepeatedFixed64 (208);
+ builder.addRepeatedInt32(201);
+ builder.addRepeatedInt64(202);
+ builder.addRepeatedUint32(203);
+ builder.addRepeatedUint64(204);
+ builder.addRepeatedSint32(205);
+ builder.addRepeatedSint64(206);
+ builder.addRepeatedFixed32(207);
+ builder.addRepeatedFixed64(208);
builder.addRepeatedSfixed32(209);
builder.addRepeatedSfixed64(210);
- builder.addRepeatedFloat (211);
- builder.addRepeatedDouble (212);
- builder.addRepeatedBool (true);
- builder.addRepeatedString ("215");
- builder.addRepeatedBytes (toBytes("216"));
-
- builder.addRepeatedGroup(
- TestAllTypesLite.RepeatedGroup.newBuilder().setA(217).build());
+ builder.addRepeatedFloat(211);
+ builder.addRepeatedDouble(212);
+ builder.addRepeatedBool(true);
+ builder.addRepeatedString("215");
+ builder.addRepeatedBytes(toBytes("216"));
+
+ builder.addRepeatedGroup(TestAllTypesLite.RepeatedGroup.newBuilder().setA(217).build());
builder.addRepeatedNestedMessage(
TestAllTypesLite.NestedMessage.newBuilder().setBb(218).build());
- builder.addRepeatedForeignMessage(
- ForeignMessageLite.newBuilder().setC(219).build());
- builder.addRepeatedImportMessage(
- ImportMessageLite.newBuilder().setD(220).build());
- builder.addRepeatedLazyMessage(
- TestAllTypesLite.NestedMessage.newBuilder().setBb(227).build());
+ builder.addRepeatedForeignMessage(ForeignMessageLite.newBuilder().setC(219).build());
+ builder.addRepeatedImportMessage(ImportMessageLite.newBuilder().setD(220).build());
+ builder.addRepeatedLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(227).build());
- builder.addRepeatedNestedEnum (TestAllTypesLite.NestedEnum.BAR);
+ builder.addRepeatedNestedEnum(TestAllTypesLite.NestedEnum.BAR);
builder.addRepeatedForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR);
- builder.addRepeatedImportEnum (ImportEnumLite.IMPORT_LITE_BAR);
+ builder.addRepeatedImportEnum(ImportEnumLite.IMPORT_LITE_BAR);
builder.addRepeatedStringPiece("224");
builder.addRepeatedCord("225");
// Add a second one of each field.
- builder.addRepeatedInt32 (301);
- builder.addRepeatedInt64 (302);
- builder.addRepeatedUint32 (303);
- builder.addRepeatedUint64 (304);
- builder.addRepeatedSint32 (305);
- builder.addRepeatedSint64 (306);
- builder.addRepeatedFixed32 (307);
- builder.addRepeatedFixed64 (308);
+ builder.addRepeatedInt32(301);
+ builder.addRepeatedInt64(302);
+ builder.addRepeatedUint32(303);
+ builder.addRepeatedUint64(304);
+ builder.addRepeatedSint32(305);
+ builder.addRepeatedSint64(306);
+ builder.addRepeatedFixed32(307);
+ builder.addRepeatedFixed64(308);
builder.addRepeatedSfixed32(309);
builder.addRepeatedSfixed64(310);
- builder.addRepeatedFloat (311);
- builder.addRepeatedDouble (312);
- builder.addRepeatedBool (false);
- builder.addRepeatedString ("315");
- builder.addRepeatedBytes (toBytes("316"));
-
- builder.addRepeatedGroup(
- TestAllTypesLite.RepeatedGroup.newBuilder().setA(317).build());
+ builder.addRepeatedFloat(311);
+ builder.addRepeatedDouble(312);
+ builder.addRepeatedBool(false);
+ builder.addRepeatedString("315");
+ builder.addRepeatedBytes(toBytes("316"));
+
+ builder.addRepeatedGroup(TestAllTypesLite.RepeatedGroup.newBuilder().setA(317).build());
builder.addRepeatedNestedMessage(
TestAllTypesLite.NestedMessage.newBuilder().setBb(318).build());
- builder.addRepeatedForeignMessage(
- ForeignMessageLite.newBuilder().setC(319).build());
- builder.addRepeatedImportMessage(
- ImportMessageLite.newBuilder().setD(320).build());
- builder.addRepeatedLazyMessage(
- TestAllTypesLite.NestedMessage.newBuilder().setBb(327).build());
+ builder.addRepeatedForeignMessage(ForeignMessageLite.newBuilder().setC(319).build());
+ builder.addRepeatedImportMessage(ImportMessageLite.newBuilder().setD(320).build());
+ builder.addRepeatedLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(327).build());
- builder.addRepeatedNestedEnum (TestAllTypesLite.NestedEnum.BAZ);
+ builder.addRepeatedNestedEnum(TestAllTypesLite.NestedEnum.BAZ);
builder.addRepeatedForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAZ);
- builder.addRepeatedImportEnum (ImportEnumLite.IMPORT_LITE_BAZ);
+ builder.addRepeatedImportEnum(ImportEnumLite.IMPORT_LITE_BAZ);
builder.addRepeatedStringPiece("324");
builder.addRepeatedCord("325");
// -----------------------------------------------------------------
- builder.setDefaultInt32 (401);
- builder.setDefaultInt64 (402);
- builder.setDefaultUint32 (403);
- builder.setDefaultUint64 (404);
- builder.setDefaultSint32 (405);
- builder.setDefaultSint64 (406);
- builder.setDefaultFixed32 (407);
- builder.setDefaultFixed64 (408);
+ builder.setDefaultInt32(401);
+ builder.setDefaultInt64(402);
+ builder.setDefaultUint32(403);
+ builder.setDefaultUint64(404);
+ builder.setDefaultSint32(405);
+ builder.setDefaultSint64(406);
+ builder.setDefaultFixed32(407);
+ builder.setDefaultFixed64(408);
builder.setDefaultSfixed32(409);
builder.setDefaultSfixed64(410);
- builder.setDefaultFloat (411);
- builder.setDefaultDouble (412);
- builder.setDefaultBool (false);
- builder.setDefaultString ("415");
- builder.setDefaultBytes (toBytes("416"));
+ builder.setDefaultFloat(411);
+ builder.setDefaultDouble(412);
+ builder.setDefaultBool(false);
+ builder.setDefaultString("415");
+ builder.setDefaultBytes(toBytes("416"));
- builder.setDefaultNestedEnum (TestAllTypesLite.NestedEnum.FOO);
+ builder.setDefaultNestedEnum(TestAllTypesLite.NestedEnum.FOO);
builder.setDefaultForeignEnum(ForeignEnumLite.FOREIGN_LITE_FOO);
- builder.setDefaultImportEnum (ImportEnumLite.IMPORT_LITE_FOO);
+ builder.setDefaultImportEnum(ImportEnumLite.IMPORT_LITE_FOO);
builder.setDefaultStringPiece("424");
builder.setDefaultCord("425");
builder.setOneofUint32(601);
- builder.setOneofNestedMessage(
- TestAllTypesLite.NestedMessage.newBuilder().setBb(602).build());
+ builder.setOneofNestedMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(602).build());
builder.setOneofString("603");
builder.setOneofBytes(toBytes("604"));
}
/**
- * Get an unmodifiable {@link ExtensionRegistryLite} containing all the
- * extensions of {@code TestAllExtensionsLite}.
+ * Get an unmodifiable {@link ExtensionRegistryLite} containing all the extensions of {@code
+ * TestAllExtensionsLite}.
*/
public static ExtensionRegistryLite getExtensionRegistryLite() {
ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance();
@@ -328,8 +310,8 @@ public final class TestUtilLite {
}
/**
- * Register all of {@code TestAllExtensionsLite}'s extensions with the
- * given {@link ExtensionRegistryLite}.
+ * Register all of {@code TestAllExtensionsLite}'s extensions with the given {@link
+ * ExtensionRegistryLite}.
*/
public static void registerAllExtensionsLite(ExtensionRegistryLite registry) {
UnittestLite.registerAllExtensions(registry);
@@ -339,38 +321,40 @@ public final class TestUtilLite {
// Lite extensions
/**
- * Set every field of {@code message} to the values expected by
- * {@code assertAllExtensionsSet()}.
+ * Set every field of {@code message} to the values expected by {@code assertAllExtensionsSet()}.
*/
public static void setAllExtensions(TestAllExtensionsLite.Builder message) {
- message.setExtension(optionalInt32ExtensionLite , 101);
- message.setExtension(optionalInt64ExtensionLite , 102L);
- message.setExtension(optionalUint32ExtensionLite , 103);
- message.setExtension(optionalUint64ExtensionLite , 104L);
- message.setExtension(optionalSint32ExtensionLite , 105);
- message.setExtension(optionalSint64ExtensionLite , 106L);
- message.setExtension(optionalFixed32ExtensionLite , 107);
- message.setExtension(optionalFixed64ExtensionLite , 108L);
+ message.setExtension(optionalInt32ExtensionLite, 101);
+ message.setExtension(optionalInt64ExtensionLite, 102L);
+ message.setExtension(optionalUint32ExtensionLite, 103);
+ message.setExtension(optionalUint64ExtensionLite, 104L);
+ message.setExtension(optionalSint32ExtensionLite, 105);
+ message.setExtension(optionalSint64ExtensionLite, 106L);
+ message.setExtension(optionalFixed32ExtensionLite, 107);
+ message.setExtension(optionalFixed64ExtensionLite, 108L);
message.setExtension(optionalSfixed32ExtensionLite, 109);
message.setExtension(optionalSfixed64ExtensionLite, 110L);
- message.setExtension(optionalFloatExtensionLite , 111F);
- message.setExtension(optionalDoubleExtensionLite , 112D);
- message.setExtension(optionalBoolExtensionLite , true);
- message.setExtension(optionalStringExtensionLite , "115");
- message.setExtension(optionalBytesExtensionLite , toBytes("116"));
-
- message.setExtension(optionalGroupExtensionLite,
- OptionalGroup_extension_lite.newBuilder().setA(117).build());
- message.setExtension(optionalNestedMessageExtensionLite,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(118).build());
- message.setExtension(optionalForeignMessageExtensionLite,
- ForeignMessageLite.newBuilder().setC(119).build());
- message.setExtension(optionalImportMessageExtensionLite,
- ImportMessageLite.newBuilder().setD(120).build());
- message.setExtension(optionalPublicImportMessageExtensionLite,
- PublicImportMessageLite.newBuilder().setE(126).build());
- message.setExtension(optionalLazyMessageExtensionLite,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build());
+ message.setExtension(optionalFloatExtensionLite, 111F);
+ message.setExtension(optionalDoubleExtensionLite, 112D);
+ message.setExtension(optionalBoolExtensionLite, true);
+ message.setExtension(optionalStringExtensionLite, "115");
+ message.setExtension(optionalBytesExtensionLite, toBytes("116"));
+
+ message.setExtension(
+ optionalGroupExtensionLite, OptionalGroup_extension_lite.newBuilder().setA(117).build());
+ message.setExtension(
+ optionalNestedMessageExtensionLite,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(118).build());
+ message.setExtension(
+ optionalForeignMessageExtensionLite, ForeignMessageLite.newBuilder().setC(119).build());
+ message.setExtension(
+ optionalImportMessageExtensionLite, ImportMessageLite.newBuilder().setD(120).build());
+ message.setExtension(
+ optionalPublicImportMessageExtensionLite,
+ PublicImportMessageLite.newBuilder().setE(126).build());
+ message.setExtension(
+ optionalLazyMessageExtensionLite,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build());
message.setExtension(optionalNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ);
message.setExtension(optionalForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ);
@@ -381,32 +365,34 @@ public final class TestUtilLite {
// -----------------------------------------------------------------
- message.addExtension(repeatedInt32ExtensionLite , 201);
- message.addExtension(repeatedInt64ExtensionLite , 202L);
- message.addExtension(repeatedUint32ExtensionLite , 203);
- message.addExtension(repeatedUint64ExtensionLite , 204L);
- message.addExtension(repeatedSint32ExtensionLite , 205);
- message.addExtension(repeatedSint64ExtensionLite , 206L);
- message.addExtension(repeatedFixed32ExtensionLite , 207);
- message.addExtension(repeatedFixed64ExtensionLite , 208L);
+ message.addExtension(repeatedInt32ExtensionLite, 201);
+ message.addExtension(repeatedInt64ExtensionLite, 202L);
+ message.addExtension(repeatedUint32ExtensionLite, 203);
+ message.addExtension(repeatedUint64ExtensionLite, 204L);
+ message.addExtension(repeatedSint32ExtensionLite, 205);
+ message.addExtension(repeatedSint64ExtensionLite, 206L);
+ message.addExtension(repeatedFixed32ExtensionLite, 207);
+ message.addExtension(repeatedFixed64ExtensionLite, 208L);
message.addExtension(repeatedSfixed32ExtensionLite, 209);
message.addExtension(repeatedSfixed64ExtensionLite, 210L);
- message.addExtension(repeatedFloatExtensionLite , 211F);
- message.addExtension(repeatedDoubleExtensionLite , 212D);
- message.addExtension(repeatedBoolExtensionLite , true);
- message.addExtension(repeatedStringExtensionLite , "215");
- message.addExtension(repeatedBytesExtensionLite , toBytes("216"));
-
- message.addExtension(repeatedGroupExtensionLite,
- RepeatedGroup_extension_lite.newBuilder().setA(217).build());
- message.addExtension(repeatedNestedMessageExtensionLite,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(218).build());
- message.addExtension(repeatedForeignMessageExtensionLite,
- ForeignMessageLite.newBuilder().setC(219).build());
- message.addExtension(repeatedImportMessageExtensionLite,
- ImportMessageLite.newBuilder().setD(220).build());
- message.addExtension(repeatedLazyMessageExtensionLite,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(227).build());
+ message.addExtension(repeatedFloatExtensionLite, 211F);
+ message.addExtension(repeatedDoubleExtensionLite, 212D);
+ message.addExtension(repeatedBoolExtensionLite, true);
+ message.addExtension(repeatedStringExtensionLite, "215");
+ message.addExtension(repeatedBytesExtensionLite, toBytes("216"));
+
+ message.addExtension(
+ repeatedGroupExtensionLite, RepeatedGroup_extension_lite.newBuilder().setA(217).build());
+ message.addExtension(
+ repeatedNestedMessageExtensionLite,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(218).build());
+ message.addExtension(
+ repeatedForeignMessageExtensionLite, ForeignMessageLite.newBuilder().setC(219).build());
+ message.addExtension(
+ repeatedImportMessageExtensionLite, ImportMessageLite.newBuilder().setD(220).build());
+ message.addExtension(
+ repeatedLazyMessageExtensionLite,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(227).build());
message.addExtension(repeatedNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAR);
message.addExtension(repeatedForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAR);
@@ -416,32 +402,34 @@ public final class TestUtilLite {
message.addExtension(repeatedCordExtensionLite, "225");
// Add a second one of each field.
- message.addExtension(repeatedInt32ExtensionLite , 301);
- message.addExtension(repeatedInt64ExtensionLite , 302L);
- message.addExtension(repeatedUint32ExtensionLite , 303);
- message.addExtension(repeatedUint64ExtensionLite , 304L);
- message.addExtension(repeatedSint32ExtensionLite , 305);
- message.addExtension(repeatedSint64ExtensionLite , 306L);
- message.addExtension(repeatedFixed32ExtensionLite , 307);
- message.addExtension(repeatedFixed64ExtensionLite , 308L);
+ message.addExtension(repeatedInt32ExtensionLite, 301);
+ message.addExtension(repeatedInt64ExtensionLite, 302L);
+ message.addExtension(repeatedUint32ExtensionLite, 303);
+ message.addExtension(repeatedUint64ExtensionLite, 304L);
+ message.addExtension(repeatedSint32ExtensionLite, 305);
+ message.addExtension(repeatedSint64ExtensionLite, 306L);
+ message.addExtension(repeatedFixed32ExtensionLite, 307);
+ message.addExtension(repeatedFixed64ExtensionLite, 308L);
message.addExtension(repeatedSfixed32ExtensionLite, 309);
message.addExtension(repeatedSfixed64ExtensionLite, 310L);
- message.addExtension(repeatedFloatExtensionLite , 311F);
- message.addExtension(repeatedDoubleExtensionLite , 312D);
- message.addExtension(repeatedBoolExtensionLite , false);
- message.addExtension(repeatedStringExtensionLite , "315");
- message.addExtension(repeatedBytesExtensionLite , toBytes("316"));
-
- message.addExtension(repeatedGroupExtensionLite,
- RepeatedGroup_extension_lite.newBuilder().setA(317).build());
- message.addExtension(repeatedNestedMessageExtensionLite,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(318).build());
- message.addExtension(repeatedForeignMessageExtensionLite,
- ForeignMessageLite.newBuilder().setC(319).build());
- message.addExtension(repeatedImportMessageExtensionLite,
- ImportMessageLite.newBuilder().setD(320).build());
- message.addExtension(repeatedLazyMessageExtensionLite,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(327).build());
+ message.addExtension(repeatedFloatExtensionLite, 311F);
+ message.addExtension(repeatedDoubleExtensionLite, 312D);
+ message.addExtension(repeatedBoolExtensionLite, false);
+ message.addExtension(repeatedStringExtensionLite, "315");
+ message.addExtension(repeatedBytesExtensionLite, toBytes("316"));
+
+ message.addExtension(
+ repeatedGroupExtensionLite, RepeatedGroup_extension_lite.newBuilder().setA(317).build());
+ message.addExtension(
+ repeatedNestedMessageExtensionLite,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(318).build());
+ message.addExtension(
+ repeatedForeignMessageExtensionLite, ForeignMessageLite.newBuilder().setC(319).build());
+ message.addExtension(
+ repeatedImportMessageExtensionLite, ImportMessageLite.newBuilder().setD(320).build());
+ message.addExtension(
+ repeatedLazyMessageExtensionLite,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(327).build());
message.addExtension(repeatedNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ);
message.addExtension(repeatedForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ);
@@ -452,21 +440,21 @@ public final class TestUtilLite {
// -----------------------------------------------------------------
- message.setExtension(defaultInt32ExtensionLite , 401);
- message.setExtension(defaultInt64ExtensionLite , 402L);
- message.setExtension(defaultUint32ExtensionLite , 403);
- message.setExtension(defaultUint64ExtensionLite , 404L);
- message.setExtension(defaultSint32ExtensionLite , 405);
- message.setExtension(defaultSint64ExtensionLite , 406L);
- message.setExtension(defaultFixed32ExtensionLite , 407);
- message.setExtension(defaultFixed64ExtensionLite , 408L);
+ message.setExtension(defaultInt32ExtensionLite, 401);
+ message.setExtension(defaultInt64ExtensionLite, 402L);
+ message.setExtension(defaultUint32ExtensionLite, 403);
+ message.setExtension(defaultUint64ExtensionLite, 404L);
+ message.setExtension(defaultSint32ExtensionLite, 405);
+ message.setExtension(defaultSint64ExtensionLite, 406L);
+ message.setExtension(defaultFixed32ExtensionLite, 407);
+ message.setExtension(defaultFixed64ExtensionLite, 408L);
message.setExtension(defaultSfixed32ExtensionLite, 409);
message.setExtension(defaultSfixed64ExtensionLite, 410L);
- message.setExtension(defaultFloatExtensionLite , 411F);
- message.setExtension(defaultDoubleExtensionLite , 412D);
- message.setExtension(defaultBoolExtensionLite , false);
- message.setExtension(defaultStringExtensionLite , "415");
- message.setExtension(defaultBytesExtensionLite , toBytes("416"));
+ message.setExtension(defaultFloatExtensionLite, 411F);
+ message.setExtension(defaultDoubleExtensionLite, 412D);
+ message.setExtension(defaultBoolExtensionLite, false);
+ message.setExtension(defaultStringExtensionLite, "415");
+ message.setExtension(defaultBytesExtensionLite, toBytes("416"));
message.setExtension(defaultNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.FOO);
message.setExtension(defaultForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_FOO);
@@ -476,8 +464,9 @@ public final class TestUtilLite {
message.setExtension(defaultCordExtensionLite, "425");
message.setExtension(oneofUint32ExtensionLite, 601);
- message.setExtension(oneofNestedMessageExtensionLite,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(602).build());
+ message.setExtension(
+ oneofNestedMessageExtensionLite,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(602).build());
message.setExtension(oneofStringExtensionLite, "603");
message.setExtension(oneofBytesExtensionLite, toBytes("604"));
}
@@ -485,75 +474,78 @@ public final class TestUtilLite {
// -------------------------------------------------------------------
/**
- * Modify the repeated extensions of {@code message} to contain the values
- * expected by {@code assertRepeatedExtensionsModified()}.
+ * Modify the repeated extensions of {@code message} to contain the values expected by {@code
+ * assertRepeatedExtensionsModified()}.
*/
- public static void modifyRepeatedExtensions(
- TestAllExtensionsLite.Builder message) {
- message.setExtension(repeatedInt32ExtensionLite , 1, 501);
- message.setExtension(repeatedInt64ExtensionLite , 1, 502L);
- message.setExtension(repeatedUint32ExtensionLite , 1, 503);
- message.setExtension(repeatedUint64ExtensionLite , 1, 504L);
- message.setExtension(repeatedSint32ExtensionLite , 1, 505);
- message.setExtension(repeatedSint64ExtensionLite , 1, 506L);
- message.setExtension(repeatedFixed32ExtensionLite , 1, 507);
- message.setExtension(repeatedFixed64ExtensionLite , 1, 508L);
+ public static void modifyRepeatedExtensions(TestAllExtensionsLite.Builder message) {
+ message.setExtension(repeatedInt32ExtensionLite, 1, 501);
+ message.setExtension(repeatedInt64ExtensionLite, 1, 502L);
+ message.setExtension(repeatedUint32ExtensionLite, 1, 503);
+ message.setExtension(repeatedUint64ExtensionLite, 1, 504L);
+ message.setExtension(repeatedSint32ExtensionLite, 1, 505);
+ message.setExtension(repeatedSint64ExtensionLite, 1, 506L);
+ message.setExtension(repeatedFixed32ExtensionLite, 1, 507);
+ message.setExtension(repeatedFixed64ExtensionLite, 1, 508L);
message.setExtension(repeatedSfixed32ExtensionLite, 1, 509);
message.setExtension(repeatedSfixed64ExtensionLite, 1, 510L);
- message.setExtension(repeatedFloatExtensionLite , 1, 511F);
- message.setExtension(repeatedDoubleExtensionLite , 1, 512D);
- message.setExtension(repeatedBoolExtensionLite , 1, true);
- message.setExtension(repeatedStringExtensionLite , 1, "515");
- message.setExtension(repeatedBytesExtensionLite , 1, toBytes("516"));
-
- message.setExtension(repeatedGroupExtensionLite, 1,
- RepeatedGroup_extension_lite.newBuilder().setA(517).build());
- message.setExtension(repeatedNestedMessageExtensionLite, 1,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(518).build());
- message.setExtension(repeatedForeignMessageExtensionLite, 1,
- ForeignMessageLite.newBuilder().setC(519).build());
- message.setExtension(repeatedImportMessageExtensionLite, 1,
- ImportMessageLite.newBuilder().setD(520).build());
- message.setExtension(repeatedLazyMessageExtensionLite, 1,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(527).build());
-
- message.setExtension(repeatedNestedEnumExtensionLite , 1, TestAllTypesLite.NestedEnum.FOO);
+ message.setExtension(repeatedFloatExtensionLite, 1, 511F);
+ message.setExtension(repeatedDoubleExtensionLite, 1, 512D);
+ message.setExtension(repeatedBoolExtensionLite, 1, true);
+ message.setExtension(repeatedStringExtensionLite, 1, "515");
+ message.setExtension(repeatedBytesExtensionLite, 1, toBytes("516"));
+
+ message.setExtension(
+ repeatedGroupExtensionLite, 1, RepeatedGroup_extension_lite.newBuilder().setA(517).build());
+ message.setExtension(
+ repeatedNestedMessageExtensionLite,
+ 1,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(518).build());
+ message.setExtension(
+ repeatedForeignMessageExtensionLite, 1, ForeignMessageLite.newBuilder().setC(519).build());
+ message.setExtension(
+ repeatedImportMessageExtensionLite, 1, ImportMessageLite.newBuilder().setD(520).build());
+ message.setExtension(
+ repeatedLazyMessageExtensionLite,
+ 1,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(527).build());
+
+ message.setExtension(repeatedNestedEnumExtensionLite, 1, TestAllTypesLite.NestedEnum.FOO);
message.setExtension(repeatedForeignEnumExtensionLite, 1, ForeignEnumLite.FOREIGN_LITE_FOO);
- message.setExtension(repeatedImportEnumExtensionLite , 1, ImportEnumLite.IMPORT_LITE_FOO);
+ message.setExtension(repeatedImportEnumExtensionLite, 1, ImportEnumLite.IMPORT_LITE_FOO);
message.setExtension(repeatedStringPieceExtensionLite, 1, "524");
message.setExtension(repeatedCordExtensionLite, 1, "525");
}
public static void setPackedExtensions(TestPackedExtensionsLite.Builder message) {
- message.addExtension(packedInt32ExtensionLite , 601);
- message.addExtension(packedInt64ExtensionLite , 602L);
- message.addExtension(packedUint32ExtensionLite , 603);
- message.addExtension(packedUint64ExtensionLite , 604L);
- message.addExtension(packedSint32ExtensionLite , 605);
- message.addExtension(packedSint64ExtensionLite , 606L);
- message.addExtension(packedFixed32ExtensionLite , 607);
- message.addExtension(packedFixed64ExtensionLite , 608L);
+ message.addExtension(packedInt32ExtensionLite, 601);
+ message.addExtension(packedInt64ExtensionLite, 602L);
+ message.addExtension(packedUint32ExtensionLite, 603);
+ message.addExtension(packedUint64ExtensionLite, 604L);
+ message.addExtension(packedSint32ExtensionLite, 605);
+ message.addExtension(packedSint64ExtensionLite, 606L);
+ message.addExtension(packedFixed32ExtensionLite, 607);
+ message.addExtension(packedFixed64ExtensionLite, 608L);
message.addExtension(packedSfixed32ExtensionLite, 609);
message.addExtension(packedSfixed64ExtensionLite, 610L);
- message.addExtension(packedFloatExtensionLite , 611F);
- message.addExtension(packedDoubleExtensionLite , 612D);
- message.addExtension(packedBoolExtensionLite , true);
+ message.addExtension(packedFloatExtensionLite, 611F);
+ message.addExtension(packedDoubleExtensionLite, 612D);
+ message.addExtension(packedBoolExtensionLite, true);
message.addExtension(packedEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAR);
// Add a second one of each field.
- message.addExtension(packedInt32ExtensionLite , 701);
- message.addExtension(packedInt64ExtensionLite , 702L);
- message.addExtension(packedUint32ExtensionLite , 703);
- message.addExtension(packedUint64ExtensionLite , 704L);
- message.addExtension(packedSint32ExtensionLite , 705);
- message.addExtension(packedSint64ExtensionLite , 706L);
- message.addExtension(packedFixed32ExtensionLite , 707);
- message.addExtension(packedFixed64ExtensionLite , 708L);
+ message.addExtension(packedInt32ExtensionLite, 701);
+ message.addExtension(packedInt64ExtensionLite, 702L);
+ message.addExtension(packedUint32ExtensionLite, 703);
+ message.addExtension(packedUint64ExtensionLite, 704L);
+ message.addExtension(packedSint32ExtensionLite, 705);
+ message.addExtension(packedSint64ExtensionLite, 706L);
+ message.addExtension(packedFixed32ExtensionLite, 707);
+ message.addExtension(packedFixed64ExtensionLite, 708L);
message.addExtension(packedSfixed32ExtensionLite, 709);
message.addExtension(packedSfixed64ExtensionLite, 710L);
- message.addExtension(packedFloatExtensionLite , 711F);
- message.addExtension(packedDoubleExtensionLite , 712D);
- message.addExtension(packedBoolExtensionLite , false);
+ message.addExtension(packedFloatExtensionLite, 711F);
+ message.addExtension(packedDoubleExtensionLite, 712D);
+ message.addExtension(packedBoolExtensionLite, false);
message.addExtension(packedEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ);
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java b/java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java
index e338af21..ff413720 100644
--- a/java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java
+++ b/java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java
@@ -33,12 +33,9 @@ package com.google.protobuf;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import protobuf_unittest.UnittestProto.TestAllTypes;
-
import junit.framework.TestCase;
-/**
- * Test @{link TextFormatParseInfoTree}.
- */
+/** Test @{link TextFormatParseInfoTree}. */
public class TextFormatParseInfoTreeTest extends TestCase {
private static final Descriptor DESCRIPTOR = TestAllTypes.getDescriptor();
@@ -75,7 +72,7 @@ public class TextFormatParseInfoTreeTest extends TestCase {
TextFormatParseInfoTree root = rootBuilder.build();
assertEquals(LOC0, root.getLocation(OPTIONAL_INT32, 0));
assertEquals(1, root.getLocations(OPTIONAL_INT32).size());
- }
+ }
public void testGetLocationsReturnsNoParseLocationsForUnknownField() {
assertTrue(rootBuilder.build().getLocations(OPTIONAL_INT32).isEmpty());
diff --git a/java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java b/java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java
index c42bfa6e..19abc3f8 100644
--- a/java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java
+++ b/java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java
@@ -32,9 +32,7 @@ package com.google.protobuf;
import junit.framework.TestCase;
-/**
- * Test @{link TextFormatParseLocation}.
- */
+/** Test @{link TextFormatParseLocation}. */
public class TextFormatParseLocationTest extends TestCase {
public void testCreateEmpty() {
diff --git a/java/core/src/test/java/com/google/protobuf/TextFormatTest.java b/java/core/src/test/java/com/google/protobuf/TextFormatTest.java
index 24d5589f..d240088c 100644
--- a/java/core/src/test/java/com/google/protobuf/TextFormatTest.java
+++ b/java/core/src/test/java/com/google/protobuf/TextFormatTest.java
@@ -54,7 +54,7 @@ import junit.framework.TestCase;
/**
* Test case for {@link TextFormat}.
*
- * TODO(wenboz): ExtensionTest and rest of text_format_unittest.cc.
+ * <p>TODO(wenboz): ExtensionTest and rest of text_format_unittest.cc.
*
* @author wenboz@google.com (Wenbo Zhu)
*/
@@ -62,76 +62,82 @@ public class TextFormatTest extends TestCase {
// A basic string with different escapable characters for testing.
private static final String ESCAPE_TEST_STRING =
- "\"A string with ' characters \n and \r newlines and \t tabs and \001 " + "slashes \\";
+ "\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\";
// A representation of the above string with all the characters escaped.
private static final String ESCAPE_TEST_STRING_ESCAPED =
"\\\"A string with \\' characters \\n and \\r newlines "
+ "and \\t tabs and \\001 slashes \\\\";
- private static String allFieldsSetText = TestUtil.readTextFromFile(
- "text_format_unittest_data_oneof_implemented.txt");
- private static String allExtensionsSetText = TestUtil.readTextFromFile(
- "text_format_unittest_extensions_data.txt");
+ private static String allFieldsSetText =
+ TestUtil.readTextFromFile("text_format_unittest_data_oneof_implemented.txt");
+ private static String allExtensionsSetText =
+ TestUtil.readTextFromFile("text_format_unittest_extensions_data.txt");
private static String exoticText =
- "repeated_int32: -1\n" +
- "repeated_int32: -2147483648\n" +
- "repeated_int64: -1,\n" +
- "repeated_int64: -9223372036854775808\n" +
- "repeated_uint32: 4294967295\n" +
- "repeated_uint32: 2147483648\n" +
- "repeated_uint64: 18446744073709551615\n" +
- "repeated_uint64: 9223372036854775808\n" +
- "repeated_double: 123.0\n" +
- "repeated_double: 123.5\n" +
- "repeated_double: 0.125\n" +
- "repeated_double: .125\n" +
- "repeated_double: -.125\n" +
- "repeated_double: 1.23E17\n" +
- "repeated_double: 1.23E+17\n" +
- "repeated_double: -1.23e-17\n" +
- "repeated_double: .23e+17\n" +
- "repeated_double: -.23E17\n" +
- "repeated_double: 1.235E22\n" +
- "repeated_double: 1.235E-18\n" +
- "repeated_double: 123.456789\n" +
- "repeated_double: Infinity\n" +
- "repeated_double: -Infinity\n" +
- "repeated_double: NaN\n" +
- "repeated_string: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"" +
- "\\341\\210\\264\"\n" +
- "repeated_bytes: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\376\"\n";
+ ""
+ + "repeated_int32: -1\n"
+ + "repeated_int32: -2147483648\n"
+ + "repeated_int64: -1,\n"
+ + "repeated_int64: -9223372036854775808\n"
+ + "repeated_uint32: 4294967295\n"
+ + "repeated_uint32: 2147483648\n"
+ + "repeated_uint64: 18446744073709551615\n"
+ + "repeated_uint64: 9223372036854775808\n"
+ + "repeated_double: 123.0\n"
+ + "repeated_double: 123.5\n"
+ + "repeated_double: 0.125\n"
+ + "repeated_double: .125\n"
+ + "repeated_double: -.125\n"
+ + "repeated_double: 1.23E17\n"
+ + "repeated_double: 1.23E+17\n"
+ + "repeated_double: -1.23e-17\n"
+ + "repeated_double: .23e+17\n"
+ + "repeated_double: -.23E17\n"
+ + "repeated_double: 1.235E22\n"
+ + "repeated_double: 1.235E-18\n"
+ + "repeated_double: 123.456789\n"
+ + "repeated_double: Infinity\n"
+ + "repeated_double: -Infinity\n"
+ + "repeated_double: NaN\n"
+ + "repeated_string: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\""
+ + "\\341\\210\\264\"\n"
+ + "repeated_bytes: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\376\"\n";
private static String canonicalExoticText =
- exoticText.replace(": .", ": 0.").replace(": -.", ": -0.") // short-form double
- .replace("23e", "23E").replace("E+", "E").replace("0.23E17", "2.3E16").replace(",", "");
+ exoticText
+ .replace(": .", ": 0.")
+ .replace(": -.", ": -0.") // short-form double
+ .replace("23e", "23E")
+ .replace("E+", "E")
+ .replace("0.23E17", "2.3E16")
+ .replace(",", "");
private String messageSetText =
- "[protobuf_unittest.TestMessageSetExtension1] {\n" +
- " i: 123\n" +
- "}\n" +
- "[protobuf_unittest.TestMessageSetExtension2] {\n" +
- " str: \"foo\"\n" +
- "}\n";
+ ""
+ + "[protobuf_unittest.TestMessageSetExtension1] {\n"
+ + " i: 123\n"
+ + "}\n"
+ + "[protobuf_unittest.TestMessageSetExtension2] {\n"
+ + " str: \"foo\"\n"
+ + "}\n";
private String messageSetTextWithRepeatedExtension =
- "[protobuf_unittest.TestMessageSetExtension1] {\n" +
- " i: 123\n" +
- "}\n" +
- "[protobuf_unittest.TestMessageSetExtension1] {\n" +
- " i: 456\n" +
- "}\n";
+ ""
+ + "[protobuf_unittest.TestMessageSetExtension1] {\n"
+ + " i: 123\n"
+ + "}\n"
+ + "[protobuf_unittest.TestMessageSetExtension1] {\n"
+ + " i: 456\n"
+ + "}\n";
private final TextFormat.Parser parserWithOverwriteForbidden =
TextFormat.Parser.newBuilder()
- .setSingularOverwritePolicy(
- SingularOverwritePolicy.FORBID_SINGULAR_OVERWRITES)
+ .setSingularOverwritePolicy(SingularOverwritePolicy.FORBID_SINGULAR_OVERWRITES)
.build();
- private final TextFormat.Parser defaultParser =
- TextFormat.Parser.newBuilder().build();
+ private final TextFormat.Parser defaultParser = TextFormat.Parser.newBuilder().build();
/** Print TestAllTypes and compare with golden file. */
public void testPrintMessage() throws Exception {
@@ -173,38 +179,32 @@ public class TextFormatTest extends TestCase {
private UnknownFieldSet makeUnknownFieldSet() {
return UnknownFieldSet.newBuilder()
- .addField(5,
+ .addField(
+ 5,
UnknownFieldSet.Field.newBuilder()
- .addVarint(1)
- .addFixed32(2)
- .addFixed64(3)
- .addLengthDelimited(ByteString.copyFromUtf8("4"))
- .addLengthDelimited(UnknownFieldSet.newBuilder()
- .addField(12,
- UnknownFieldSet.Field.newBuilder()
- .addVarint(6)
+ .addVarint(1)
+ .addFixed32(2)
+ .addFixed64(3)
+ .addLengthDelimited(ByteString.copyFromUtf8("4"))
+ .addLengthDelimited(
+ UnknownFieldSet.newBuilder()
+ .addField(12, UnknownFieldSet.Field.newBuilder().addVarint(6).build())
+ .build()
+ .toByteString())
+ .addGroup(
+ UnknownFieldSet.newBuilder()
+ .addField(10, UnknownFieldSet.Field.newBuilder().addVarint(5).build())
.build())
- .build().toByteString())
- .addGroup(
- UnknownFieldSet.newBuilder()
- .addField(10,
- UnknownFieldSet.Field.newBuilder()
- .addVarint(5)
- .build())
.build())
- .build())
- .addField(8,
- UnknownFieldSet.Field.newBuilder()
- .addVarint(1)
- .addVarint(2)
- .addVarint(3)
- .build())
- .addField(15,
+ .addField(
+ 8, UnknownFieldSet.Field.newBuilder().addVarint(1).addVarint(2).addVarint(3).build())
+ .addField(
+ 15,
UnknownFieldSet.Field.newBuilder()
- .addVarint(0xABCDEF1234567890L)
- .addFixed32(0xABCD1234)
- .addFixed64(0xABCDEF1234567890L)
- .build())
+ .addVarint(0xABCDEF1234567890L)
+ .addFixed32(0xABCD1234)
+ .addFixed64(0xABCDEF1234567890L)
+ .build())
.build();
}
@@ -212,9 +212,7 @@ public class TextFormatTest extends TestCase {
// Test printing of unknown fields in a message.
TestEmptyMessage message =
- TestEmptyMessage.newBuilder()
- .setUnknownFields(makeUnknownFieldSet())
- .build();
+ TestEmptyMessage.newBuilder().setUnknownFields(makeUnknownFieldSet()).build();
assertEquals(
"5: 1\n"
@@ -237,34 +235,29 @@ public class TextFormatTest extends TestCase {
}
public void testPrintField() throws Exception {
- final FieldDescriptor dataField =
- OneString.getDescriptor().findFieldByName("data");
- assertEquals(
- "data: \"test data\"\n",
- TextFormat.printFieldToString(dataField, "test data"));
+ final FieldDescriptor dataField = OneString.getDescriptor().findFieldByName("data");
+ assertEquals("data: \"test data\"\n", TextFormat.printFieldToString(dataField, "test data"));
final FieldDescriptor optionalField =
- TestAllTypes.getDescriptor().findFieldByName("optional_nested_message");
+ TestAllTypes.getDescriptor().findFieldByName("optional_nested_message");
final Object value = NestedMessage.newBuilder().setBb(42).build();
assertEquals(
- "optional_nested_message {\n bb: 42\n}\n",
- TextFormat.printFieldToString(optionalField, value));
+ "optional_nested_message {\n bb: 42\n}\n",
+ TextFormat.printFieldToString(optionalField, value));
}
/**
- * Helper to construct a ByteString from a String containing only 8-bit
- * characters. The characters are converted directly to bytes, *not*
- * encoded using UTF-8.
+ * Helper to construct a ByteString from a String containing only 8-bit characters. The characters
+ * are converted directly to bytes, *not* encoded using UTF-8.
*/
private ByteString bytes(String str) {
return ByteString.copyFrom(str.getBytes(Internal.ISO_8859_1));
}
/**
- * Helper to construct a ByteString from a bunch of bytes. The inputs are
- * actually ints so that I can use hex notation and not get stupid errors
- * about precision.
+ * Helper to construct a ByteString from a bunch of bytes. The inputs are actually ints so that I
+ * can use hex notation and not get stupid errors about precision.
*/
private ByteString bytes(int... bytesAsInts) {
byte[] bytes = new byte[bytesAsInts.length];
@@ -275,54 +268,54 @@ public class TextFormatTest extends TestCase {
}
public void testPrintExotic() throws Exception {
- Message message = TestAllTypes.newBuilder()
- // Signed vs. unsigned numbers.
- .addRepeatedInt32 (-1)
- .addRepeatedUint32(-1)
- .addRepeatedInt64 (-1)
- .addRepeatedUint64(-1)
-
- .addRepeatedInt32 (1 << 31)
- .addRepeatedUint32(1 << 31)
- .addRepeatedInt64 (1L << 63)
- .addRepeatedUint64(1L << 63)
-
- // Floats of various precisions and exponents.
- .addRepeatedDouble(123)
- .addRepeatedDouble(123.5)
- .addRepeatedDouble(0.125)
- .addRepeatedDouble(.125)
- .addRepeatedDouble(-.125)
- .addRepeatedDouble(123e15)
- .addRepeatedDouble(123e15)
- .addRepeatedDouble(-1.23e-17)
- .addRepeatedDouble(.23e17)
- .addRepeatedDouble(-23e15)
- .addRepeatedDouble(123.5e20)
- .addRepeatedDouble(123.5e-20)
- .addRepeatedDouble(123.456789)
- .addRepeatedDouble(Double.POSITIVE_INFINITY)
- .addRepeatedDouble(Double.NEGATIVE_INFINITY)
- .addRepeatedDouble(Double.NaN)
-
- // Strings and bytes that needing escaping.
- .addRepeatedString("\0\001\007\b\f\n\r\t\013\\\'\"\u1234")
- .addRepeatedBytes(bytes("\0\001\007\b\f\n\r\t\013\\\'\"\u00fe"))
- .build();
+ Message message =
+ TestAllTypes.newBuilder()
+ // Signed vs. unsigned numbers.
+ .addRepeatedInt32(-1)
+ .addRepeatedUint32(-1)
+ .addRepeatedInt64(-1)
+ .addRepeatedUint64(-1)
+ .addRepeatedInt32(1 << 31)
+ .addRepeatedUint32(1 << 31)
+ .addRepeatedInt64(1L << 63)
+ .addRepeatedUint64(1L << 63)
+
+ // Floats of various precisions and exponents.
+ .addRepeatedDouble(123)
+ .addRepeatedDouble(123.5)
+ .addRepeatedDouble(0.125)
+ .addRepeatedDouble(.125)
+ .addRepeatedDouble(-.125)
+ .addRepeatedDouble(123e15)
+ .addRepeatedDouble(123e15)
+ .addRepeatedDouble(-1.23e-17)
+ .addRepeatedDouble(.23e17)
+ .addRepeatedDouble(-23e15)
+ .addRepeatedDouble(123.5e20)
+ .addRepeatedDouble(123.5e-20)
+ .addRepeatedDouble(123.456789)
+ .addRepeatedDouble(Double.POSITIVE_INFINITY)
+ .addRepeatedDouble(Double.NEGATIVE_INFINITY)
+ .addRepeatedDouble(Double.NaN)
+
+ // Strings and bytes that needing escaping.
+ .addRepeatedString("\0\001\007\b\f\n\r\t\013\\\'\"\u1234")
+ .addRepeatedBytes(bytes("\0\001\007\b\f\n\r\t\013\\\'\"\u00fe"))
+ .build();
assertEquals(canonicalExoticText, message.toString());
}
public void testPrintMessageSet() throws Exception {
TestMessageSet messageSet =
- TestMessageSet.newBuilder()
- .setExtension(
- TestMessageSetExtension1.messageSetExtension,
- TestMessageSetExtension1.newBuilder().setI(123).build())
- .setExtension(
- TestMessageSetExtension2.messageSetExtension,
- TestMessageSetExtension2.newBuilder().setStr("foo").build())
- .build();
+ TestMessageSet.newBuilder()
+ .setExtension(
+ TestMessageSetExtension1.messageSetExtension,
+ TestMessageSetExtension1.newBuilder().setI(123).build())
+ .setExtension(
+ TestMessageSetExtension2.messageSetExtension,
+ TestMessageSetExtension2.newBuilder().setStr("foo").build())
+ .build();
assertEquals(messageSetText, messageSet.toString());
}
@@ -336,22 +329,19 @@ public class TextFormatTest extends TestCase {
}
public void testParse() throws Exception {
- TestUtil.assertAllFieldsSet(
- TextFormat.parse(allFieldsSetText, TestAllTypes.class));
+ TestUtil.assertAllFieldsSet(TextFormat.parse(allFieldsSetText, TestAllTypes.class));
}
public void testMergeInitialized() throws Exception {
TestRequired.Builder builder = TestRequired.newBuilder();
TextFormat.merge(TEST_REQUIRED_INITIALIZED.toString(), builder);
- assertEquals(TEST_REQUIRED_INITIALIZED.toString(),
- builder.buildPartial().toString());
+ assertEquals(TEST_REQUIRED_INITIALIZED.toString(), builder.buildPartial().toString());
assertTrue(builder.isInitialized());
}
public void testParseInitialized() throws Exception {
TestRequired parsed =
- TextFormat.parse(TEST_REQUIRED_INITIALIZED.toString(),
- TestRequired.class);
+ TextFormat.parse(TEST_REQUIRED_INITIALIZED.toString(), TestRequired.class);
assertEquals(TEST_REQUIRED_INITIALIZED.toString(), parsed.toString());
assertTrue(parsed.isInitialized());
}
@@ -359,15 +349,13 @@ public class TextFormatTest extends TestCase {
public void testMergeUninitialized() throws Exception {
TestRequired.Builder builder = TestRequired.newBuilder();
TextFormat.merge(TEST_REQUIRED_UNINITIALIZED.toString(), builder);
- assertEquals(TEST_REQUIRED_UNINITIALIZED.toString(),
- builder.buildPartial().toString());
+ assertEquals(TEST_REQUIRED_UNINITIALIZED.toString(), builder.buildPartial().toString());
assertFalse(builder.isInitialized());
}
public void testParseUninitialized() throws Exception {
try {
- TextFormat.parse(TEST_REQUIRED_UNINITIALIZED.toString(),
- TestRequired.class);
+ TextFormat.parse(TEST_REQUIRED_UNINITIALIZED.toString(), TestRequired.class);
fail("Expected UninitializedMessageException.");
} catch (UninitializedMessageException e) {
assertEquals("Message missing required fields: b, c", e.getMessage());
@@ -393,30 +381,32 @@ public class TextFormatTest extends TestCase {
}
public void testMergeAndParseCompatibility() throws Exception {
- String original = "repeated_float: inf\n" +
- "repeated_float: -inf\n" +
- "repeated_float: nan\n" +
- "repeated_float: inff\n" +
- "repeated_float: -inff\n" +
- "repeated_float: nanf\n" +
- "repeated_float: 1.0f\n" +
- "repeated_float: infinityf\n" +
- "repeated_float: -Infinityf\n" +
- "repeated_double: infinity\n" +
- "repeated_double: -infinity\n" +
- "repeated_double: nan\n";
- String canonical = "repeated_float: Infinity\n" +
- "repeated_float: -Infinity\n" +
- "repeated_float: NaN\n" +
- "repeated_float: Infinity\n" +
- "repeated_float: -Infinity\n" +
- "repeated_float: NaN\n" +
- "repeated_float: 1.0\n" +
- "repeated_float: Infinity\n" +
- "repeated_float: -Infinity\n" +
- "repeated_double: Infinity\n" +
- "repeated_double: -Infinity\n" +
- "repeated_double: NaN\n";
+ String original =
+ "repeated_float: inf\n"
+ + "repeated_float: -inf\n"
+ + "repeated_float: nan\n"
+ + "repeated_float: inff\n"
+ + "repeated_float: -inff\n"
+ + "repeated_float: nanf\n"
+ + "repeated_float: 1.0f\n"
+ + "repeated_float: infinityf\n"
+ + "repeated_float: -Infinityf\n"
+ + "repeated_double: infinity\n"
+ + "repeated_double: -infinity\n"
+ + "repeated_double: nan\n";
+ String canonical =
+ "repeated_float: Infinity\n"
+ + "repeated_float: -Infinity\n"
+ + "repeated_float: NaN\n"
+ + "repeated_float: Infinity\n"
+ + "repeated_float: -Infinity\n"
+ + "repeated_float: NaN\n"
+ + "repeated_float: 1.0\n"
+ + "repeated_float: Infinity\n"
+ + "repeated_float: -Infinity\n"
+ + "repeated_double: Infinity\n"
+ + "repeated_double: -Infinity\n"
+ + "repeated_double: NaN\n";
// Test merge().
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
@@ -424,8 +414,7 @@ public class TextFormatTest extends TestCase {
assertEquals(canonical, builder.build().toString());
// Test parse().
- assertEquals(canonical,
- TextFormat.parse(original, TestAllTypes.class).toString());
+ assertEquals(canonical, TextFormat.parse(original, TestAllTypes.class).toString());
}
public void testMergeAndParseExotic() throws Exception {
@@ -435,8 +424,7 @@ public class TextFormatTest extends TestCase {
// Too lazy to check things individually. Don't try to debug this
// if testPrintExotic() is failing.
assertEquals(canonicalExoticText, builder.build().toString());
- assertEquals(canonicalExoticText,
- TextFormat.parse(exoticText, TestAllTypes.class).toString());
+ assertEquals(canonicalExoticText, TextFormat.parse(exoticText, TestAllTypes.class).toString());
}
public void testMergeMessageSet() throws Exception {
@@ -448,21 +436,16 @@ public class TextFormatTest extends TestCase {
TextFormat.merge(messageSetText, extensionRegistry, builder);
TestMessageSet messageSet = builder.build();
- assertTrue(messageSet.hasExtension(
- TestMessageSetExtension1.messageSetExtension));
- assertEquals(123, messageSet.getExtension(
- TestMessageSetExtension1.messageSetExtension).getI());
- assertTrue(messageSet.hasExtension(
- TestMessageSetExtension2.messageSetExtension));
- assertEquals("foo", messageSet.getExtension(
- TestMessageSetExtension2.messageSetExtension).getStr());
+ assertTrue(messageSet.hasExtension(TestMessageSetExtension1.messageSetExtension));
+ assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI());
+ assertTrue(messageSet.hasExtension(TestMessageSetExtension2.messageSetExtension));
+ assertEquals(
+ "foo", messageSet.getExtension(TestMessageSetExtension2.messageSetExtension).getStr());
builder = TestMessageSet.newBuilder();
- TextFormat.merge(messageSetTextWithRepeatedExtension, extensionRegistry,
- builder);
+ TextFormat.merge(messageSetTextWithRepeatedExtension, extensionRegistry, builder);
messageSet = builder.build();
- assertEquals(456, messageSet.getExtension(
- TestMessageSetExtension1.messageSetExtension).getI());
+ assertEquals(456, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI());
}
public void testMergeMessageSetWithOverwriteForbidden() throws Exception {
@@ -471,13 +454,11 @@ public class TextFormatTest extends TestCase {
extensionRegistry.add(TestMessageSetExtension2.messageSetExtension);
TestMessageSet.Builder builder = TestMessageSet.newBuilder();
- parserWithOverwriteForbidden.merge(
- messageSetText, extensionRegistry, builder);
+ parserWithOverwriteForbidden.merge(messageSetText, extensionRegistry, builder);
TestMessageSet messageSet = builder.build();
- assertEquals(123, messageSet.getExtension(
- TestMessageSetExtension1.messageSetExtension).getI());
- assertEquals("foo", messageSet.getExtension(
- TestMessageSetExtension2.messageSetExtension).getStr());
+ assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI());
+ assertEquals(
+ "foo", messageSet.getExtension(TestMessageSetExtension2.messageSetExtension).getStr());
builder = TestMessageSet.newBuilder();
try {
@@ -485,9 +466,10 @@ public class TextFormatTest extends TestCase {
messageSetTextWithRepeatedExtension, extensionRegistry, builder);
fail("expected parse exception");
} catch (TextFormat.ParseException e) {
- assertEquals("6:1: Non-repeated field "
- + "\"protobuf_unittest.TestMessageSetExtension1.message_set_extension\""
- + " cannot be overwritten.",
+ assertEquals(
+ "6:1: Non-repeated field "
+ + "\"protobuf_unittest.TestMessageSetExtension1.message_set_extension\""
+ + " cannot be overwritten.",
e.getMessage());
}
}
@@ -508,10 +490,11 @@ public class TextFormatTest extends TestCase {
public void testMergeComment() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(
- "# this is a comment\n" +
- "optional_int32: 1 # another comment\n" +
- "optional_int64: 2\n" +
- "# EOF comment", builder);
+ "# this is a comment\n"
+ + "optional_int32: 1 # another comment\n"
+ + "optional_int64: 2\n"
+ + "# EOF comment",
+ builder);
assertEquals(1, builder.getOptionalInt32());
assertEquals(2, builder.getOptionalInt64());
}
@@ -536,8 +519,7 @@ public class TextFormatTest extends TestCase {
}
- private void assertParseErrorWithOverwriteForbidden(String error,
- String text) {
+ private void assertParseErrorWithOverwriteForbidden(String error, String text) {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
try {
parserWithOverwriteForbidden.merge(text, TestUtil.getFullExtensionRegistry(), builder);
@@ -547,118 +529,91 @@ public class TextFormatTest extends TestCase {
}
}
- private TestAllTypes assertParseSuccessWithOverwriteForbidden(
- String text) throws TextFormat.ParseException {
+ private TestAllTypes assertParseSuccessWithOverwriteForbidden(String text)
+ throws TextFormat.ParseException {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
parserWithOverwriteForbidden.merge(text, TestUtil.getFullExtensionRegistry(), builder);
return builder.build();
}
public void testParseErrors() throws Exception {
+ assertParseError("1:16: Expected \":\".", "optional_int32 123");
+ assertParseError("1:23: Expected identifier. Found '?'", "optional_nested_enum: ?");
assertParseError(
- "1:16: Expected \":\".",
- "optional_int32 123");
- assertParseError(
- "1:23: Expected identifier. Found '?'",
- "optional_nested_enum: ?");
- assertParseError(
- "1:18: Couldn't parse integer: Number must be positive: -1",
- "optional_uint32: -1");
- assertParseError(
- "1:17: Couldn't parse integer: Number out of range for 32-bit signed " +
- "integer: 82301481290849012385230157",
- "optional_int32: 82301481290849012385230157");
+ "1:18: Couldn't parse integer: Number must be positive: -1", "optional_uint32: -1");
assertParseError(
- "1:16: Expected \"true\" or \"false\". Found \"maybe\".",
- "optional_bool: maybe");
+ "1:17: Couldn't parse integer: Number out of range for 32-bit signed "
+ + "integer: 82301481290849012385230157",
+ "optional_int32: 82301481290849012385230157");
assertParseError(
- "1:16: Expected \"true\" or \"false\". Found \"2\".",
- "optional_bool: 2");
+ "1:16: Expected \"true\" or \"false\". Found \"maybe\".", "optional_bool: maybe");
+ assertParseError("1:16: Expected \"true\" or \"false\". Found \"2\".", "optional_bool: 2");
+ assertParseError("1:18: Expected string.", "optional_string: 123");
+ assertParseError("1:18: String missing ending quote.", "optional_string: \"ueoauaoe");
assertParseError(
- "1:18: Expected string.",
- "optional_string: 123");
+ "1:18: String missing ending quote.", "optional_string: \"ueoauaoe\noptional_int32: 123");
+ assertParseError("1:18: Invalid escape sequence: '\\z'", "optional_string: \"\\z\"");
assertParseError(
- "1:18: String missing ending quote.",
- "optional_string: \"ueoauaoe");
+ "1:18: String missing ending quote.", "optional_string: \"ueoauaoe\noptional_int32: 123");
assertParseError(
- "1:18: String missing ending quote.",
- "optional_string: \"ueoauaoe\n" +
- "optional_int32: 123");
+ "1:2: Input contains unknown fields and/or extensions:\n"
+ + "1:2:\tprotobuf_unittest.TestAllTypes.[nosuchext]",
+ "[nosuchext]: 123");
assertParseError(
- "1:18: Invalid escape sequence: '\\z'",
- "optional_string: \"\\z\"");
+ "1:20: Extension \"protobuf_unittest.optional_int32_extension\" does "
+ + "not extend message type \"protobuf_unittest.TestAllTypes\".",
+ "[protobuf_unittest.optional_int32_extension]: 123");
assertParseError(
- "1:18: String missing ending quote.",
- "optional_string: \"ueoauaoe\n" +
- "optional_int32: 123");
+ "1:1: Input contains unknown fields and/or extensions:\n"
+ + "1:1:\tprotobuf_unittest.TestAllTypes.nosuchfield",
+ "nosuchfield: 123");
+ assertParseError("1:21: Expected \">\".", "OptionalGroup < a: 1");
assertParseError(
- "1:2: Input contains unknown fields and/or extensions:\n" +
- "1:2:\tprotobuf_unittest.TestAllTypes.[nosuchext]",
- "[nosuchext]: 123");
+ "1:23: Enum type \"protobuf_unittest.TestAllTypes.NestedEnum\" has no "
+ + "value named \"NO_SUCH_VALUE\".",
+ "optional_nested_enum: NO_SUCH_VALUE");
assertParseError(
- "1:20: Extension \"protobuf_unittest.optional_int32_extension\" does " +
- "not extend message type \"protobuf_unittest.TestAllTypes\".",
- "[protobuf_unittest.optional_int32_extension]: 123");
- assertParseError(
- "1:1: Input contains unknown fields and/or extensions:\n" +
- "1:1:\tprotobuf_unittest.TestAllTypes.nosuchfield",
- "nosuchfield: 123");
- assertParseError(
- "1:21: Expected \">\".",
- "OptionalGroup < a: 1");
- assertParseError(
- "1:23: Enum type \"protobuf_unittest.TestAllTypes.NestedEnum\" has no " +
- "value named \"NO_SUCH_VALUE\".",
- "optional_nested_enum: NO_SUCH_VALUE");
- assertParseError(
- "1:23: Enum type \"protobuf_unittest.TestAllTypes.NestedEnum\" has no " +
- "value with number 123.",
- "optional_nested_enum: 123");
+ "1:23: Enum type \"protobuf_unittest.TestAllTypes.NestedEnum\" has no "
+ + "value with number 123.",
+ "optional_nested_enum: 123");
// Delimiters must match.
- assertParseError(
- "1:22: Expected identifier. Found '}'",
- "OptionalGroup < a: 1 }");
- assertParseError(
- "1:22: Expected identifier. Found '>'",
- "OptionalGroup { a: 1 >");
+ assertParseError("1:22: Expected identifier. Found '}'", "OptionalGroup < a: 1 }");
+ assertParseError("1:22: Expected identifier. Found '>'", "OptionalGroup { a: 1 >");
}
// =================================================================
public void testEscape() throws Exception {
// Escape sequences.
- assertEquals("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\177",
- TextFormat.escapeBytes(bytes("\0\001\007\b\f\n\r\t\013\\\'\"\177")));
- assertEquals("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\177",
- TextFormat.escapeText("\0\001\007\b\f\n\r\t\013\\\'\"\177"));
- assertEquals(bytes("\0\001\007\b\f\n\r\t\013\\\'\""),
- TextFormat.unescapeBytes("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\""));
- assertEquals("\0\001\007\b\f\n\r\t\013\\\'\"",
- TextFormat.unescapeText("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\""));
+ assertEquals(
+ "\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\177",
+ TextFormat.escapeBytes(bytes("\0\001\007\b\f\n\r\t\013\\\'\"\177")));
+ assertEquals(
+ "\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\177",
+ TextFormat.escapeText("\0\001\007\b\f\n\r\t\013\\\'\"\177"));
+ assertEquals(
+ bytes("\0\001\007\b\f\n\r\t\013\\\'\""),
+ TextFormat.unescapeBytes("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\""));
+ assertEquals(
+ "\0\001\007\b\f\n\r\t\013\\\'\"",
+ TextFormat.unescapeText("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\""));
assertEquals(ESCAPE_TEST_STRING_ESCAPED, TextFormat.escapeText(ESCAPE_TEST_STRING));
assertEquals(ESCAPE_TEST_STRING, TextFormat.unescapeText(ESCAPE_TEST_STRING_ESCAPED));
// Invariant
- assertEquals("hello",
- TextFormat.escapeBytes(bytes("hello")));
- assertEquals("hello",
- TextFormat.escapeText("hello"));
- assertEquals(bytes("hello"),
- TextFormat.unescapeBytes("hello"));
- assertEquals("hello",
- TextFormat.unescapeText("hello"));
+ assertEquals("hello", TextFormat.escapeBytes(bytes("hello")));
+ assertEquals("hello", TextFormat.escapeText("hello"));
+ assertEquals(bytes("hello"), TextFormat.unescapeBytes("hello"));
+ assertEquals("hello", TextFormat.unescapeText("hello"));
// Unicode handling.
assertEquals("\\341\\210\\264", TextFormat.escapeText("\u1234"));
- assertEquals("\\341\\210\\264",
- TextFormat.escapeBytes(bytes(0xe1, 0x88, 0xb4)));
+ assertEquals("\\341\\210\\264", TextFormat.escapeBytes(bytes(0xe1, 0x88, 0xb4)));
assertEquals("\u1234", TextFormat.unescapeText("\\341\\210\\264"));
- assertEquals(bytes(0xe1, 0x88, 0xb4),
- TextFormat.unescapeBytes("\\341\\210\\264"));
+ assertEquals(bytes(0xe1, 0x88, 0xb4), TextFormat.unescapeBytes("\\341\\210\\264"));
assertEquals("\u1234", TextFormat.unescapeText("\\xe1\\x88\\xb4"));
- assertEquals(bytes(0xe1, 0x88, 0xb4),
- TextFormat.unescapeBytes("\\xe1\\x88\\xb4"));
+ assertEquals(bytes(0xe1, 0x88, 0xb4), TextFormat.unescapeBytes("\\xe1\\x88\\xb4"));
// Handling of strings with unescaped Unicode characters > 255.
final String zh = "\u9999\u6e2f\u4e0a\u6d77\ud84f\udf80\u8c50\u9280\u884c";
@@ -689,53 +644,48 @@ public class TextFormatTest extends TestCase {
}
public void testParseInteger() throws Exception {
- assertEquals( 0, TextFormat.parseInt32( "0"));
- assertEquals( 1, TextFormat.parseInt32( "1"));
- assertEquals( -1, TextFormat.parseInt32( "-1"));
- assertEquals( 12345, TextFormat.parseInt32( "12345"));
- assertEquals( -12345, TextFormat.parseInt32( "-12345"));
- assertEquals( 2147483647, TextFormat.parseInt32( "2147483647"));
+ assertEquals(0, TextFormat.parseInt32("0"));
+ assertEquals(1, TextFormat.parseInt32("1"));
+ assertEquals(-1, TextFormat.parseInt32("-1"));
+ assertEquals(12345, TextFormat.parseInt32("12345"));
+ assertEquals(-12345, TextFormat.parseInt32("-12345"));
+ assertEquals(2147483647, TextFormat.parseInt32("2147483647"));
assertEquals(-2147483648, TextFormat.parseInt32("-2147483648"));
- assertEquals( 0, TextFormat.parseUInt32( "0"));
- assertEquals( 1, TextFormat.parseUInt32( "1"));
- assertEquals( 12345, TextFormat.parseUInt32( "12345"));
- assertEquals( 2147483647, TextFormat.parseUInt32("2147483647"));
+ assertEquals(0, TextFormat.parseUInt32("0"));
+ assertEquals(1, TextFormat.parseUInt32("1"));
+ assertEquals(12345, TextFormat.parseUInt32("12345"));
+ assertEquals(2147483647, TextFormat.parseUInt32("2147483647"));
assertEquals((int) 2147483648L, TextFormat.parseUInt32("2147483648"));
assertEquals((int) 4294967295L, TextFormat.parseUInt32("4294967295"));
- assertEquals( 0L, TextFormat.parseInt64( "0"));
- assertEquals( 1L, TextFormat.parseInt64( "1"));
- assertEquals( -1L, TextFormat.parseInt64( "-1"));
- assertEquals( 12345L, TextFormat.parseInt64( "12345"));
- assertEquals( -12345L, TextFormat.parseInt64( "-12345"));
- assertEquals( 2147483647L, TextFormat.parseInt64( "2147483647"));
+ assertEquals(0L, TextFormat.parseInt64("0"));
+ assertEquals(1L, TextFormat.parseInt64("1"));
+ assertEquals(-1L, TextFormat.parseInt64("-1"));
+ assertEquals(12345L, TextFormat.parseInt64("12345"));
+ assertEquals(-12345L, TextFormat.parseInt64("-12345"));
+ assertEquals(2147483647L, TextFormat.parseInt64("2147483647"));
assertEquals(-2147483648L, TextFormat.parseInt64("-2147483648"));
- assertEquals( 4294967295L, TextFormat.parseInt64( "4294967295"));
- assertEquals( 4294967296L, TextFormat.parseInt64( "4294967296"));
- assertEquals(9223372036854775807L,
- TextFormat.parseInt64("9223372036854775807"));
- assertEquals(-9223372036854775808L,
- TextFormat.parseInt64("-9223372036854775808"));
-
- assertEquals( 0L, TextFormat.parseUInt64( "0"));
- assertEquals( 1L, TextFormat.parseUInt64( "1"));
- assertEquals( 12345L, TextFormat.parseUInt64( "12345"));
- assertEquals( 2147483647L, TextFormat.parseUInt64( "2147483647"));
- assertEquals( 4294967295L, TextFormat.parseUInt64( "4294967295"));
- assertEquals( 4294967296L, TextFormat.parseUInt64( "4294967296"));
- assertEquals(9223372036854775807L,
- TextFormat.parseUInt64("9223372036854775807"));
- assertEquals(-9223372036854775808L,
- TextFormat.parseUInt64("9223372036854775808"));
+ assertEquals(4294967295L, TextFormat.parseInt64("4294967295"));
+ assertEquals(4294967296L, TextFormat.parseInt64("4294967296"));
+ assertEquals(9223372036854775807L, TextFormat.parseInt64("9223372036854775807"));
+ assertEquals(-9223372036854775808L, TextFormat.parseInt64("-9223372036854775808"));
+
+ assertEquals(0L, TextFormat.parseUInt64("0"));
+ assertEquals(1L, TextFormat.parseUInt64("1"));
+ assertEquals(12345L, TextFormat.parseUInt64("12345"));
+ assertEquals(2147483647L, TextFormat.parseUInt64("2147483647"));
+ assertEquals(4294967295L, TextFormat.parseUInt64("4294967295"));
+ assertEquals(4294967296L, TextFormat.parseUInt64("4294967296"));
+ assertEquals(9223372036854775807L, TextFormat.parseUInt64("9223372036854775807"));
+ assertEquals(-9223372036854775808L, TextFormat.parseUInt64("9223372036854775808"));
assertEquals(-1L, TextFormat.parseUInt64("18446744073709551615"));
// Hex
assertEquals(0x1234abcd, TextFormat.parseInt32("0x1234abcd"));
assertEquals(-0x1234abcd, TextFormat.parseInt32("-0x1234abcd"));
assertEquals(-1, TextFormat.parseUInt64("0xffffffffffffffff"));
- assertEquals(0x7fffffffffffffffL,
- TextFormat.parseInt64("0x7fffffffffffffff"));
+ assertEquals(0x7fffffffffffffffL, TextFormat.parseInt64("0x7fffffffffffffff"));
// Octal
assertEquals(01234567, TextFormat.parseInt32("01234567"));
@@ -815,26 +765,26 @@ public class TextFormatTest extends TestCase {
public void testParseLongString() throws Exception {
String longText =
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890";
+ "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890";
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge("optional_string: \"" + longText + "\"", builder);
@@ -843,16 +793,16 @@ public class TextFormatTest extends TestCase {
public void testParseBoolean() throws Exception {
String goodText =
- "repeated_bool: t repeated_bool : 0\n" +
- "repeated_bool :f repeated_bool:1\n" +
- "repeated_bool: False repeated_bool: True";
+ "repeated_bool: t repeated_bool : 0\n"
+ + "repeated_bool :f repeated_bool:1\n"
+ + "repeated_bool: False repeated_bool: True";
String goodTextCanonical =
- "repeated_bool: true\n" +
- "repeated_bool: false\n" +
- "repeated_bool: false\n" +
- "repeated_bool: true\n" +
- "repeated_bool: false\n" +
- "repeated_bool: true\n";
+ "repeated_bool: true\n"
+ + "repeated_bool: false\n"
+ + "repeated_bool: false\n"
+ + "repeated_bool: true\n"
+ + "repeated_bool: false\n"
+ + "repeated_bool: true\n";
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(goodText, builder);
assertEquals(goodTextCanonical, builder.build().toString());
@@ -881,83 +831,75 @@ public class TextFormatTest extends TestCase {
public void testPrintFieldValue() throws Exception {
assertPrintFieldValue("\"Hello\"", "Hello", "repeated_string");
- assertPrintFieldValue("123.0", 123f, "repeated_float");
- assertPrintFieldValue("123.0", 123d, "repeated_double");
- assertPrintFieldValue("123", 123, "repeated_int32");
- assertPrintFieldValue("123", 123L, "repeated_int64");
- assertPrintFieldValue("true", true, "repeated_bool");
+ assertPrintFieldValue("123.0", 123f, "repeated_float");
+ assertPrintFieldValue("123.0", 123d, "repeated_double");
+ assertPrintFieldValue("123", 123, "repeated_int32");
+ assertPrintFieldValue("123", 123L, "repeated_int64");
+ assertPrintFieldValue("true", true, "repeated_bool");
assertPrintFieldValue("4294967295", 0xFFFFFFFF, "repeated_uint32");
- assertPrintFieldValue("18446744073709551615", 0xFFFFFFFFFFFFFFFFL,
- "repeated_uint64");
- assertPrintFieldValue("\"\\001\\002\\003\"",
- ByteString.copyFrom(new byte[] {1, 2, 3}), "repeated_bytes");
+ assertPrintFieldValue("18446744073709551615", 0xFFFFFFFFFFFFFFFFL, "repeated_uint64");
+ assertPrintFieldValue(
+ "\"\\001\\002\\003\"", ByteString.copyFrom(new byte[] {1, 2, 3}), "repeated_bytes");
}
- private void assertPrintFieldValue(String expect, Object value,
- String fieldName) throws Exception {
+ private void assertPrintFieldValue(String expect, Object value, String fieldName)
+ throws Exception {
StringBuilder sb = new StringBuilder();
- TextFormat.printFieldValue(
- TestAllTypes.getDescriptor().findFieldByName(fieldName),
- value, sb);
+ TextFormat.printFieldValue(TestAllTypes.getDescriptor().findFieldByName(fieldName), value, sb);
assertEquals(expect, sb.toString());
}
public void testShortDebugString() {
- assertEquals("optional_nested_message { bb: 42 } repeated_int32: 1"
- + " repeated_uint32: 2",
- TextFormat.shortDebugString(TestAllTypes.newBuilder()
- .addRepeatedInt32(1)
- .addRepeatedUint32(2)
- .setOptionalNestedMessage(
- NestedMessage.newBuilder().setBb(42).build())
- .build()));
+ assertEquals(
+ "optional_nested_message { bb: 42 } repeated_int32: 1 repeated_uint32: 2",
+ TextFormat.shortDebugString(
+ TestAllTypes.newBuilder()
+ .addRepeatedInt32(1)
+ .addRepeatedUint32(2)
+ .setOptionalNestedMessage(NestedMessage.newBuilder().setBb(42).build())
+ .build()));
}
public void testShortDebugString_field() {
- final FieldDescriptor dataField =
- OneString.getDescriptor().findFieldByName("data");
- assertEquals(
- "data: \"test data\"",
- TextFormat.shortDebugString(dataField, "test data"));
+ final FieldDescriptor dataField = OneString.getDescriptor().findFieldByName("data");
+ assertEquals("data: \"test data\"", TextFormat.shortDebugString(dataField, "test data"));
final FieldDescriptor optionalField =
- TestAllTypes.getDescriptor().findFieldByName("optional_nested_message");
+ TestAllTypes.getDescriptor().findFieldByName("optional_nested_message");
final Object value = NestedMessage.newBuilder().setBb(42).build();
assertEquals(
- "optional_nested_message { bb: 42 }",
- TextFormat.shortDebugString(optionalField, value));
+ "optional_nested_message { bb: 42 }", TextFormat.shortDebugString(optionalField, value));
}
public void testShortDebugString_unknown() {
- assertEquals("5: 1 5: 0x00000002 5: 0x0000000000000003 5: \"4\" 5: { 12: 6 } 5 { 10: 5 }"
- + " 8: 1 8: 2 8: 3 15: 12379813812177893520 15: 0xabcd1234 15:"
- + " 0xabcdef1234567890",
+ assertEquals(
+ "5: 1 5: 0x00000002 5: 0x0000000000000003 5: \"4\" 5: { 12: 6 } 5 { 10: 5 }"
+ + " 8: 1 8: 2 8: 3 15: 12379813812177893520 15: 0xabcd1234 15:"
+ + " 0xabcdef1234567890",
TextFormat.shortDebugString(makeUnknownFieldSet()));
}
public void testPrintToUnicodeString() throws Exception {
assertEquals(
- "optional_string: \"abc\u3042efg\"\n" +
- "optional_bytes: \"\\343\\201\\202\"\n" +
- "repeated_string: \"\u3093XYZ\"\n",
- TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
- .setOptionalString("abc\u3042efg")
- .setOptionalBytes(bytes(0xe3, 0x81, 0x82))
- .addRepeatedString("\u3093XYZ")
- .build()));
+ "optional_string: \"abc\u3042efg\"\n"
+ + "optional_bytes: \"\\343\\201\\202\"\n"
+ + "repeated_string: \"\u3093XYZ\"\n",
+ TextFormat.printToUnicodeString(
+ TestAllTypes.newBuilder()
+ .setOptionalString("abc\u3042efg")
+ .setOptionalBytes(bytes(0xe3, 0x81, 0x82))
+ .addRepeatedString("\u3093XYZ")
+ .build()));
// Double quotes and backslashes should be escaped
assertEquals(
"optional_string: \"a\\\\bc\\\"ef\\\"g\"\n",
- TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
- .setOptionalString("a\\bc\"ef\"g")
- .build()));
+ TextFormat.printToUnicodeString(
+ TestAllTypes.newBuilder().setOptionalString("a\\bc\"ef\"g").build()));
// Test escaping roundtrip
- TestAllTypes message = TestAllTypes.newBuilder()
- .setOptionalString("a\\bc\\\"ef\"g")
- .build();
+ TestAllTypes message = TestAllTypes.newBuilder().setOptionalString("a\\bc\\\"ef\"g").build();
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(TextFormat.printToUnicodeString(message), builder);
assertEquals(message.getOptionalString(), builder.getOptionalString());
@@ -965,35 +907,34 @@ public class TextFormatTest extends TestCase {
public void testPrintToUnicodeStringWithNewlines() throws Exception {
// No newlines at start and end
- assertEquals("optional_string: \"test newlines\\n\\nin\\nstring\"\n",
- TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
- .setOptionalString("test newlines\n\nin\nstring")
- .build()));
+ assertEquals(
+ "optional_string: \"test newlines\\n\\nin\\nstring\"\n",
+ TextFormat.printToUnicodeString(
+ TestAllTypes.newBuilder().setOptionalString("test newlines\n\nin\nstring").build()));
// Newlines at start and end
- assertEquals("optional_string: \"\\ntest\\nnewlines\\n\\nin\\nstring\\n\"\n",
- TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
- .setOptionalString("\ntest\nnewlines\n\nin\nstring\n")
- .build()));
+ assertEquals(
+ "optional_string: \"\\ntest\\nnewlines\\n\\nin\\nstring\\n\"\n",
+ TextFormat.printToUnicodeString(
+ TestAllTypes.newBuilder()
+ .setOptionalString("\ntest\nnewlines\n\nin\nstring\n")
+ .build()));
// Strings with 0, 1 and 2 newlines.
- assertEquals("optional_string: \"\"\n",
- TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
- .setOptionalString("")
- .build()));
- assertEquals("optional_string: \"\\n\"\n",
- TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
- .setOptionalString("\n")
- .build()));
- assertEquals("optional_string: \"\\n\\n\"\n",
- TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
- .setOptionalString("\n\n")
- .build()));
+ assertEquals(
+ "optional_string: \"\"\n",
+ TextFormat.printToUnicodeString(TestAllTypes.newBuilder().setOptionalString("").build()));
+ assertEquals(
+ "optional_string: \"\\n\"\n",
+ TextFormat.printToUnicodeString(TestAllTypes.newBuilder().setOptionalString("\n").build()));
+ assertEquals(
+ "optional_string: \"\\n\\n\"\n",
+ TextFormat.printToUnicodeString(
+ TestAllTypes.newBuilder().setOptionalString("\n\n").build()));
// Test escaping roundtrip
- TestAllTypes message = TestAllTypes.newBuilder()
- .setOptionalString("\ntest\nnewlines\n\nin\nstring\n")
- .build();
+ TestAllTypes message =
+ TestAllTypes.newBuilder().setOptionalString("\ntest\nnewlines\n\nin\nstring\n").build();
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(TextFormat.printToUnicodeString(message), builder);
assertEquals(message.getOptionalString(), builder.getOptionalString());
@@ -1002,57 +943,51 @@ public class TextFormatTest extends TestCase {
public void testPrintToUnicodeString_unknown() {
assertEquals(
"1: \"\\343\\201\\202\"\n",
- TextFormat.printToUnicodeString(UnknownFieldSet.newBuilder()
- .addField(1,
- UnknownFieldSet.Field.newBuilder()
- .addLengthDelimited(bytes(0xe3, 0x81, 0x82)).build())
- .build()));
+ TextFormat.printToUnicodeString(
+ UnknownFieldSet.newBuilder()
+ .addField(
+ 1,
+ UnknownFieldSet.Field.newBuilder()
+ .addLengthDelimited(bytes(0xe3, 0x81, 0x82))
+ .build())
+ .build()));
}
// See additional coverage in testOneofOverwriteForbidden and testMapOverwriteForbidden.
public void testParseNonRepeatedFields() throws Exception {
+ assertParseSuccessWithOverwriteForbidden("repeated_int32: 1\nrepeated_int32: 2\n");
+ assertParseSuccessWithOverwriteForbidden("RepeatedGroup { a: 1 }\nRepeatedGroup { a: 2 }\n");
assertParseSuccessWithOverwriteForbidden(
- "repeated_int32: 1\n" +
- "repeated_int32: 2\n");
- assertParseSuccessWithOverwriteForbidden(
- "RepeatedGroup { a: 1 }\n" +
- "RepeatedGroup { a: 2 }\n");
- assertParseSuccessWithOverwriteForbidden(
- "repeated_nested_message { bb: 1 }\n" +
- "repeated_nested_message { bb: 2 }\n");
+ "repeated_nested_message { bb: 1 }\nrepeated_nested_message { bb: 2 }\n");
assertParseErrorWithOverwriteForbidden(
- "3:17: Non-repeated field " +
- "\"protobuf_unittest.TestAllTypes.optional_int32\" " +
- "cannot be overwritten.",
- "optional_int32: 1\n" +
- "optional_bool: true\n" +
- "optional_int32: 1\n");
+ "3:17: Non-repeated field "
+ + "\"protobuf_unittest.TestAllTypes.optional_int32\" "
+ + "cannot be overwritten.",
+ "optional_int32: 1\noptional_bool: true\noptional_int32: 1\n");
assertParseErrorWithOverwriteForbidden(
- "2:17: Non-repeated field " +
- "\"protobuf_unittest.TestAllTypes.optionalgroup\" " +
- "cannot be overwritten.",
- "OptionalGroup { a: 1 }\n" +
- "OptionalGroup { }\n");
+ "2:17: Non-repeated field "
+ + "\"protobuf_unittest.TestAllTypes.optionalgroup\" "
+ + "cannot be overwritten.",
+ "OptionalGroup { a: 1 }\nOptionalGroup { }\n");
assertParseErrorWithOverwriteForbidden(
- "2:33: Non-repeated field " +
- "\"protobuf_unittest.TestAllTypes.optional_nested_message\" " +
- "cannot be overwritten.",
- "optional_nested_message { }\n" +
- "optional_nested_message { bb: 3 }\n");
+ "2:33: Non-repeated field "
+ + "\"protobuf_unittest.TestAllTypes.optional_nested_message\" "
+ + "cannot be overwritten.",
+ "optional_nested_message { }\noptional_nested_message { bb: 3 }\n");
assertParseErrorWithOverwriteForbidden(
- "2:16: Non-repeated field " +
- "\"protobuf_unittest.TestAllTypes.default_int32\" " +
- "cannot be overwritten.",
- "default_int32: 41\n" + // the default value
- "default_int32: 41\n");
+ "2:16: Non-repeated field "
+ + "\"protobuf_unittest.TestAllTypes.default_int32\" "
+ + "cannot be overwritten.",
+ "default_int32: 41\n"
+ + // the default value
+ "default_int32: 41\n");
assertParseErrorWithOverwriteForbidden(
- "2:17: Non-repeated field " +
- "\"protobuf_unittest.TestAllTypes.default_string\" " +
- "cannot be overwritten.",
- "default_string: \"zxcv\"\n" +
- "default_string: \"asdf\"\n");
+ "2:17: Non-repeated field "
+ + "\"protobuf_unittest.TestAllTypes.default_string\" "
+ + "cannot be overwritten.",
+ "default_string: \"zxcv\"\ndefault_string: \"asdf\"\n");
}
public void testParseShortRepeatedFormOfRepeatedFields() throws Exception {
@@ -1073,27 +1008,20 @@ public class TextFormatTest extends TestCase {
public void testParseShortRepeatedFormWithTrailingComma() throws Exception {
assertParseErrorWithOverwriteForbidden(
- "1:38: Expected identifier. Found \']\'",
- "repeated_foreign_enum: [FOREIGN_FOO, ]\n");
+ "1:38: Expected identifier. Found \']\'", "repeated_foreign_enum: [FOREIGN_FOO, ]\n");
assertParseErrorWithOverwriteForbidden(
- "1:22: Couldn't parse integer: For input string: \"]\"",
- "repeated_int32: [ 1, ]\n");
+ "1:22: Couldn't parse integer: For input string: \"]\"", "repeated_int32: [ 1, ]\n");
+ assertParseErrorWithOverwriteForbidden("1:25: Expected \"{\".", "RepeatedGroup [{ a: 1 },]\n");
assertParseErrorWithOverwriteForbidden(
- "1:25: Expected \"{\".",
- "RepeatedGroup [{ a: 1 },]\n");
- assertParseErrorWithOverwriteForbidden(
- "1:37: Expected \"{\".",
- "repeated_nested_message [{ bb: 1 }, ]\n");
+ "1:37: Expected \"{\".", "repeated_nested_message [{ bb: 1 }, ]\n");
// See also testMapShortFormTrailingComma.
}
public void testParseShortRepeatedFormOfNonRepeatedFields() throws Exception {
assertParseErrorWithOverwriteForbidden(
- "1:17: Couldn't parse integer: For input string: \"[\"",
- "optional_int32: [1]\n");
+ "1:17: Couldn't parse integer: For input string: \"[\"", "optional_int32: [1]\n");
assertParseErrorWithOverwriteForbidden(
- "1:17: Couldn't parse integer: For input string: \"[\"",
- "optional_int32: []\n");
+ "1:17: Couldn't parse integer: For input string: \"[\"", "optional_int32: []\n");
}
// =======================================================================
@@ -1115,9 +1043,11 @@ public class TextFormatTest extends TestCase {
parserWithOverwriteForbidden.merge(input, TestUtil.getFullExtensionRegistry(), builder);
fail("Expected parse exception.");
} catch (TextFormat.ParseException e) {
- assertEquals("1:36: Field \"protobuf_unittest.TestOneof2.foo_int\""
- + " is specified along with field \"protobuf_unittest.TestOneof2.foo_string\","
- + " another member of oneof \"foo\".", e.getMessage());
+ assertEquals(
+ "1:36: Field \"protobuf_unittest.TestOneof2.foo_int\""
+ + " is specified along with field \"protobuf_unittest.TestOneof2.foo_string\","
+ + " another member of oneof \"foo\".",
+ e.getMessage());
}
}
@@ -1157,8 +1087,8 @@ public class TextFormatTest extends TestCase {
public void testMapShortForm() throws Exception {
String text =
"string_to_int32_field [{ key: 'x' value: 10 }, { key: 'y' value: 20 }]\n"
- + "int32_to_message_field "
- + "[{ key: 1 value { value: 100 } }, { key: 2 value: { value: 200 } }]\n";
+ + "int32_to_message_field "
+ + "[{ key: 1 value { value: 100 } }, { key: 2 value: { value: 200 } }]\n";
TestMap.Builder dest = TestMap.newBuilder();
parserWithOverwriteForbidden.merge(text, dest);
TestMap message = dest.build();
@@ -1169,8 +1099,7 @@ public class TextFormatTest extends TestCase {
}
public void testMapShortFormEmpty() throws Exception {
- String text = "string_to_int32_field []\n"
- + "int32_to_message_field: []\n";
+ String text = "string_to_int32_field []\nint32_to_message_field: []\n";
TestMap.Builder dest = TestMap.newBuilder();
parserWithOverwriteForbidden.merge(text, dest);
TestMap message = dest.build();
@@ -1231,19 +1160,19 @@ public class TextFormatTest extends TestCase {
final String stringData =
"optional_int32: 1\n"
- + "optional_int64: 2\n"
- + " optional_double: 2.4\n"
- + "repeated_int32: 5\n"
- + "repeated_int32: 10\n"
- + "optional_nested_message <\n"
- + " bb: 78\n"
- + ">\n"
- + "repeated_nested_message <\n"
- + " bb: 79\n"
- + ">\n"
- + "repeated_nested_message <\n"
- + " bb: 80\n"
- + ">";
+ + "optional_int64: 2\n"
+ + " optional_double: 2.4\n"
+ + "repeated_int32: 5\n"
+ + "repeated_int32: 10\n"
+ + "optional_nested_message <\n"
+ + " bb: 78\n"
+ + ">\n"
+ + "repeated_nested_message <\n"
+ + " bb: 79\n"
+ + ">\n"
+ + "repeated_nested_message <\n"
+ + " bb: 80\n"
+ + ">";
parser.merge(stringData, builder);
TextFormatParseInfoTree tree = treeBuilder.build();
@@ -1303,9 +1232,7 @@ public class TextFormatTest extends TestCase {
fail(
String.format(
"Tree/descriptor/fieldname did not contain index %d, line %d column %d expected",
- index,
- line,
- column));
+ index, line, column));
}
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java b/java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java
index 88cbbf86..cc18547b 100644
--- a/java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java
+++ b/java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java
@@ -39,8 +39,7 @@ import com.google.protobuf.TextFormat.ParseException;
import junit.framework.TestCase;
/**
- * Unit tests for protos that keep unknown enum values rather than discard
- * them as unknown fields.
+ * Unit tests for protos that keep unknown enum values rather than discard them as unknown fields.
*/
public class UnknownEnumValueTest extends TestCase {
public void testUnknownEnumValues() throws Exception {
@@ -58,7 +57,7 @@ public class UnknownEnumValueTest extends TestCase {
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, message.getRepeatedNestedEnum(0));
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, message.getRepeatedNestedEnumList().get(0));
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, message.getPackedNestedEnum(0));
-
+
// Test serialization and parsing.
ByteString data = message.toByteString();
message = TestAllTypes.parseFrom(data);
@@ -71,19 +70,19 @@ public class UnknownEnumValueTest extends TestCase {
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, message.getRepeatedNestedEnum(0));
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, message.getRepeatedNestedEnumList().get(0));
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, message.getPackedNestedEnum(0));
-
+
// Test toBuilder().
builder = message.toBuilder();
assertEquals(4321, builder.getOptionalNestedEnumValue());
assertEquals(5432, builder.getRepeatedNestedEnumValue(0));
assertEquals(5432, builder.getRepeatedNestedEnumValueList().get(0).intValue());
- assertEquals(6543, builder.getPackedNestedEnumValue(0));
+ assertEquals(6543, builder.getPackedNestedEnumValue(0));
// Returns UNRECOGNIZED if an enum type is requested.
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getOptionalNestedEnum());
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getRepeatedNestedEnum(0));
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getRepeatedNestedEnumList().get(0));
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getPackedNestedEnum(0));
-
+
// Test mergeFrom().
builder = TestAllTypes.newBuilder().mergeFrom(message);
assertEquals(4321, builder.getOptionalNestedEnumValue());
@@ -95,7 +94,7 @@ public class UnknownEnumValueTest extends TestCase {
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getRepeatedNestedEnum(0));
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getRepeatedNestedEnumList().get(0));
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getPackedNestedEnum(0));
-
+
// Test equals() and hashCode()
TestAllTypes sameMessage = builder.build();
assertEquals(message, sameMessage);
@@ -123,7 +122,7 @@ public class UnknownEnumValueTest extends TestCase {
// Expected.
}
}
-
+
public void testUnknownEnumValueInReflectionApi() throws Exception {
Descriptor descriptor = TestAllTypes.getDescriptor();
FieldDescriptor optionalNestedEnumField = descriptor.findFieldByName("optional_nested_enum");
@@ -132,14 +131,13 @@ public class UnknownEnumValueTest extends TestCase {
EnumDescriptor enumType = TestAllTypes.NestedEnum.getDescriptor();
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
- builder.setField(optionalNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(4321));
- builder.addRepeatedField(repeatedNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(5432));
- builder.addRepeatedField(packedNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(6543));
+ builder.setField(optionalNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(4321));
+ builder.addRepeatedField(
+ repeatedNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(5432));
+ builder.addRepeatedField(
+ packedNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(6543));
TestAllTypes message = builder.build();
-
+
// Getters will return unknown enum values as EnumValueDescriptor.
EnumValueDescriptor unknown4321 =
(EnumValueDescriptor) message.getField(optionalNestedEnumField);
@@ -166,79 +164,78 @@ public class UnknownEnumValueTest extends TestCase {
message = builder.build();
// Like other descriptors, unknown EnumValueDescriptor can be compared by
// object identity.
- assertTrue(unknown6543 == message.getField(optionalNestedEnumField));
- assertTrue(unknown4321 == message.getRepeatedField(repeatedNestedEnumField, 0));
- assertTrue(unknown5432 == message.getRepeatedField(packedNestedEnumField, 0));
+ assertSame(message.getField(optionalNestedEnumField), unknown6543);
+ assertSame(message.getRepeatedField(repeatedNestedEnumField, 0), unknown4321);
+ assertSame(message.getRepeatedField(packedNestedEnumField, 0), unknown5432);
}
-
+
public void testUnknownEnumValueWithDynamicMessage() throws Exception {
Descriptor descriptor = TestAllTypes.getDescriptor();
FieldDescriptor optionalNestedEnumField = descriptor.findFieldByName("optional_nested_enum");
FieldDescriptor repeatedNestedEnumField = descriptor.findFieldByName("repeated_nested_enum");
FieldDescriptor packedNestedEnumField = descriptor.findFieldByName("packed_nested_enum");
EnumDescriptor enumType = TestAllTypes.NestedEnum.getDescriptor();
-
+
Message dynamicMessageDefaultInstance = DynamicMessage.getDefaultInstance(descriptor);
Message.Builder builder = dynamicMessageDefaultInstance.newBuilderForType();
- builder.setField(optionalNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(4321));
- builder.addRepeatedField(repeatedNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(5432));
- builder.addRepeatedField(packedNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(6543));
+ builder.setField(optionalNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(4321));
+ builder.addRepeatedField(
+ repeatedNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(5432));
+ builder.addRepeatedField(
+ packedNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(6543));
Message message = builder.build();
- assertEquals(4321,
- ((EnumValueDescriptor) message.getField(optionalNestedEnumField)).getNumber());
- assertEquals(5432,
+ assertEquals(
+ 4321, ((EnumValueDescriptor) message.getField(optionalNestedEnumField)).getNumber());
+ assertEquals(
+ 5432,
((EnumValueDescriptor) message.getRepeatedField(repeatedNestedEnumField, 0)).getNumber());
- assertEquals(6543,
+ assertEquals(
+ 6543,
((EnumValueDescriptor) message.getRepeatedField(packedNestedEnumField, 0)).getNumber());
-
+
// Test reflection based serialization/parsing implementation.
ByteString data = message.toByteString();
- message = dynamicMessageDefaultInstance
- .newBuilderForType()
- .mergeFrom(data)
- .build();
- assertEquals(4321,
- ((EnumValueDescriptor) message.getField(optionalNestedEnumField)).getNumber());
- assertEquals(5432,
+ message = dynamicMessageDefaultInstance.newBuilderForType().mergeFrom(data).build();
+ assertEquals(
+ 4321, ((EnumValueDescriptor) message.getField(optionalNestedEnumField)).getNumber());
+ assertEquals(
+ 5432,
((EnumValueDescriptor) message.getRepeatedField(repeatedNestedEnumField, 0)).getNumber());
- assertEquals(6543,
+ assertEquals(
+ 6543,
((EnumValueDescriptor) message.getRepeatedField(packedNestedEnumField, 0)).getNumber());
-
+
// Test reflection based equals()/hashCode().
builder = dynamicMessageDefaultInstance.newBuilderForType();
- builder.setField(optionalNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(4321));
- builder.addRepeatedField(repeatedNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(5432));
- builder.addRepeatedField(packedNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(6543));
+ builder.setField(optionalNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(4321));
+ builder.addRepeatedField(
+ repeatedNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(5432));
+ builder.addRepeatedField(
+ packedNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(6543));
Message sameMessage = builder.build();
assertEquals(message, sameMessage);
assertEquals(message.hashCode(), sameMessage.hashCode());
- builder.setField(optionalNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(0));
+ builder.setField(optionalNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(0));
Message differentMessage = builder.build();
assertFalse(message.equals(differentMessage));
}
-
+
public void testUnknownEnumValuesInTextFormat() {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
builder.setOptionalNestedEnumValue(4321);
builder.addRepeatedNestedEnumValue(5432);
builder.addPackedNestedEnumValue(6543);
TestAllTypes message = builder.build();
-
+
// We can print a message with unknown enum values.
String textData = TextFormat.printToString(message);
assertEquals(
"optional_nested_enum: UNKNOWN_ENUM_VALUE_NestedEnum_4321\n"
- + "repeated_nested_enum: UNKNOWN_ENUM_VALUE_NestedEnum_5432\n"
- + "packed_nested_enum: UNKNOWN_ENUM_VALUE_NestedEnum_6543\n", textData);
-
+ + "repeated_nested_enum: UNKNOWN_ENUM_VALUE_NestedEnum_5432\n"
+ + "packed_nested_enum: UNKNOWN_ENUM_VALUE_NestedEnum_6543\n",
+ textData);
+
// Parsing unknown enum values will fail just like parsing other kinds of
// unknown fields.
try {
diff --git a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java
index 8ce0ca73..a947d271 100644
--- a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java
+++ b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java
@@ -110,9 +110,7 @@ public class UnknownFieldSetLiteTest extends TestCase {
}
public void testMergeFieldFrom() throws IOException {
- Foo foo = Foo.newBuilder()
- .setValue(2)
- .build();
+ Foo foo = Foo.newBuilder().setValue(2).build();
CodedInputStream input = CodedInputStream.newInstance(foo.toByteArray());
@@ -123,9 +121,7 @@ public class UnknownFieldSetLiteTest extends TestCase {
}
public void testSerializedSize() throws IOException {
- Foo foo = Foo.newBuilder()
- .setValue(2)
- .build();
+ Foo foo = Foo.newBuilder().setValue(2).build();
CodedInputStream input = CodedInputStream.newInstance(foo.toByteArray());
@@ -136,9 +132,7 @@ public class UnknownFieldSetLiteTest extends TestCase {
}
public void testHashCodeAfterDeserialization() throws IOException {
- Foo foo = Foo.newBuilder()
- .setValue(2)
- .build();
+ Foo foo = Foo.newBuilder().setValue(2).build();
Foo fooDeserialized = Foo.parseFrom(foo.toByteArray());
@@ -172,8 +166,7 @@ public class UnknownFieldSetLiteTest extends TestCase {
UnknownFieldSetLite builder = UnknownFieldSetLite.newInstance();
builder.mergeVarintField(10, -6);
- CodedInputStream input =
- CodedInputStream.newInstance(toByteString(builder).toByteArray());
+ CodedInputStream input = CodedInputStream.newInstance(toByteString(builder).toByteArray());
int tag = input.readTag();
assertEquals(10, WireFormat.getTagFieldNumber(tag));
@@ -217,8 +210,9 @@ public class UnknownFieldSetLiteTest extends TestCase {
}
public void testMutableCopyOf_empty() {
- UnknownFieldSetLite unknownFields = UnknownFieldSetLite.mutableCopyOf(
- UnknownFieldSetLite.getDefaultInstance(), UnknownFieldSetLite.getDefaultInstance());
+ UnknownFieldSetLite unknownFields =
+ UnknownFieldSetLite.mutableCopyOf(
+ UnknownFieldSetLite.getDefaultInstance(), UnknownFieldSetLite.getDefaultInstance());
unknownFields.checkMutable();
assertEquals(0, unknownFields.getSerializedSize());
@@ -226,18 +220,17 @@ public class UnknownFieldSetLiteTest extends TestCase {
}
public void testRoundTrips() throws InvalidProtocolBufferException {
- Foo foo = Foo.newBuilder()
- .setValue(1)
- .setExtension(Bar.fooExt, Bar.newBuilder()
- .setName("name")
- .build())
- .setExtension(LiteEqualsAndHash.varint, 22)
- .setExtension(LiteEqualsAndHash.fixed32, 44)
- .setExtension(LiteEqualsAndHash.fixed64, 66L)
- .setExtension(LiteEqualsAndHash.myGroup, LiteEqualsAndHash.MyGroup.newBuilder()
- .setGroupValue("value")
- .build())
- .build();
+ Foo foo =
+ Foo.newBuilder()
+ .setValue(1)
+ .setExtension(Bar.fooExt, Bar.newBuilder().setName("name").build())
+ .setExtension(LiteEqualsAndHash.varint, 22)
+ .setExtension(LiteEqualsAndHash.fixed32, 44)
+ .setExtension(LiteEqualsAndHash.fixed64, 66L)
+ .setExtension(
+ LiteEqualsAndHash.myGroup,
+ LiteEqualsAndHash.MyGroup.newBuilder().setGroupValue("value").build())
+ .build();
Foo copy = Foo.parseFrom(foo.toByteArray());
@@ -310,16 +303,15 @@ public class UnknownFieldSetLiteTest extends TestCase {
}
public void testTruncatedInput() {
- Foo foo = Foo.newBuilder()
- .setValue(1)
- .setExtension(Bar.fooExt, Bar.newBuilder()
- .setName("name")
- .build())
- .setExtension(LiteEqualsAndHash.varint, 22)
- .setExtension(LiteEqualsAndHash.myGroup, LiteEqualsAndHash.MyGroup.newBuilder()
- .setGroupValue("value")
- .build())
- .build();
+ Foo foo =
+ Foo.newBuilder()
+ .setValue(1)
+ .setExtension(Bar.fooExt, Bar.newBuilder().setName("name").build())
+ .setExtension(LiteEqualsAndHash.varint, 22)
+ .setExtension(
+ LiteEqualsAndHash.myGroup,
+ LiteEqualsAndHash.MyGroup.newBuilder().setGroupValue("value").build())
+ .build();
try {
Foo.parseFrom(foo.toByteString().substring(0, foo.toByteString().size() - 10));
@@ -328,63 +320,72 @@ public class UnknownFieldSetLiteTest extends TestCase {
// Expected.
}
}
-
+
public void testMakeImmutable() throws Exception {
UnknownFieldSetLite unknownFields = UnknownFieldSetLite.newInstance();
unknownFields.makeImmutable();
-
+
try {
unknownFields.mergeVarintField(1, 1);
fail();
- } catch (UnsupportedOperationException expected) {}
-
+ } catch (UnsupportedOperationException expected) {
+ }
+
try {
unknownFields.mergeLengthDelimitedField(2, ByteString.copyFromUtf8("hello"));
fail();
- } catch (UnsupportedOperationException expected) {}
-
+ } catch (UnsupportedOperationException expected) {
+ }
+
try {
unknownFields.mergeFieldFrom(1, CodedInputStream.newInstance(new byte[0]));
fail();
- } catch (UnsupportedOperationException expected) {}
+ } catch (UnsupportedOperationException expected) {
+ }
}
-
+
public void testEndToEnd() throws Exception {
TestAllTypesLite testAllTypes = TestAllTypesLite.getDefaultInstance();
try {
testAllTypes.unknownFields.checkMutable();
fail();
- } catch (UnsupportedOperationException expected) {}
-
+ } catch (UnsupportedOperationException expected) {
+ }
+
testAllTypes = TestAllTypesLite.parseFrom(new byte[0]);
try {
testAllTypes.unknownFields.checkMutable();
fail();
- } catch (UnsupportedOperationException expected) {}
-
+ } catch (UnsupportedOperationException expected) {
+ }
+
testAllTypes = TestAllTypesLite.newBuilder().build();
try {
testAllTypes.unknownFields.checkMutable();
fail();
- } catch (UnsupportedOperationException expected) {}
-
- testAllTypes = TestAllTypesLite.newBuilder()
- .setDefaultBool(true)
- .build();
+ } catch (UnsupportedOperationException expected) {
+ }
+
+ testAllTypes = TestAllTypesLite.newBuilder().setDefaultBool(true).build();
try {
testAllTypes.unknownFields.checkMutable();
fail();
- } catch (UnsupportedOperationException expected) {}
-
- TestAllExtensionsLite testAllExtensions = TestAllExtensionsLite.newBuilder()
- .mergeFrom(TestAllExtensionsLite.newBuilder()
- .setExtension(UnittestLite.optionalInt32ExtensionLite, 2)
- .build().toByteArray())
- .build();
+ } catch (UnsupportedOperationException expected) {
+ }
+
+ TestAllExtensionsLite testAllExtensions =
+ TestAllExtensionsLite.newBuilder()
+ .mergeFrom(
+ TestAllExtensionsLite.newBuilder()
+ .setExtension(UnittestLite.optionalInt32ExtensionLite, 2)
+ .build()
+ .toByteArray())
+ .build();
try {
testAllExtensions.unknownFields.checkMutable();
fail();
- } catch (UnsupportedOperationException expected) {}
+ } catch (UnsupportedOperationException expected) {
+ }
}
private ByteString toByteString(UnknownFieldSetLite unknownFields) {
diff --git a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java
index 1a84806a..86630f65 100644
--- a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java
+++ b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java
@@ -69,13 +69,10 @@ public class UnknownFieldSetTest extends TestCase {
ByteString getBizarroData() throws Exception {
UnknownFieldSet.Builder bizarroFields = UnknownFieldSet.newBuilder();
- UnknownFieldSet.Field varintField =
- UnknownFieldSet.Field.newBuilder().addVarint(1).build();
- UnknownFieldSet.Field fixed32Field =
- UnknownFieldSet.Field.newBuilder().addFixed32(1).build();
+ UnknownFieldSet.Field varintField = UnknownFieldSet.Field.newBuilder().addVarint(1).build();
+ UnknownFieldSet.Field fixed32Field = UnknownFieldSet.Field.newBuilder().addFixed32(1).build();
- for (Map.Entry<Integer, UnknownFieldSet.Field> entry :
- unknownFields.asMap().entrySet()) {
+ for (Map.Entry<Integer, UnknownFieldSet.Field> entry : unknownFields.asMap().entrySet()) {
if (entry.getValue().getVarintList().isEmpty()) {
// Original field is not a varint, so use a varint.
bizarroFields.addField(entry.getKey(), varintField);
@@ -102,34 +99,30 @@ public class UnknownFieldSetTest extends TestCase {
public void testVarint() throws Exception {
UnknownFieldSet.Field field = getField("optional_int32");
assertEquals(1, field.getVarintList().size());
- assertEquals(allFields.getOptionalInt32(),
- (long) field.getVarintList().get(0));
+ assertEquals(allFields.getOptionalInt32(), (long) field.getVarintList().get(0));
}
public void testFixed32() throws Exception {
UnknownFieldSet.Field field = getField("optional_fixed32");
assertEquals(1, field.getFixed32List().size());
- assertEquals(allFields.getOptionalFixed32(),
- (int) field.getFixed32List().get(0));
+ assertEquals(allFields.getOptionalFixed32(), (int) field.getFixed32List().get(0));
}
public void testFixed64() throws Exception {
UnknownFieldSet.Field field = getField("optional_fixed64");
assertEquals(1, field.getFixed64List().size());
- assertEquals(allFields.getOptionalFixed64(),
- (long) field.getFixed64List().get(0));
+ assertEquals(allFields.getOptionalFixed64(), (long) field.getFixed64List().get(0));
}
public void testLengthDelimited() throws Exception {
UnknownFieldSet.Field field = getField("optional_bytes");
assertEquals(1, field.getLengthDelimitedList().size());
- assertEquals(allFields.getOptionalBytes(),
- field.getLengthDelimitedList().get(0));
+ assertEquals(allFields.getOptionalBytes(), field.getLengthDelimitedList().get(0));
}
public void testGroup() throws Exception {
Descriptors.FieldDescriptor nestedFieldDescriptor =
- TestAllTypes.OptionalGroup.getDescriptor().findFieldByName("a");
+ TestAllTypes.OptionalGroup.getDescriptor().findFieldByName("a");
assertNotNull(nestedFieldDescriptor);
UnknownFieldSet.Field field = getField("optionalgroup");
@@ -139,11 +132,9 @@ public class UnknownFieldSetTest extends TestCase {
assertEquals(1, group.asMap().size());
assertTrue(group.hasField(nestedFieldDescriptor.getNumber()));
- UnknownFieldSet.Field nestedField =
- group.getField(nestedFieldDescriptor.getNumber());
+ UnknownFieldSet.Field nestedField = group.getField(nestedFieldDescriptor.getNumber());
assertEquals(1, nestedField.getVarintList().size());
- assertEquals(allFields.getOptionalGroup().getA(),
- (long) nestedField.getVarintList().get(0));
+ assertEquals(allFields.getOptionalGroup().getA(), (long) nestedField.getVarintList().get(0));
}
public void testSerialize() throws Exception {
@@ -154,59 +145,44 @@ public class UnknownFieldSetTest extends TestCase {
}
public void testCopyFrom() throws Exception {
- TestEmptyMessage message =
- TestEmptyMessage.newBuilder().mergeFrom(emptyMessage).build();
+ TestEmptyMessage message = TestEmptyMessage.newBuilder().mergeFrom(emptyMessage).build();
assertEquals(emptyMessage.toString(), message.toString());
}
public void testMergeFrom() throws Exception {
TestEmptyMessage source =
- TestEmptyMessage.newBuilder()
- .setUnknownFields(
- UnknownFieldSet.newBuilder()
- .addField(2,
- UnknownFieldSet.Field.newBuilder()
- .addVarint(2).build())
- .addField(3,
- UnknownFieldSet.Field.newBuilder()
- .addVarint(4).build())
- .build())
- .build();
+ TestEmptyMessage.newBuilder()
+ .setUnknownFields(
+ UnknownFieldSet.newBuilder()
+ .addField(2, UnknownFieldSet.Field.newBuilder().addVarint(2).build())
+ .addField(3, UnknownFieldSet.Field.newBuilder().addVarint(4).build())
+ .build())
+ .build();
TestEmptyMessage destination =
- TestEmptyMessage.newBuilder()
- .setUnknownFields(
- UnknownFieldSet.newBuilder()
- .addField(1,
- UnknownFieldSet.Field.newBuilder()
- .addVarint(1).build())
- .addField(3,
- UnknownFieldSet.Field.newBuilder()
- .addVarint(3).build())
- .build())
- .mergeFrom(source)
- .build();
-
- assertEquals(
- "1: 1\n" +
- "2: 2\n" +
- "3: 3\n" +
- "3: 4\n",
- destination.toString());
+ TestEmptyMessage.newBuilder()
+ .setUnknownFields(
+ UnknownFieldSet.newBuilder()
+ .addField(1, UnknownFieldSet.Field.newBuilder().addVarint(1).build())
+ .addField(3, UnknownFieldSet.Field.newBuilder().addVarint(3).build())
+ .build())
+ .mergeFrom(source)
+ .build();
+
+ assertEquals("1: 1\n2: 2\n3: 3\n3: 4\n", destination.toString());
}
public void testClear() throws Exception {
- UnknownFieldSet fields =
- UnknownFieldSet.newBuilder().mergeFrom(unknownFields).clear().build();
+ UnknownFieldSet fields = UnknownFieldSet.newBuilder().mergeFrom(unknownFields).clear().build();
assertTrue(fields.asMap().isEmpty());
}
public void testClearMessage() throws Exception {
TestEmptyMessage message =
- TestEmptyMessage.newBuilder().mergeFrom(emptyMessage).clear().build();
+ TestEmptyMessage.newBuilder().mergeFrom(emptyMessage).clear().build();
assertEquals(0, message.getSerializedSize());
}
-
+
public void testClearField() throws Exception {
int fieldNumber = unknownFields.asMap().keySet().iterator().next();
UnknownFieldSet fields =
@@ -218,10 +194,9 @@ public class UnknownFieldSetTest extends TestCase {
// Test mixing known and unknown fields when parsing.
UnknownFieldSet fields =
- UnknownFieldSet.newBuilder(unknownFields)
- .addField(123456,
- UnknownFieldSet.Field.newBuilder().addVarint(654321).build())
- .build();
+ UnknownFieldSet.newBuilder(unknownFields)
+ .addField(123456, UnknownFieldSet.Field.newBuilder().addVarint(654321).build())
+ .build();
ByteString data = fields.toByteString();
TestAllTypes destination = TestAllTypes.parseFrom(data);
@@ -229,8 +204,7 @@ public class UnknownFieldSetTest extends TestCase {
TestUtil.assertAllFieldsSet(destination);
assertEquals(1, destination.getUnknownFields().asMap().size());
- UnknownFieldSet.Field field =
- destination.getUnknownFields().getField(123456);
+ UnknownFieldSet.Field field = destination.getUnknownFields().getField(123456);
assertEquals(1, field.getVarintList().size());
assertEquals(654321, (long) field.getVarintList().get(0));
}
@@ -253,10 +227,9 @@ public class UnknownFieldSetTest extends TestCase {
// they are declared as extension numbers.
TestEmptyMessageWithExtensions message =
- TestEmptyMessageWithExtensions.parseFrom(allFieldsData);
+ TestEmptyMessageWithExtensions.parseFrom(allFieldsData);
- assertEquals(unknownFields.asMap().size(),
- message.getUnknownFields().asMap().size());
+ assertEquals(unknownFields.asMap().size(), message.getUnknownFields().asMap().size());
assertEquals(allFieldsData, message.toByteString());
}
@@ -265,134 +238,99 @@ public class UnknownFieldSetTest extends TestCase {
// when parsing extensions.
ByteString bizarroData = getBizarroData();
- TestAllExtensions allExtensionsMessage =
- TestAllExtensions.parseFrom(bizarroData);
+ TestAllExtensions allExtensionsMessage = TestAllExtensions.parseFrom(bizarroData);
TestEmptyMessage emptyMessage = TestEmptyMessage.parseFrom(bizarroData);
// All fields should have been interpreted as unknown, so the debug strings
// should be the same.
- assertEquals(emptyMessage.toString(),
- allExtensionsMessage.toString());
+ assertEquals(emptyMessage.toString(), allExtensionsMessage.toString());
}
public void testParseUnknownEnumValue() throws Exception {
Descriptors.FieldDescriptor singularField =
- TestAllTypes.getDescriptor().findFieldByName("optional_nested_enum");
+ TestAllTypes.getDescriptor().findFieldByName("optional_nested_enum");
Descriptors.FieldDescriptor repeatedField =
- TestAllTypes.getDescriptor().findFieldByName("repeated_nested_enum");
+ TestAllTypes.getDescriptor().findFieldByName("repeated_nested_enum");
assertNotNull(singularField);
assertNotNull(repeatedField);
ByteString data =
- UnknownFieldSet.newBuilder()
- .addField(singularField.getNumber(),
- UnknownFieldSet.Field.newBuilder()
- .addVarint(TestAllTypes.NestedEnum.BAR.getNumber())
- .addVarint(5) // not valid
- .build())
- .addField(repeatedField.getNumber(),
- UnknownFieldSet.Field.newBuilder()
- .addVarint(TestAllTypes.NestedEnum.FOO.getNumber())
- .addVarint(4) // not valid
- .addVarint(TestAllTypes.NestedEnum.BAZ.getNumber())
- .addVarint(6) // not valid
- .build())
- .build()
- .toByteString();
+ UnknownFieldSet.newBuilder()
+ .addField(
+ singularField.getNumber(),
+ UnknownFieldSet.Field.newBuilder()
+ .addVarint(TestAllTypes.NestedEnum.BAR.getNumber())
+ .addVarint(5) // not valid
+ .build())
+ .addField(
+ repeatedField.getNumber(),
+ UnknownFieldSet.Field.newBuilder()
+ .addVarint(TestAllTypes.NestedEnum.FOO.getNumber())
+ .addVarint(4) // not valid
+ .addVarint(TestAllTypes.NestedEnum.BAZ.getNumber())
+ .addVarint(6) // not valid
+ .build())
+ .build()
+ .toByteString();
{
TestAllTypes message = TestAllTypes.parseFrom(data);
- assertEquals(TestAllTypes.NestedEnum.BAR,
- message.getOptionalNestedEnum());
+ assertEquals(TestAllTypes.NestedEnum.BAR, message.getOptionalNestedEnum());
assertEquals(
- Arrays.asList(TestAllTypes.NestedEnum.FOO, TestAllTypes.NestedEnum.BAZ),
- message.getRepeatedNestedEnumList());
- assertEquals(Arrays.asList(5L),
- message.getUnknownFields()
- .getField(singularField.getNumber())
- .getVarintList());
- assertEquals(Arrays.asList(4L, 6L),
- message.getUnknownFields()
- .getField(repeatedField.getNumber())
- .getVarintList());
+ Arrays.asList(TestAllTypes.NestedEnum.FOO, TestAllTypes.NestedEnum.BAZ),
+ message.getRepeatedNestedEnumList());
+ assertEquals(
+ Arrays.asList(5L),
+ message.getUnknownFields().getField(singularField.getNumber()).getVarintList());
+ assertEquals(
+ Arrays.asList(4L, 6L),
+ message.getUnknownFields().getField(repeatedField.getNumber()).getVarintList());
}
{
TestAllExtensions message =
- TestAllExtensions.parseFrom(data, TestUtil.getExtensionRegistry());
- assertEquals(TestAllTypes.NestedEnum.BAR,
- message.getExtension(UnittestProto.optionalNestedEnumExtension));
+ TestAllExtensions.parseFrom(data, TestUtil.getExtensionRegistry());
+ assertEquals(
+ TestAllTypes.NestedEnum.BAR,
+ message.getExtension(UnittestProto.optionalNestedEnumExtension));
+ assertEquals(
+ Arrays.asList(TestAllTypes.NestedEnum.FOO, TestAllTypes.NestedEnum.BAZ),
+ message.getExtension(UnittestProto.repeatedNestedEnumExtension));
assertEquals(
- Arrays.asList(TestAllTypes.NestedEnum.FOO, TestAllTypes.NestedEnum.BAZ),
- message.getExtension(UnittestProto.repeatedNestedEnumExtension));
- assertEquals(Arrays.asList(5L),
- message.getUnknownFields()
- .getField(singularField.getNumber())
- .getVarintList());
- assertEquals(Arrays.asList(4L, 6L),
- message.getUnknownFields()
- .getField(repeatedField.getNumber())
- .getVarintList());
+ Arrays.asList(5L),
+ message.getUnknownFields().getField(singularField.getNumber()).getVarintList());
+ assertEquals(
+ Arrays.asList(4L, 6L),
+ message.getUnknownFields().getField(repeatedField.getNumber()).getVarintList());
}
}
public void testLargeVarint() throws Exception {
ByteString data =
- UnknownFieldSet.newBuilder()
- .addField(1,
- UnknownFieldSet.Field.newBuilder()
- .addVarint(0x7FFFFFFFFFFFFFFFL)
- .build())
- .build()
- .toByteString();
+ UnknownFieldSet.newBuilder()
+ .addField(1, UnknownFieldSet.Field.newBuilder().addVarint(0x7FFFFFFFFFFFFFFFL).build())
+ .build()
+ .toByteString();
UnknownFieldSet parsed = UnknownFieldSet.parseFrom(data);
UnknownFieldSet.Field field = parsed.getField(1);
assertEquals(1, field.getVarintList().size());
- assertEquals(0x7FFFFFFFFFFFFFFFL, (long)field.getVarintList().get(0));
+ assertEquals(0x7FFFFFFFFFFFFFFFL, (long) field.getVarintList().get(0));
}
public void testEqualsAndHashCode() {
- UnknownFieldSet.Field fixed32Field =
- UnknownFieldSet.Field.newBuilder()
- .addFixed32(1)
- .build();
- UnknownFieldSet.Field fixed64Field =
- UnknownFieldSet.Field.newBuilder()
- .addFixed64(1)
- .build();
- UnknownFieldSet.Field varIntField =
- UnknownFieldSet.Field.newBuilder()
- .addVarint(1)
- .build();
+ UnknownFieldSet.Field fixed32Field = UnknownFieldSet.Field.newBuilder().addFixed32(1).build();
+ UnknownFieldSet.Field fixed64Field = UnknownFieldSet.Field.newBuilder().addFixed64(1).build();
+ UnknownFieldSet.Field varIntField = UnknownFieldSet.Field.newBuilder().addVarint(1).build();
UnknownFieldSet.Field lengthDelimitedField =
- UnknownFieldSet.Field.newBuilder()
- .addLengthDelimited(ByteString.EMPTY)
- .build();
+ UnknownFieldSet.Field.newBuilder().addLengthDelimited(ByteString.EMPTY).build();
UnknownFieldSet.Field groupField =
- UnknownFieldSet.Field.newBuilder()
- .addGroup(unknownFields)
- .build();
+ UnknownFieldSet.Field.newBuilder().addGroup(unknownFields).build();
- UnknownFieldSet a =
- UnknownFieldSet.newBuilder()
- .addField(1, fixed32Field)
- .build();
- UnknownFieldSet b =
- UnknownFieldSet.newBuilder()
- .addField(1, fixed64Field)
- .build();
- UnknownFieldSet c =
- UnknownFieldSet.newBuilder()
- .addField(1, varIntField)
- .build();
- UnknownFieldSet d =
- UnknownFieldSet.newBuilder()
- .addField(1, lengthDelimitedField)
- .build();
- UnknownFieldSet e =
- UnknownFieldSet.newBuilder()
- .addField(1, groupField)
- .build();
+ UnknownFieldSet a = UnknownFieldSet.newBuilder().addField(1, fixed32Field).build();
+ UnknownFieldSet b = UnknownFieldSet.newBuilder().addField(1, fixed64Field).build();
+ UnknownFieldSet c = UnknownFieldSet.newBuilder().addField(1, varIntField).build();
+ UnknownFieldSet d = UnknownFieldSet.newBuilder().addField(1, lengthDelimitedField).build();
+ UnknownFieldSet e = UnknownFieldSet.newBuilder().addField(1, groupField).build();
checkEqualsIsConsistent(a);
checkEqualsIsConsistent(b);
@@ -413,12 +351,10 @@ public class UnknownFieldSetTest extends TestCase {
}
/**
- * Asserts that the given field sets are not equal and have different
- * hash codes.
+ * Asserts that the given field sets are not equal and have different hash codes.
*
- * @warning It's valid for non-equal objects to have the same hash code, so
- * this test is stricter than it needs to be. However, this should happen
- * relatively rarely.
+ * @warning It's valid for non-equal objects to have the same hash code, so this test is stricter
+ * than it needs to be. However, this should happen relatively rarely.
*/
private void checkNotEqual(UnknownFieldSet s1, UnknownFieldSet s2) {
String equalsError = String.format("%s should not be equal to %s", s1, s2);
@@ -430,9 +366,7 @@ public class UnknownFieldSetTest extends TestCase {
s1.hashCode() == s2.hashCode());
}
- /**
- * Asserts that the given field sets are equal and have identical hash codes.
- */
+ /** Asserts that the given field sets are equal and have identical hash codes. */
private void checkEqualsIsConsistent(UnknownFieldSet set) {
// Object should be equal to itself.
assertEquals(set, set);
diff --git a/java/core/src/test/java/com/google/protobuf/WireFormatTest.java b/java/core/src/test/java/com/google/protobuf/WireFormatTest.java
index 425b56da..45a396ac 100644
--- a/java/core/src/test/java/com/google/protobuf/WireFormatTest.java
+++ b/java/core/src/test/java/com/google/protobuf/WireFormatTest.java
@@ -54,6 +54,13 @@ import junit.framework.TestCase;
* @author kenton@google.com (Kenton Varda)
*/
public class WireFormatTest extends TestCase {
+
+ private static final int TYPE_ID_1 =
+ TestMessageSetExtension1.getDescriptor().getExtensions().get(0).getNumber();
+ private static final int TYPE_ID_2 =
+ TestMessageSetExtension2.getDescriptor().getExtensions().get(0).getNumber();
+ private static final int UNKNOWN_TYPE_ID = 1550055;
+
public void testSerialization() throws Exception {
TestAllTypes message = TestUtil.getAllSet();
@@ -102,8 +109,7 @@ public class WireFormatTest extends TestCase {
assertEquals(rawBytes, rawBytes2);
}
- public void testSerializationPackedWithoutGetSerializedSize()
- throws Exception {
+ public void testSerializationPackedWithoutGetSerializedSize() throws Exception {
// Write directly to an OutputStream, without invoking getSerializedSize()
// This used to be a bug where the size of a packed field was incorrect,
// since getSerializedSize() was never invoked.
@@ -118,8 +124,7 @@ public class WireFormatTest extends TestCase {
codedOutput.flush();
- TestPackedTypes message2 = TestPackedTypes.parseFrom(
- outputStream.toByteArray());
+ TestPackedTypes message2 = TestPackedTypes.parseFrom(outputStream.toByteArray());
TestUtil.assertPackedFieldsSet(message2);
}
@@ -134,8 +139,7 @@ public class WireFormatTest extends TestCase {
ExtensionRegistryLite registry = TestUtil.getExtensionRegistry();
- TestAllExtensions message2 =
- TestAllExtensions.parseFrom(rawBytes, registry);
+ TestAllExtensions message2 = TestAllExtensions.parseFrom(rawBytes, registry);
TestUtil.assertAllExtensionsSet(message2);
}
@@ -147,8 +151,7 @@ public class WireFormatTest extends TestCase {
ExtensionRegistryLite registry = TestUtil.getExtensionRegistry();
- TestPackedExtensions message2 =
- TestPackedExtensions.parseFrom(rawBytes, registry);
+ TestPackedExtensions message2 = TestPackedExtensions.parseFrom(rawBytes, registry);
TestUtil.assertPackedExtensionsSet(message2);
}
@@ -192,25 +195,27 @@ public class WireFormatTest extends TestCase {
// Tests that fields are written in order even when extension ranges
// are interleaved with field numbers.
ByteString data =
- TestFieldOrderings.newBuilder()
- .setMyInt(1)
- .setMyString("foo")
- .setMyFloat(1.0F)
- .setExtension(UnittestProto.myExtensionInt, 23)
- .setExtension(UnittestProto.myExtensionString, "bar")
- .build().toByteString();
+ TestFieldOrderings.newBuilder()
+ .setMyInt(1)
+ .setMyString("foo")
+ .setMyFloat(1.0F)
+ .setExtension(UnittestProto.myExtensionInt, 23)
+ .setExtension(UnittestProto.myExtensionString, "bar")
+ .build()
+ .toByteString();
assertFieldsInOrder(data);
Descriptors.Descriptor descriptor = TestFieldOrderings.getDescriptor();
- ByteString dynamic_data =
- DynamicMessage.newBuilder(TestFieldOrderings.getDescriptor())
- .setField(descriptor.findFieldByName("my_int"), 1L)
- .setField(descriptor.findFieldByName("my_string"), "foo")
- .setField(descriptor.findFieldByName("my_float"), 1.0F)
- .setField(UnittestProto.myExtensionInt.getDescriptor(), 23)
- .setField(UnittestProto.myExtensionString.getDescriptor(), "bar")
- .build().toByteString();
- assertFieldsInOrder(dynamic_data);
+ ByteString dynamicData =
+ DynamicMessage.newBuilder(TestFieldOrderings.getDescriptor())
+ .setField(descriptor.findFieldByName("my_int"), 1L)
+ .setField(descriptor.findFieldByName("my_string"), "foo")
+ .setField(descriptor.findFieldByName("my_float"), 1.0F)
+ .setField(UnittestProto.myExtensionInt.getDescriptor(), 23)
+ .setField(UnittestProto.myExtensionString.getDescriptor(), "bar")
+ .build()
+ .toByteString();
+ assertFieldsInOrder(dynamicData);
}
private ExtensionRegistry getTestFieldOrderingsRegistry() {
@@ -224,36 +229,35 @@ public class WireFormatTest extends TestCase {
// Make sure we can parse a message that contains multiple extensions
// ranges.
TestFieldOrderings source =
- TestFieldOrderings.newBuilder()
- .setMyInt(1)
- .setMyString("foo")
- .setMyFloat(1.0F)
- .setExtension(UnittestProto.myExtensionInt, 23)
- .setExtension(UnittestProto.myExtensionString, "bar")
- .build();
+ TestFieldOrderings.newBuilder()
+ .setMyInt(1)
+ .setMyString("foo")
+ .setMyFloat(1.0F)
+ .setExtension(UnittestProto.myExtensionInt, 23)
+ .setExtension(UnittestProto.myExtensionString, "bar")
+ .build();
TestFieldOrderings dest =
- TestFieldOrderings.parseFrom(source.toByteString(),
- getTestFieldOrderingsRegistry());
+ TestFieldOrderings.parseFrom(source.toByteString(), getTestFieldOrderingsRegistry());
assertEquals(source, dest);
}
-
+
private static ExtensionRegistry getTestExtensionInsideTableRegistry() {
ExtensionRegistry result = ExtensionRegistry.newInstance();
result.add(UnittestProto.testExtensionInsideTableExtension);
return result;
}
-
+
public void testExtensionInsideTable() throws Exception {
// Make sure the extension within the range of table is parsed correctly in experimental
// runtime.
TestExtensionInsideTable source =
TestExtensionInsideTable.newBuilder()
- .setField1(1)
- .setExtension(UnittestProto.testExtensionInsideTableExtension, 23)
- .build();
+ .setField1(1)
+ .setExtension(UnittestProto.testExtensionInsideTableExtension, 23)
+ .build();
TestExtensionInsideTable dest =
- TestExtensionInsideTable.parseFrom(source.toByteString(),
- getTestExtensionInsideTableRegistry());
+ TestExtensionInsideTable.parseFrom(
+ source.toByteString(), getTestExtensionInsideTableRegistry());
assertEquals(source, dest);
}
@@ -261,25 +265,19 @@ public class WireFormatTest extends TestCase {
// Same as above except with DynamicMessage.
Descriptors.Descriptor descriptor = TestFieldOrderings.getDescriptor();
DynamicMessage source =
- DynamicMessage.newBuilder(TestFieldOrderings.getDescriptor())
- .setField(descriptor.findFieldByName("my_int"), 1L)
- .setField(descriptor.findFieldByName("my_string"), "foo")
- .setField(descriptor.findFieldByName("my_float"), 1.0F)
- .setField(UnittestProto.myExtensionInt.getDescriptor(), 23)
- .setField(UnittestProto.myExtensionString.getDescriptor(), "bar")
- .build();
+ DynamicMessage.newBuilder(TestFieldOrderings.getDescriptor())
+ .setField(descriptor.findFieldByName("my_int"), 1L)
+ .setField(descriptor.findFieldByName("my_string"), "foo")
+ .setField(descriptor.findFieldByName("my_float"), 1.0F)
+ .setField(UnittestProto.myExtensionInt.getDescriptor(), 23)
+ .setField(UnittestProto.myExtensionString.getDescriptor(), "bar")
+ .build();
DynamicMessage dest =
- DynamicMessage.parseFrom(descriptor, source.toByteString(),
- getTestFieldOrderingsRegistry());
+ DynamicMessage.parseFrom(
+ descriptor, source.toByteString(), getTestFieldOrderingsRegistry());
assertEquals(source, dest);
}
- private static final int UNKNOWN_TYPE_ID = 1550055;
- private static final int TYPE_ID_1 =
- TestMessageSetExtension1.getDescriptor().getExtensions().get(0).getNumber();
- private static final int TYPE_ID_2 =
- TestMessageSetExtension2.getDescriptor().getExtensions().get(0).getNumber();
-
public void testSerializeMessageSetEagerly() throws Exception {
testSerializeMessageSetWithFlag(true);
}
@@ -288,26 +286,26 @@ public class WireFormatTest extends TestCase {
testSerializeMessageSetWithFlag(false);
}
- private void testSerializeMessageSetWithFlag(boolean eagerParsing)
- throws Exception {
+ private void testSerializeMessageSetWithFlag(boolean eagerParsing) throws Exception {
ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing);
// Set up a TestMessageSet with two known messages and an unknown one.
TestMessageSet messageSet =
- TestMessageSet.newBuilder()
- .setExtension(
- TestMessageSetExtension1.messageSetExtension,
- TestMessageSetExtension1.newBuilder().setI(123).build())
- .setExtension(
- TestMessageSetExtension2.messageSetExtension,
- TestMessageSetExtension2.newBuilder().setStr("foo").build())
- .setUnknownFields(
- UnknownFieldSet.newBuilder()
- .addField(UNKNOWN_TYPE_ID,
- UnknownFieldSet.Field.newBuilder()
- .addLengthDelimited(ByteString.copyFromUtf8("bar"))
- .build())
- .build())
- .build();
+ TestMessageSet.newBuilder()
+ .setExtension(
+ TestMessageSetExtension1.messageSetExtension,
+ TestMessageSetExtension1.newBuilder().setI(123).build())
+ .setExtension(
+ TestMessageSetExtension2.messageSetExtension,
+ TestMessageSetExtension2.newBuilder().setStr("foo").build())
+ .setUnknownFields(
+ UnknownFieldSet.newBuilder()
+ .addField(
+ UNKNOWN_TYPE_ID,
+ UnknownFieldSet.Field.newBuilder()
+ .addLengthDelimited(ByteString.copyFromUtf8("bar"))
+ .build())
+ .build())
+ .build();
ByteString data = messageSet.toByteString();
@@ -322,13 +320,11 @@ public class WireFormatTest extends TestCase {
assertEquals(UNKNOWN_TYPE_ID, raw.getItem(2).getTypeId());
TestMessageSetExtension1 message1 =
- TestMessageSetExtension1.parseFrom(
- raw.getItem(0).getMessage().toByteArray());
+ TestMessageSetExtension1.parseFrom(raw.getItem(0).getMessage());
assertEquals(123, message1.getI());
TestMessageSetExtension2 message2 =
- TestMessageSetExtension2.parseFrom(
- raw.getItem(1).getMessage().toByteArray());
+ TestMessageSetExtension2.parseFrom(raw.getItem(1).getMessage());
assertEquals("foo", message2.getStr());
assertEquals("bar", raw.getItem(2).getMessage().toStringUtf8());
@@ -338,12 +334,11 @@ public class WireFormatTest extends TestCase {
testParseMessageSetWithFlag(true);
}
- public void testParseMessageSetNotEagerly()throws Exception {
+ public void testParseMessageSetNotEagerly() throws Exception {
testParseMessageSetWithFlag(false);
}
- private void testParseMessageSetWithFlag(boolean eagerParsing)
- throws Exception {
+ private void testParseMessageSetWithFlag(boolean eagerParsing) throws Exception {
ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing);
ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
extensionRegistry.add(TestMessageSetExtension1.messageSetExtension);
@@ -351,40 +346,34 @@ public class WireFormatTest extends TestCase {
// Set up a RawMessageSet with two known messages and an unknown one.
RawMessageSet raw =
- RawMessageSet.newBuilder()
- .addItem(
- RawMessageSet.Item.newBuilder()
- .setTypeId(TYPE_ID_1)
- .setMessage(
- TestMessageSetExtension1.newBuilder()
- .setI(123)
- .build().toByteString())
- .build())
- .addItem(
- RawMessageSet.Item.newBuilder()
- .setTypeId(TYPE_ID_2)
- .setMessage(
- TestMessageSetExtension2.newBuilder()
- .setStr("foo")
- .build().toByteString())
- .build())
- .addItem(
- RawMessageSet.Item.newBuilder()
- .setTypeId(UNKNOWN_TYPE_ID)
- .setMessage(ByteString.copyFromUtf8("bar"))
- .build())
- .build();
+ RawMessageSet.newBuilder()
+ .addItem(
+ RawMessageSet.Item.newBuilder()
+ .setTypeId(TYPE_ID_1)
+ .setMessage(
+ TestMessageSetExtension1.newBuilder().setI(123).build().toByteString())
+ .build())
+ .addItem(
+ RawMessageSet.Item.newBuilder()
+ .setTypeId(TYPE_ID_2)
+ .setMessage(
+ TestMessageSetExtension2.newBuilder().setStr("foo").build().toByteString())
+ .build())
+ .addItem(
+ RawMessageSet.Item.newBuilder()
+ .setTypeId(UNKNOWN_TYPE_ID)
+ .setMessage(ByteString.copyFromUtf8("bar"))
+ .build())
+ .build();
ByteString data = raw.toByteString();
// Parse as a TestMessageSet and check the contents.
- TestMessageSet messageSet =
- TestMessageSet.parseFrom(data, extensionRegistry);
+ TestMessageSet messageSet = TestMessageSet.parseFrom(data, extensionRegistry);
- assertEquals(123, messageSet.getExtension(
- TestMessageSetExtension1.messageSetExtension).getI());
- assertEquals("foo", messageSet.getExtension(
- TestMessageSetExtension2.messageSetExtension).getStr());
+ assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI());
+ assertEquals(
+ "foo", messageSet.getExtension(TestMessageSetExtension2.messageSetExtension).getStr());
// Check for unknown field with type LENGTH_DELIMITED,
// number UNKNOWN_TYPE_ID, and contents "bar".
@@ -405,35 +394,27 @@ public class WireFormatTest extends TestCase {
testParseMessageSetExtensionWithFlag(false);
}
- private void testParseMessageSetExtensionWithFlag(boolean eagerParsing)
- throws Exception {
+ private void testParseMessageSetExtensionWithFlag(boolean eagerParsing) throws Exception {
ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing);
ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
extensionRegistry.add(TestMessageSetExtension1.messageSetExtension);
// Set up a RawMessageSet with a known messages.
- int TYPE_ID_1 =
- TestMessageSetExtension1
- .getDescriptor().getExtensions().get(0).getNumber();
RawMessageSet raw =
- RawMessageSet.newBuilder()
- .addItem(
- RawMessageSet.Item.newBuilder()
- .setTypeId(TYPE_ID_1)
- .setMessage(
- TestMessageSetExtension1.newBuilder()
- .setI(123)
- .build().toByteString())
- .build())
- .build();
+ RawMessageSet.newBuilder()
+ .addItem(
+ RawMessageSet.Item.newBuilder()
+ .setTypeId(TYPE_ID_1)
+ .setMessage(
+ TestMessageSetExtension1.newBuilder().setI(123).build().toByteString())
+ .build())
+ .build();
ByteString data = raw.toByteString();
// Parse as a TestMessageSet and check the contents.
- TestMessageSet messageSet =
- TestMessageSet.parseFrom(data, extensionRegistry);
- assertEquals(123, messageSet.getExtension(
- TestMessageSetExtension1.messageSetExtension).getI());
+ TestMessageSet messageSet = TestMessageSet.parseFrom(data, extensionRegistry);
+ assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI());
}
public void testMergeLazyMessageSetExtensionEagerly() throws Exception {
@@ -444,38 +425,29 @@ public class WireFormatTest extends TestCase {
testMergeLazyMessageSetExtensionWithFlag(false);
}
- private void testMergeLazyMessageSetExtensionWithFlag(boolean eagerParsing)
- throws Exception {
+ private void testMergeLazyMessageSetExtensionWithFlag(boolean eagerParsing) throws Exception {
ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing);
ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
extensionRegistry.add(TestMessageSetExtension1.messageSetExtension);
// Set up a RawMessageSet with a known messages.
- int TYPE_ID_1 =
- TestMessageSetExtension1
- .getDescriptor().getExtensions().get(0).getNumber();
RawMessageSet raw =
- RawMessageSet.newBuilder()
- .addItem(
- RawMessageSet.Item.newBuilder()
- .setTypeId(TYPE_ID_1)
- .setMessage(
- TestMessageSetExtension1.newBuilder()
- .setI(123)
- .build().toByteString())
- .build())
- .build();
+ RawMessageSet.newBuilder()
+ .addItem(
+ RawMessageSet.Item.newBuilder()
+ .setTypeId(TYPE_ID_1)
+ .setMessage(
+ TestMessageSetExtension1.newBuilder().setI(123).build().toByteString())
+ .build())
+ .build();
ByteString data = raw.toByteString();
// Parse as a TestMessageSet and store value into lazy field
- TestMessageSet messageSet =
- TestMessageSet.parseFrom(data, extensionRegistry);
+ TestMessageSet messageSet = TestMessageSet.parseFrom(data, extensionRegistry);
// Merge lazy field check the contents.
- messageSet =
- messageSet.toBuilder().mergeFrom(data, extensionRegistry).build();
- assertEquals(123, messageSet.getExtension(
- TestMessageSetExtension1.messageSetExtension).getI());
+ messageSet = messageSet.toBuilder().mergeFrom(data, extensionRegistry).build();
+ assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI());
}
public void testMergeMessageSetExtensionEagerly() throws Exception {
@@ -486,31 +458,24 @@ public class WireFormatTest extends TestCase {
testMergeMessageSetExtensionWithFlag(false);
}
- private void testMergeMessageSetExtensionWithFlag(boolean eagerParsing)
- throws Exception {
+ private void testMergeMessageSetExtensionWithFlag(boolean eagerParsing) throws Exception {
ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing);
ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
extensionRegistry.add(TestMessageSetExtension1.messageSetExtension);
// Set up a RawMessageSet with a known messages.
- int TYPE_ID_1 =
- TestMessageSetExtension1
- .getDescriptor().getExtensions().get(0).getNumber();
RawMessageSet raw =
- RawMessageSet.newBuilder()
- .addItem(
- RawMessageSet.Item.newBuilder()
- .setTypeId(TYPE_ID_1)
- .setMessage(
- TestMessageSetExtension1.newBuilder()
- .setI(123)
- .build().toByteString())
- .build())
- .build();
+ RawMessageSet.newBuilder()
+ .addItem(
+ RawMessageSet.Item.newBuilder()
+ .setTypeId(TYPE_ID_1)
+ .setMessage(
+ TestMessageSetExtension1.newBuilder().setI(123).build().toByteString())
+ .build())
+ .build();
// Serialize RawMessageSet unnormally (message value before type id)
- ByteString.CodedBuilder out = ByteString.newCodedBuilder(
- raw.getSerializedSize());
+ ByteString.CodedBuilder out = ByteString.newCodedBuilder(raw.getSerializedSize());
CodedOutputStream output = out.getCodedOutput();
List<RawMessageSet.Item> items = raw.getItemList();
for (int i = 0; i < items.size(); i++) {
@@ -525,8 +490,7 @@ public class WireFormatTest extends TestCase {
// Merge bytes into TestMessageSet and check the contents.
TestMessageSet messageSet =
TestMessageSet.newBuilder().mergeFrom(data, extensionRegistry).build();
- assertEquals(123, messageSet.getExtension(
- TestMessageSetExtension1.messageSetExtension).getI());
+ assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI());
}
// ================================================================
@@ -544,8 +508,8 @@ public class WireFormatTest extends TestCase {
}
public void testOneofOnlyLastSet() throws Exception {
- TestOneofBackwardsCompatible source = TestOneofBackwardsCompatible
- .newBuilder().setFooInt(100).setFooString("101").build();
+ TestOneofBackwardsCompatible source =
+ TestOneofBackwardsCompatible.newBuilder().setFooInt(100).setFooString("101").build();
ByteString rawBytes = source.toByteString();
TestOneof2 message = TestOneof2.parseFrom(rawBytes);
diff --git a/java/util/src/main/java/com/google/protobuf/util/JsonFormat.java b/java/util/src/main/java/com/google/protobuf/util/JsonFormat.java
index 955dfd86..46deb5d1 100644
--- a/java/util/src/main/java/com/google/protobuf/util/JsonFormat.java
+++ b/java/util/src/main/java/com/google/protobuf/util/JsonFormat.java
@@ -1540,7 +1540,7 @@ public class JsonFormat {
Object key = parseFieldValue(keyField, new JsonPrimitive(entry.getKey()), entryBuilder);
Object value = parseFieldValue(valueField, entry.getValue(), entryBuilder);
if (value == null) {
- if(ignoringUnknownFields && valueField.getType() == Type.ENUM) {
+ if (ignoringUnknownFields && valueField.getType() == Type.ENUM) {
continue;
} else {
throw new InvalidProtocolBufferException("Map value cannot be null.");
@@ -1562,11 +1562,11 @@ public class JsonFormat {
for (int i = 0; i < array.size(); ++i) {
Object value = parseFieldValue(field, array.get(i), builder);
if (value == null) {
- if(ignoringUnknownFields && field.getType() == Type.ENUM) {
+ if (ignoringUnknownFields && field.getType() == Type.ENUM) {
continue;
} else {
throw new InvalidProtocolBufferException(
- "Repeated field elements cannot be null in field: " + field.getFullName());
+ "Repeated field elements cannot be null in field: " + field.getFullName());
}
}
builder.addRepeatedField(field, value);
diff --git a/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java b/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java
index 7637c267..64413bc1 100644
--- a/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java
+++ b/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java
@@ -161,7 +161,8 @@ public class JsonFormatTest extends TestCase {
JsonFormat.parser().merge(json, builder);
}
- private void mergeFromJsonIgnoringUnknownFields(String json, Message.Builder builder) throws IOException {
+ private void mergeFromJsonIgnoringUnknownFields(String json, Message.Builder builder)
+ throws IOException {
JsonFormat.parser().ignoringUnknownFields().merge(json, builder);
}
@@ -677,17 +678,14 @@ public class JsonFormatTest extends TestCase {
// Exception expected.
}
}
-
+
public void testMapEnumNullValueIsIgnored() throws Exception {
TestMap.Builder builder = TestMap.newBuilder();
mergeFromJsonIgnoringUnknownFields(
- "{\n"
- + " \"int32ToEnumMap\": {\"1\": null}\n"
- + "}",
- builder);
- TestMap map = builder.build();
- assertEquals(0, map.getInt32ToEnumMapMap().entrySet().size());
- }
+ "{\n" + " \"int32ToEnumMap\": {\"1\": null}\n" + "}", builder);
+ TestMap map = builder.build();
+ assertEquals(0, map.getInt32ToEnumMapMap().size());
+ }
public void testParserAcceptNonQuotedObjectKey() throws Exception {
TestMap.Builder builder = TestMap.newBuilder();
@@ -1188,40 +1186,36 @@ public class JsonFormatTest extends TestCase {
String json = "{\n" + " \"unknownField\": \"XXX\"\n" + "}";
JsonFormat.parser().ignoringUnknownFields().merge(json, builder);
}
-
+
public void testParserIgnoringUnknownEnums() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
String json = "{\n" + " \"optionalNestedEnum\": \"XXX\"\n" + "}";
JsonFormat.parser().ignoringUnknownFields().merge(json, builder);
assertEquals(0, builder.getOptionalNestedEnumValue());
}
-
+
public void testUnknownEnumMap() throws Exception {
TestMap.Builder builder = TestMap.newBuilder();
- JsonFormat.parser().ignoringUnknownFields().merge(
- "{\n"
- + " \"int32ToEnumMap\": {1: XXX, 2: FOO}"
- + "}",
- builder);
-
- assertEquals(NestedEnum.FOO, builder.getInt32ToEnumMapMap().get(2));
- assertEquals(1, builder.getInt32ToEnumMapMap().size());
+ JsonFormat.parser()
+ .ignoringUnknownFields()
+ .merge("{\n" + " \"int32ToEnumMap\": {1: XXX, 2: FOO}" + "}", builder);
+
+ assertEquals(NestedEnum.FOO, builder.getInt32ToEnumMapMap().get(2));
+ assertEquals(1, builder.getInt32ToEnumMapMap().size());
}
-
+
public void testRepeatedUnknownEnum() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
- JsonFormat.parser().ignoringUnknownFields().merge(
- "{\n"
- + " \"repeatedNestedEnum\": [XXX, FOO, BAR, BAZ]"
- + "}",
- builder);
-
+ JsonFormat.parser()
+ .ignoringUnknownFields()
+ .merge("{\n" + " \"repeatedNestedEnum\": [XXX, FOO, BAR, BAZ]" + "}", builder);
+
assertEquals(NestedEnum.FOO, builder.getRepeatedNestedEnum(0));
assertEquals(NestedEnum.BAR, builder.getRepeatedNestedEnum(1));
assertEquals(NestedEnum.BAZ, builder.getRepeatedNestedEnum(2));
assertEquals(3, builder.getRepeatedNestedEnumList().size());
}
-
+
public void testParserIntegerEnumValue() throws Exception {
TestAllTypes.Builder actualBuilder = TestAllTypes.newBuilder();
mergeFromJson("{\n" + " \"optionalNestedEnum\": 2\n" + "}", actualBuilder);