ADD: added new version of protobuf

This commit is contained in:
Henry Winkel
2022-12-20 10:09:28 +01:00
parent 4a79559129
commit 1e2b3dda7b
1513 changed files with 123720 additions and 83381 deletions

View File

@@ -209,7 +209,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeInt32List_Internal(int fieldNumber, List<Integer> list, boolean packed)
private final void writeInt32List_Internal(int fieldNumber, List<Integer> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT64_SIZE));
@@ -227,7 +227,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeInt32List_Internal(int fieldNumber, IntArrayList list, boolean packed)
private final void writeInt32List_Internal(int fieldNumber, IntArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT64_SIZE));
@@ -255,7 +255,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeFixed32List_Internal(int fieldNumber, List<Integer> list, boolean packed)
private final void writeFixed32List_Internal(int fieldNumber, List<Integer> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * FIXED32_SIZE));
@@ -273,7 +273,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeFixed32List_Internal(int fieldNumber, IntArrayList list, boolean packed)
private final void writeFixed32List_Internal(int fieldNumber, IntArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * FIXED32_SIZE));
@@ -307,7 +307,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeUInt64List_Internal(int fieldNumber, List<Long> list, boolean packed)
private final void writeUInt64List_Internal(int fieldNumber, List<Long> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT64_SIZE));
@@ -325,7 +325,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeUInt64List_Internal(int fieldNumber, LongArrayList list, boolean packed)
private final void writeUInt64List_Internal(int fieldNumber, LongArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT64_SIZE));
@@ -353,7 +353,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeFixed64List_Internal(int fieldNumber, List<Long> list, boolean packed)
private final void writeFixed64List_Internal(int fieldNumber, List<Long> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * FIXED64_SIZE));
@@ -371,7 +371,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeFixed64List_Internal(int fieldNumber, LongArrayList list, boolean packed)
private final void writeFixed64List_Internal(int fieldNumber, LongArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * FIXED64_SIZE));
@@ -399,7 +399,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeFloatList_Internal(int fieldNumber, List<Float> list, boolean packed)
private final void writeFloatList_Internal(int fieldNumber, List<Float> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * FIXED32_SIZE));
@@ -417,7 +417,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeFloatList_Internal(int fieldNumber, FloatArrayList list, boolean packed)
private final void writeFloatList_Internal(int fieldNumber, FloatArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * FIXED32_SIZE));
@@ -445,7 +445,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeDoubleList_Internal(int fieldNumber, List<Double> list, boolean packed)
private final void writeDoubleList_Internal(int fieldNumber, List<Double> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * FIXED64_SIZE));
@@ -463,7 +463,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeDoubleList_Internal(int fieldNumber, DoubleArrayList list, boolean packed)
private final void writeDoubleList_Internal(int fieldNumber, DoubleArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * FIXED64_SIZE));
@@ -497,7 +497,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeBoolList_Internal(int fieldNumber, List<Boolean> list, boolean packed)
private final void writeBoolList_Internal(int fieldNumber, List<Boolean> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + list.size());
@@ -515,7 +515,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeBoolList_Internal(int fieldNumber, BooleanArrayList list, boolean packed)
private final void writeBoolList_Internal(int fieldNumber, BooleanArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + list.size());
@@ -572,7 +572,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeUInt32List_Internal(int fieldNumber, List<Integer> list, boolean packed)
private final void writeUInt32List_Internal(int fieldNumber, List<Integer> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT32_SIZE));
@@ -590,7 +590,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeUInt32List_Internal(int fieldNumber, IntArrayList list, boolean packed)
private final void writeUInt32List_Internal(int fieldNumber, IntArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT32_SIZE));
@@ -630,7 +630,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeSInt32List_Internal(int fieldNumber, List<Integer> list, boolean packed)
private final void writeSInt32List_Internal(int fieldNumber, List<Integer> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT32_SIZE));
@@ -648,7 +648,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeSInt32List_Internal(int fieldNumber, IntArrayList list, boolean packed)
private final void writeSInt32List_Internal(int fieldNumber, IntArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT32_SIZE));
@@ -759,7 +759,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeSInt64List_Internal(int fieldNumber, List<Long> list, boolean packed)
private final void writeSInt64List_Internal(int fieldNumber, List<Long> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT64_SIZE));
@@ -777,7 +777,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
private void writeSInt64List_Internal(int fieldNumber, LongArrayList list, boolean packed)
private final void writeSInt64List_Internal(int fieldNumber, LongArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT64_SIZE));

View File

@@ -75,7 +75,6 @@ import java.util.NoSuchElementException;
*/
@CheckReturnValue
public abstract class ByteString implements Iterable<Byte>, Serializable {
private static final long serialVersionUID = 1L;
/**
* When two strings to be concatenated have a combined length shorter than this, we just copy
@@ -386,7 +385,8 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
// String -> ByteString
/**
* Returns a {@code ByteString} from a hexadecimal String.
* Returns a {@code ByteString} from a hexadecimal String. Alternative CharSequences should use
* {@link ByteStrings#decode(CharSequence, BaseEncoding)}
*
* @param hexString String of hexadecimal digits to create {@code ByteString} from.
* @throws NumberFormatException if the hexString does not contain a parsable hex String.
@@ -946,8 +946,6 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
/** Base class for leaf {@link ByteString}s (i.e. non-ropes). */
abstract static class LeafByteString extends ByteString {
private static final long serialVersionUID = 1L;
@Override
protected final int getTreeDepth() {
return 0;
@@ -1132,6 +1130,13 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
return ByteString.copyFrom(flushedBuffers);
}
/** 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));
return result;
}
/**
* Writes the complete contents of this byte array output stream to the specified output stream
* argument.
@@ -1146,7 +1151,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[0]);
cachedFlushBuffers = flushedBuffers.toArray(new ByteString[flushedBuffers.size()]);
cachedBuffer = buffer;
cachedBufferPos = bufferPos;
}
@@ -1154,7 +1159,7 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
byteString.writeTo(out);
}
out.write(Arrays.copyOf(cachedBuffer, cachedBufferPos));
out.write(copyArray(cachedBuffer, cachedBufferPos));
}
/**
@@ -1205,7 +1210,7 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
private void flushLastBuffer() {
if (bufferPos < buffer.length) {
if (bufferPos > 0) {
byte[] bufferCopy = Arrays.copyOf(buffer, bufferPos);
byte[] bufferCopy = copyArray(buffer, bufferPos);
flushedBuffers.add(new LiteralByteString(bufferCopy));
}
// We reuse this buffer for further writes.
@@ -1606,6 +1611,7 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
// Keep this class private to avoid deadlocks in classloading across threads as ByteString's
// static initializer loads LiteralByteString and another thread loads BoundedByteString.
private static final class BoundedByteString extends LiteralByteString {
private final int bytesOffset;
private final int bytesLength;

View File

@@ -31,6 +31,7 @@
package com.google.protobuf;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.CLASS;
import java.lang.annotation.Documented;
@@ -44,6 +45,6 @@ import java.lang.annotation.Target;
* annotated with {@code @CheckReturnValue} to exempt specific methods from the default.
*/
@Documented
@Target(METHOD) // TODO(kak): consider adding CONSTRUCTOR later if necessary
@Target({METHOD, TYPE})
@Retention(CLASS)
@interface CanIgnoreReturnValue {}

View File

@@ -41,13 +41,13 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Indicates that the return value of the annotated method must be used. An error is triggered when
* one of these methods is called but the result is not used.
* Indicates that the return value of the annotated method must be checked. An error is triggered
* when one of these methods is called but the result is not used.
*
* <p>{@code @CheckReturnValue} may be applied to a class or package to indicate that all methods in
* that class (including indirectly; that is, methods of inner classes within the annotated class)
* or package must have their return values used. For convenience, we provide an annotation, {@link
* CanIgnoreReturnValue}, to exempt specific methods or classes from this behavior.
* that class or package must have their return values checked. For convenience, we provide an
* annotation, {@link CanIgnoreReturnValue}, to exempt specific methods or classes from this
* behavior.
*/
@Documented
@Target({METHOD, CONSTRUCTOR, TYPE, PACKAGE})

View File

@@ -78,7 +78,6 @@ import java.util.logging.Logger;
*
* @author kenton@google.com Kenton Varda
*/
@CheckReturnValue
public final class Descriptors {
private static final Logger logger = Logger.getLogger(Descriptors.class.getName());
private static final int[] EMPTY_INT_ARRAY = new int[0];
@@ -462,20 +461,21 @@ public final class Descriptors {
}
/**
* This method is to be called by generated code only. It updates the
* 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(
FileDescriptor descriptor, ExtensionRegistry registry) {
final FileDescriptor descriptor, final ExtensionRegistry registry) {
ByteString bytes = descriptor.proto.toByteString();
FileDescriptorProto proto;
try {
FileDescriptorProto proto = FileDescriptorProto.parseFrom(bytes, registry);
descriptor.setProto(proto);
proto = FileDescriptorProto.parseFrom(bytes, registry);
} catch (InvalidProtocolBufferException e) {
throw new IllegalArgumentException(
"Failed to parse protocol buffer descriptor for generated code.", e);
}
descriptor.setProto(proto);
}
/**
@@ -1788,27 +1788,6 @@ public final class Descriptors {
return Collections.unmodifiableList(Arrays.asList(values));
}
/** Determines if the given field number is reserved. */
public boolean isReservedNumber(final int number) {
for (final EnumDescriptorProto.EnumReservedRange range : proto.getReservedRangeList()) {
if (range.getStart() <= number && number <= range.getEnd()) {
return true;
}
}
return false;
}
/** Determines if the given field name is reserved. */
public boolean isReservedName(final String name) {
checkNotNull(name);
for (final String reservedName : proto.getReservedNameList()) {
if (reservedName.equals(name)) {
return true;
}
}
return false;
}
/**
* Find an enum value by name.
*

View File

@@ -123,15 +123,16 @@ public class ExtensionRegistryLite {
* ExtensionRegistry} (if the full (non-Lite) proto libraries are available).
*/
public static ExtensionRegistryLite getEmptyRegistry() {
if (!doFullRuntimeInheritanceCheck) {
return EMPTY_REGISTRY_LITE;
}
ExtensionRegistryLite result = emptyRegistry;
if (result == null) {
synchronized (ExtensionRegistryLite.class) {
result = emptyRegistry;
if (result == null) {
result = emptyRegistry = ExtensionRegistryFactory.createEmpty();
result =
emptyRegistry =
doFullRuntimeInheritanceCheck
? ExtensionRegistryFactory.createEmpty()
: EMPTY_REGISTRY_LITE;
}
}
}

View File

@@ -728,10 +728,6 @@ final class FieldSet<T extends FieldSet.FieldDescriptorLite<T>> {
if (descriptor.isRepeated()) {
final List<?> valueList = (List<?>) value;
if (descriptor.isPacked()) {
if (valueList.isEmpty()) {
// The tag should not be written for empty packed fields.
return;
}
output.writeTag(number, WireFormat.WIRETYPE_LENGTH_DELIMITED);
// Compute the total data size so the length can be written.
int dataSize = 0;
@@ -897,13 +893,9 @@ final class FieldSet<T extends FieldSet.FieldDescriptorLite<T>> {
WireFormat.FieldType type = descriptor.getLiteType();
int number = descriptor.getNumber();
if (descriptor.isRepeated()) {
List<?> valueList = (List<?>) value;
if (descriptor.isPacked()) {
if (valueList.isEmpty()) {
return 0;
}
int dataSize = 0;
for (final Object element : valueList) {
for (final Object element : (List<?>) value) {
dataSize += computeElementSizeNoTag(type, element);
}
return dataSize
@@ -911,7 +903,7 @@ final class FieldSet<T extends FieldSet.FieldDescriptorLite<T>> {
+ CodedOutputStream.computeUInt32SizeNoTag(dataSize);
} else {
int size = 0;
for (final Object element : valueList) {
for (final Object element : (List<?>) value) {
size += computeElementSize(type, number, element);
}
return size;

View File

@@ -188,7 +188,7 @@ public abstract class GeneratedMessageLite<
// any unnecessary intermediary allocations while reducing the generated code size.
/** Lazily initializes unknown fields. */
private void ensureUnknownFieldsInitialized() {
private final void ensureUnknownFieldsInitialized() {
if (unknownFields == UnknownFieldSetLite.getDefaultInstance()) {
unknownFields = UnknownFieldSetLite.newInstance();
}
@@ -295,16 +295,11 @@ public abstract class GeneratedMessageLite<
*
* <p>For use by generated code only.
*/
protected abstract Object dynamicMethod(
MethodToInvoke method,
Object arg0,
Object arg1);
protected abstract Object dynamicMethod(MethodToInvoke method, Object arg0, Object arg1);
/** Same as {@link #dynamicMethod(MethodToInvoke, Object, Object)} with {@code null} padding. */
@CanIgnoreReturnValue
protected Object dynamicMethod(
MethodToInvoke method,
Object arg0) {
protected Object dynamicMethod(MethodToInvoke method, Object arg0) {
return dynamicMethod(method, arg0, null);
}
@@ -1355,11 +1350,11 @@ public abstract class GeneratedMessageLite<
}
@SuppressWarnings("unchecked")
Object fromFieldSetType(Object value) {
Object fromFieldSetType(final Object value) {
if (descriptor.isRepeated()) {
if (descriptor.getLiteJavaType() == WireFormat.JavaType.ENUM) {
List<Object> result = new ArrayList<>();
for (Object element : (List) value) {
final List result = new ArrayList<>();
for (final Object element : (List) value) {
result.add(singularFromFieldSetType(element));
}
return result;
@@ -1371,7 +1366,7 @@ public abstract class GeneratedMessageLite<
}
}
Object singularFromFieldSetType(Object value) {
Object singularFromFieldSetType(final Object value) {
if (descriptor.getLiteJavaType() == WireFormat.JavaType.ENUM) {
return descriptor.enumTypeMap.findValueByNumber((Integer) value);
} else {
@@ -1379,11 +1374,12 @@ public abstract class GeneratedMessageLite<
}
}
Object toFieldSetType(Object value) {
@SuppressWarnings("unchecked")
Object toFieldSetType(final Object value) {
if (descriptor.isRepeated()) {
if (descriptor.getLiteJavaType() == WireFormat.JavaType.ENUM) {
List<Object> result = new ArrayList<>();
for (Object element : (List) value) {
final List result = new ArrayList<>();
for (final Object element : (List) value) {
result.add(singularToFieldSetType(element));
}
return result;
@@ -1395,7 +1391,7 @@ public abstract class GeneratedMessageLite<
}
}
Object singularToFieldSetType(Object value) {
Object singularToFieldSetType(final Object value) {
if (descriptor.getLiteJavaType() == WireFormat.JavaType.ENUM) {
return ((Internal.EnumLite) value).getNumber();
} else {

View File

@@ -600,7 +600,6 @@ public final class Internal {
void addInt(int element);
/** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */
@CanIgnoreReturnValue
int setInt(int index, int element);
/** Returns a mutable clone of this list with the specified capacity. */
@@ -621,7 +620,6 @@ public final class Internal {
void addBoolean(boolean element);
/** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */
@CanIgnoreReturnValue
boolean setBoolean(int index, boolean element);
/** Returns a mutable clone of this list with the specified capacity. */
@@ -642,7 +640,6 @@ public final class Internal {
void addLong(long element);
/** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */
@CanIgnoreReturnValue
long setLong(int index, long element);
/** Returns a mutable clone of this list with the specified capacity. */
@@ -663,7 +660,6 @@ public final class Internal {
void addDouble(double element);
/** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */
@CanIgnoreReturnValue
double setDouble(int index, double element);
/** Returns a mutable clone of this list with the specified capacity. */
@@ -684,7 +680,6 @@ public final class Internal {
void addFloat(float element);
/** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */
@CanIgnoreReturnValue
float setFloat(int index, float element);
/** Returns a mutable clone of this list with the specified capacity. */

View File

@@ -39,12 +39,11 @@ import java.util.Map;
*
* <p>See also {@link MessageLite}, which defines most of the methods that typical users care about.
* {@link Message} adds methods that are not available in the "lite" runtime. The biggest added
* features are introspection and reflection; that is, getting descriptors for the message type and
* accessing the field values dynamically.
* features are introspection and reflection; that is, getting descriptors for the message type
* and accessing the field values dynamically.
*
* @author kenton@google.com Kenton Varda
*/
@CheckReturnValue
public interface Message extends MessageLite, MessageOrBuilder {
// (From MessageLite, re-declared here only for return type covariance.)
@@ -103,7 +102,6 @@ public interface Message extends MessageLite, MessageOrBuilder {
// (From MessageLite.Builder, re-declared here only for return type
// covariance.)
@Override
@CanIgnoreReturnValue
Builder clear();
/**
@@ -123,7 +121,6 @@ public interface Message extends MessageLite, MessageOrBuilder {
*
* <p>This is equivalent to the {@code Message::MergeFrom} method in C++.
*/
@CanIgnoreReturnValue
Builder mergeFrom(Message other);
// (From MessageLite.Builder, re-declared here only for return type
@@ -138,11 +135,9 @@ public interface Message extends MessageLite, MessageOrBuilder {
Builder clone();
@Override
@CanIgnoreReturnValue
Builder mergeFrom(CodedInputStream input) throws IOException;
@Override
@CanIgnoreReturnValue
Builder mergeFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry)
throws IOException;
@@ -195,21 +190,18 @@ public interface Message extends MessageLite, MessageOrBuilder {
* Sets a field to the given value. The value must be of the correct type for this field, that
* is, the same type that {@link Message#getField(Descriptors.FieldDescriptor)} returns.
*/
@CanIgnoreReturnValue
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.
*/
@CanIgnoreReturnValue
Builder clearField(Descriptors.FieldDescriptor field);
/**
* Clears the oneof. This is exactly equivalent to calling the generated "clear" accessor method
* corresponding to the oneof.
*/
@CanIgnoreReturnValue
Builder clearOneof(Descriptors.OneofDescriptor oneof);
/**
@@ -220,7 +212,6 @@ public interface Message extends MessageLite, MessageOrBuilder {
* @throws IllegalArgumentException if the field is not a repeated field, or {@code
* field.getContainingType() != getDescriptorForType()}.
*/
@CanIgnoreReturnValue
Builder setRepeatedField(Descriptors.FieldDescriptor field, int index, Object value);
/**
@@ -229,15 +220,12 @@ public interface Message extends MessageLite, MessageOrBuilder {
* @throws IllegalArgumentException if the field is not a repeated field, or {@code
* field.getContainingType() != getDescriptorForType()}
*/
@CanIgnoreReturnValue
Builder addRepeatedField(Descriptors.FieldDescriptor field, Object value);
/** Set the {@link UnknownFieldSet} for this message. */
@CanIgnoreReturnValue
Builder setUnknownFields(UnknownFieldSet unknownFields);
/** Merge some unknown fields into the {@link UnknownFieldSet} for this message. */
@CanIgnoreReturnValue
Builder mergeUnknownFields(UnknownFieldSet unknownFields);
// ---------------------------------------------------------------
@@ -246,38 +234,30 @@ public interface Message extends MessageLite, MessageOrBuilder {
// (From MessageLite.Builder, re-declared here only for return type
// covariance.)
@Override
@CanIgnoreReturnValue
Builder mergeFrom(ByteString data) throws InvalidProtocolBufferException;
@Override
@CanIgnoreReturnValue
Builder mergeFrom(ByteString data, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
@Override
@CanIgnoreReturnValue
Builder mergeFrom(byte[] data) throws InvalidProtocolBufferException;
@Override
@CanIgnoreReturnValue
Builder mergeFrom(byte[] data, int off, int len) throws InvalidProtocolBufferException;
@Override
@CanIgnoreReturnValue
Builder mergeFrom(byte[] data, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
@Override
@CanIgnoreReturnValue
Builder mergeFrom(byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
@Override
@CanIgnoreReturnValue
Builder mergeFrom(InputStream input) throws IOException;
@Override
@CanIgnoreReturnValue
Builder mergeFrom(InputStream input, ExtensionRegistryLite extensionRegistry)
throws IOException;

View File

@@ -59,7 +59,6 @@ import java.io.OutputStream;
*
* @author kenton@google.com Kenton Varda
*/
@CheckReturnValue
public interface MessageLite extends MessageLiteOrBuilder {
/**
@@ -139,7 +138,6 @@ public interface MessageLite extends MessageLiteOrBuilder {
/** Abstract interface implemented by Protocol Message builders. */
interface Builder extends MessageLiteOrBuilder, Cloneable {
/** Resets all fields to their default values. */
@CanIgnoreReturnValue
Builder clear();
/**
@@ -183,12 +181,11 @@ public interface MessageLite extends MessageLiteOrBuilder {
* <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.
*
* @throws InvalidProtocolBufferException the bytes read are not syntactically correct according
* to the protobuf wire format specification. The data is corrupt, incomplete, or was never
* a protobuf in the first place.
* @throws InvalidProtocolBufferException the bytes read are not syntactically correct
* according to the protobuf wire format specification. The data is corrupt, incomplete,
* or was never a protobuf in the first place.
* @throws IOException an I/O error reading from the stream
*/
@CanIgnoreReturnValue
Builder mergeFrom(CodedInputStream input) throws IOException;
/**
@@ -196,12 +193,11 @@ public interface MessageLite extends MessageLiteOrBuilder {
* 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.
*
* @throws InvalidProtocolBufferException the bytes read are not syntactically correct according
* to the protobuf wire format specification. The data is corrupt, incomplete, or was never
* a protobuf in the first place.
* @throws InvalidProtocolBufferException the bytes read are not syntactically correct
* according to the protobuf wire format specification. The data is corrupt, incomplete,
* or was never a protobuf in the first place.
* @throws IOException an I/O error reading from the stream
*/
@CanIgnoreReturnValue
Builder mergeFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry)
throws IOException;
@@ -213,11 +209,10 @@ public interface MessageLite extends MessageLiteOrBuilder {
* is just a small wrapper around {@link #mergeFrom(CodedInputStream)}.
*
* @throws InvalidProtocolBufferException the bytes in data are not syntactically correct
* according to the protobuf wire format specification. The data is corrupt, incomplete, or
* was never a protobuf in the first place.
* according to the protobuf wire format specification. The data is corrupt, incomplete,
* or was never a protobuf in the first place.
* @return this
*/
@CanIgnoreReturnValue
Builder mergeFrom(ByteString data) throws InvalidProtocolBufferException;
/**
@@ -225,11 +220,10 @@ public interface MessageLite extends MessageLiteOrBuilder {
* is just a small wrapper around {@link #mergeFrom(CodedInputStream,ExtensionRegistryLite)}.
*
* @throws InvalidProtocolBufferException the bytes in data are not syntactically correct
* according to the protobuf wire format specification. The data is corrupt, incomplete, or
* was never a protobuf in the first place.
* according to the protobuf wire format specification. The data is corrupt, incomplete,
* or was never a protobuf in the first place.
* @return this
*/
@CanIgnoreReturnValue
Builder mergeFrom(ByteString data, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
@@ -238,11 +232,10 @@ public interface MessageLite extends MessageLiteOrBuilder {
* is just a small wrapper around {@link #mergeFrom(CodedInputStream)}.
*
* @throws InvalidProtocolBufferException the bytes in data are not syntactically correct
* according to the protobuf wire format specification. The data is corrupt, incomplete, or
* was never a protobuf in the first place.
* according to the protobuf wire format specification. The data is corrupt, incomplete,
* or was never a protobuf in the first place.
* @return this
*/
@CanIgnoreReturnValue
Builder mergeFrom(byte[] data) throws InvalidProtocolBufferException;
/**
@@ -250,11 +243,10 @@ public interface MessageLite extends MessageLiteOrBuilder {
* is just a small wrapper around {@link #mergeFrom(CodedInputStream)}.
*
* @throws InvalidProtocolBufferException the bytes in data are not syntactically correct
* according to the protobuf wire format specification. The data is corrupt, incomplete, or
* was never a protobuf in the first place.
* according to the protobuf wire format specification. The data is corrupt, incomplete,
* or was never a protobuf in the first place.
* @return this
*/
@CanIgnoreReturnValue
Builder mergeFrom(byte[] data, int off, int len) throws InvalidProtocolBufferException;
/**
@@ -262,11 +254,10 @@ public interface MessageLite extends MessageLiteOrBuilder {
* is just a small wrapper around {@link #mergeFrom(CodedInputStream,ExtensionRegistryLite)}.
*
* @throws InvalidProtocolBufferException the bytes in data are not syntactically correct
* according to the protobuf wire format specification. The data is corrupt, incomplete, or
* was never a protobuf in the first place.
* according to the protobuf wire format specification. The data is corrupt, incomplete,
* or was never a protobuf in the first place.
* @return this
*/
@CanIgnoreReturnValue
Builder mergeFrom(byte[] data, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
@@ -275,11 +266,10 @@ public interface MessageLite extends MessageLiteOrBuilder {
* is just a small wrapper around {@link #mergeFrom(CodedInputStream,ExtensionRegistryLite)}.
*
* @throws InvalidProtocolBufferException the bytes in data are not syntactically correct
* according to the protobuf wire format specification. The data is corrupt, incomplete, or
* was never a protobuf in the first place.
* according to the protobuf wire format specification. The data is corrupt, incomplete,
* or was never a protobuf in the first place.
* @return this
*/
@CanIgnoreReturnValue
Builder mergeFrom(byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
@@ -293,13 +283,12 @@ public interface MessageLite extends MessageLiteOrBuilder {
*
* <p>Despite usually reading the entire input, this does not close the stream.
*
* @throws InvalidProtocolBufferException the bytes read are not syntactically correct according
* to the protobuf wire format specification. The data is corrupt, incomplete, or was never
* a protobuf in the first place.
* @throws InvalidProtocolBufferException the bytes read are not syntactically correct
* according to the protobuf wire format specification. The data is corrupt, incomplete,
* or was never a protobuf in the first place.
* @throws IOException an I/O error reading from the stream
* @return this
*/
@CanIgnoreReturnValue
Builder mergeFrom(InputStream input) throws IOException;
/**
@@ -309,7 +298,6 @@ public interface MessageLite extends MessageLiteOrBuilder {
*
* @return this
*/
@CanIgnoreReturnValue
Builder mergeFrom(InputStream input, ExtensionRegistryLite extensionRegistry)
throws IOException;
@@ -329,7 +317,6 @@ public interface MessageLite extends MessageLiteOrBuilder {
*
* <p>This is equivalent to the {@code Message::MergeFrom} method in C++.
*/
@CanIgnoreReturnValue
Builder mergeFrom(MessageLite other);
/**
@@ -339,9 +326,9 @@ public interface MessageLite extends MessageLiteOrBuilder {
*
* @return true if successful, or false if the stream is at EOF when the method starts. Any
* other error (including reaching EOF during parsing) causes an exception to be thrown.
* @throws InvalidProtocolBufferException the bytes read are not syntactically correct according
* to the protobuf wire format specification. The data is corrupt, incomplete, or was never
* a protobuf in the first place.
* @throws InvalidProtocolBufferException the bytes read are not syntactically correct
* according to the protobuf wire format specification. The data is corrupt, incomplete,
* or was never a protobuf in the first place.
* @throws IOException an I/O error reading from the stream
*/
boolean mergeDelimitedFrom(InputStream input) throws IOException;
@@ -351,9 +338,9 @@ public interface MessageLite extends MessageLiteOrBuilder {
*
* @return true if successful, or false if the stream is at EOF when the method starts. Any
* other error (including reaching EOF during parsing) causes an exception to be thrown.
* @throws InvalidProtocolBufferException the bytes read are not syntactically correct according
* to the protobuf wire format specification. The data is corrupt, incomplete, or was never
* a protobuf in the first place.
* @throws InvalidProtocolBufferException the bytes read are not syntactically correct
* according to the protobuf wire format specification. The data is corrupt, incomplete,
* or was never a protobuf in the first place.
* @throws IOException an I/O error reading from the stream
*/
boolean mergeDelimitedFrom(InputStream input, ExtensionRegistryLite extensionRegistry)

View File

@@ -36,7 +36,6 @@ package com.google.protobuf;
*
* @author jonp@google.com (Jon Perlow)
*/
@CheckReturnValue
public interface MessageLiteOrBuilder {
/**
* Get an instance of the type with no fields set. Because no fields are set, all getters for

View File

@@ -39,7 +39,6 @@ import java.util.Map;
*
* @author jonp@google.com (Jon Perlow)
*/
@CheckReturnValue
public interface MessageOrBuilder extends MessageLiteOrBuilder {
// (From MessageLite, re-declared here only for return type covariance.)

View File

@@ -277,7 +277,6 @@ public class RepeatedFieldBuilder<
* @param message the message to set
* @return the builder
*/
@CanIgnoreReturnValue
public RepeatedFieldBuilder<MType, BType, IType> setMessage(int index, MType message) {
checkNotNull(message);
ensureMutableMessageList();
@@ -299,7 +298,6 @@ public class RepeatedFieldBuilder<
* @param message the message to add
* @return the builder
*/
@CanIgnoreReturnValue
public RepeatedFieldBuilder<MType, BType, IType> addMessage(MType message) {
checkNotNull(message);
ensureMutableMessageList();
@@ -321,7 +319,6 @@ public class RepeatedFieldBuilder<
* @param message the message to add
* @return the builder
*/
@CanIgnoreReturnValue
public RepeatedFieldBuilder<MType, BType, IType> addMessage(int index, MType message) {
checkNotNull(message);
ensureMutableMessageList();
@@ -341,7 +338,6 @@ public class RepeatedFieldBuilder<
* @param values the messages to add
* @return the builder
*/
@CanIgnoreReturnValue
public RepeatedFieldBuilder<MType, BType, IType> addAllMessages(
Iterable<? extends MType> values) {
for (final MType value : values) {

View File

@@ -277,7 +277,6 @@ public class RepeatedFieldBuilderV3<
* @param message the message to set
* @return the builder
*/
@CanIgnoreReturnValue
public RepeatedFieldBuilderV3<MType, BType, IType> setMessage(int index, MType message) {
checkNotNull(message);
ensureMutableMessageList();
@@ -299,7 +298,6 @@ public class RepeatedFieldBuilderV3<
* @param message the message to add
* @return the builder
*/
@CanIgnoreReturnValue
public RepeatedFieldBuilderV3<MType, BType, IType> addMessage(MType message) {
checkNotNull(message);
ensureMutableMessageList();
@@ -321,7 +319,6 @@ public class RepeatedFieldBuilderV3<
* @param message the message to add
* @return the builder
*/
@CanIgnoreReturnValue
public RepeatedFieldBuilderV3<MType, BType, IType> addMessage(int index, MType message) {
checkNotNull(message);
ensureMutableMessageList();
@@ -341,7 +338,6 @@ public class RepeatedFieldBuilderV3<
* @param values the messages to add
* @return the builder
*/
@CanIgnoreReturnValue
public RepeatedFieldBuilderV3<MType, BType, IType> addAllMessages(
Iterable<? extends MType> values) {
for (final MType value : values) {

View File

@@ -156,7 +156,6 @@ public class SingleFieldBuilder<
* @param message the message to set
* @return the builder
*/
@CanIgnoreReturnValue
public SingleFieldBuilder<MType, BType, IType> setMessage(MType message) {
this.message = checkNotNull(message);
if (builder != null) {
@@ -173,7 +172,6 @@ public class SingleFieldBuilder<
* @param value the value to merge from
* @return the builder
*/
@CanIgnoreReturnValue
public SingleFieldBuilder<MType, BType, IType> mergeFrom(MType value) {
if (builder == null && message == message.getDefaultInstanceForType()) {
message = value;
@@ -190,7 +188,6 @@ public class SingleFieldBuilder<
* @return the builder
*/
@SuppressWarnings("unchecked")
@CanIgnoreReturnValue
public SingleFieldBuilder<MType, BType, IType> clear() {
message =
(MType)

View File

@@ -156,7 +156,6 @@ public class SingleFieldBuilderV3<
* @param message the message to set
* @return the builder
*/
@CanIgnoreReturnValue
public SingleFieldBuilderV3<MType, BType, IType> setMessage(MType message) {
this.message = checkNotNull(message);
if (builder != null) {
@@ -173,7 +172,6 @@ public class SingleFieldBuilderV3<
* @param value the value to merge from
* @return the builder
*/
@CanIgnoreReturnValue
public SingleFieldBuilderV3<MType, BType, IType> mergeFrom(MType value) {
if (builder == null && message == message.getDefaultInstanceForType()) {
message = value;
@@ -190,7 +188,6 @@ public class SingleFieldBuilderV3<
* @return the builder
*/
@SuppressWarnings("unchecked")
@CanIgnoreReturnValue
public SingleFieldBuilderV3<MType, BType, IType> clear() {
message =
(MType)
@@ -202,6 +199,9 @@ public class SingleFieldBuilderV3<
builder = null;
}
onChanged();
// After clearing, parent is dirty, but this field builder is now clean and any changes should
// trickle up.
isClean = true;
return this;
}

View File

@@ -61,6 +61,7 @@ public final class TextFormat {
private static final String DEBUG_STRING_SILENT_MARKER = "\t ";
/**
* 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
@@ -115,8 +116,8 @@ public final class TextFormat {
/**
* Generates a human readable form of this message, useful for debugging and other purposes, with
* no newline characters. This is just a trivial wrapper around {@link
* TextFormat.Printer#shortDebugString(MessageOrBuilder)}.
* no newline characters. This is just a trivial wrapper around
* {@link TextFormat.Printer#shortDebugString(MessageOrBuilder)}.
*/
public static String shortDebugString(final MessageOrBuilder message) {
return printer().shortDebugString(message);
@@ -458,7 +459,9 @@ public final class TextFormat {
}
}
/** An adapter class that can take a {@link MapEntry} and returns its key and entry. */
/**
* An adapter class that can take a {@link MapEntry} and returns its key and entry.
*/
private static class MapEntryAdapter implements Comparable<MapEntryAdapter> {
private Object entry;
@@ -738,9 +741,9 @@ public final class TextFormat {
// Groups must be serialized with their original capitalization.
generator.print(field.getMessageType().getName());
} else {
generator.print(field.getName());
generator.print(field.getName());
}
}
}
if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
generator.print(" {");
@@ -950,7 +953,6 @@ public final class TextFormat {
* the next token is parsed.
*/
private boolean containsSilentMarkerAfterCurrentToken = false;
private boolean containsSilentMarkerAfterPrevToken = false;
/** Construct a tokenizer that parses tokens from the given text. */
@@ -1376,6 +1378,7 @@ public final class TextFormat {
private ParseException floatParseException(final NumberFormatException e) {
return parseException("Couldn't parse number: " + e.getMessage());
}
}
/** Thrown when parsing an invalid text format message. */
@@ -1548,7 +1551,7 @@ public final class TextFormat {
* the current token is part of the field value, so the silent marker is indicated by
* containsSilentMarkerAfterPrevToken.
*/
private void detectSilentMarker(Tokenizer tokenizer, String fieldName) {
private void detectSilentMarker(Tokenizer tokenizer) {
}
/**
@@ -1625,8 +1628,8 @@ public final class TextFormat {
* unknown field is encountered. If this is set, the parser will only log a warning. Allow
* unknown fields will also allow unknown extensions.
*
* <p>Use of this parameter is discouraged which may hide some errors (e.g. spelling error on
* field name).
* <p>Use of this parameter is discouraged which may hide some errors (e.g.
* spelling error on field name).
*/
public Builder setAllowUnknownFields(boolean allowUnknownFields) {
this.allowUnknownFields = allowUnknownFields;
@@ -1634,9 +1637,10 @@ public final class TextFormat {
}
/**
* Set whether this parser will allow unknown extensions. By default, an exception is thrown
* if unknown extension is encountered. If this is set true, the parser will only log a
* warning. Allow unknown extensions does not mean allow normal unknown fields.
* Set whether this parser will allow unknown extensions. By default, an
* exception is thrown if unknown extension is encountered. If this is set true,
* the parser will only log a warning. Allow unknown extensions does not mean
* allow normal unknown fields.
*/
public Builder setAllowUnknownExtensions(boolean allowUnknownExtensions) {
this.allowUnknownExtensions = allowUnknownExtensions;
@@ -1721,8 +1725,7 @@ public final class TextFormat {
static final class UnknownField {
static enum Type {
FIELD,
EXTENSION;
FIELD, EXTENSION;
}
final String message;
@@ -1783,6 +1786,7 @@ public final class TextFormat {
throws ParseException {
final Tokenizer tokenizer = new Tokenizer(input);
MessageReflection.BuilderAdapter target = new MessageReflection.BuilderAdapter(builder);
List<UnknownField> unknownFields = new ArrayList<UnknownField>();
while (!tokenizer.atEnd()) {
@@ -1799,7 +1803,12 @@ public final class TextFormat {
final MessageReflection.MergeTarget target,
List<UnknownField> unknownFields)
throws ParseException {
mergeField(tokenizer, extensionRegistry, target, parseInfoTreeBuilder, unknownFields);
mergeField(
tokenizer,
extensionRegistry,
target,
parseInfoTreeBuilder,
unknownFields);
}
/** Parse a single field from {@code tokenizer} and merge it into {@code target}. */
@@ -1811,40 +1820,38 @@ public final class TextFormat {
List<UnknownField> unknownFields)
throws ParseException {
FieldDescriptor field = null;
String name;
int startLine = tokenizer.getLine();
int startColumn = tokenizer.getColumn();
final Descriptor type = target.getDescriptorForType();
ExtensionRegistry.ExtensionInfo extension = null;
if ("google.protobuf.Any".equals(type.getFullName()) && tokenizer.tryConsume("[")) {
mergeAnyFieldValue(
tokenizer, extensionRegistry, target, parseTreeBuilder, unknownFields, type);
mergeAnyFieldValue(tokenizer, extensionRegistry, target, parseTreeBuilder, unknownFields,
type);
return;
}
if (tokenizer.tryConsume("[")) {
// An extension.
StringBuilder nameBuilder = new StringBuilder(tokenizer.consumeIdentifier());
final StringBuilder name = new StringBuilder(tokenizer.consumeIdentifier());
while (tokenizer.tryConsume(".")) {
nameBuilder.append('.');
nameBuilder.append(tokenizer.consumeIdentifier());
name.append('.');
name.append(tokenizer.consumeIdentifier());
}
name = nameBuilder.toString();
extension = target.findExtensionByName(extensionRegistry, name);
extension = target.findExtensionByName(extensionRegistry, name.toString());
if (extension == null) {
String message =
(tokenizer.getPreviousLine() + 1)
+ ":"
+ (tokenizer.getPreviousColumn() + 1)
+ ":\t"
+ type.getFullName()
+ ".["
+ name
+ "]";
unknownFields.add(new UnknownField(message, UnknownField.Type.EXTENSION));
String message =
(tokenizer.getPreviousLine() + 1)
+ ":"
+ (tokenizer.getPreviousColumn() + 1)
+ ":\t"
+ type.getFullName()
+ ".["
+ name
+ "]";
unknownFields.add(new UnknownField(message, UnknownField.Type.EXTENSION));
} else {
if (extension.descriptor.getContainingType() != type) {
throw tokenizer.parseExceptionPreviousToken(
@@ -1859,7 +1866,7 @@ public final class TextFormat {
tokenizer.consume("]");
} else {
name = tokenizer.consumeIdentifier();
final String name = tokenizer.consumeIdentifier();
field = type.findFieldByName(name);
// Group names are expected to be capitalized as they appear in the
@@ -1883,14 +1890,13 @@ public final class TextFormat {
}
if (field == null) {
String message =
(tokenizer.getPreviousLine() + 1)
+ ":"
+ (tokenizer.getPreviousColumn() + 1)
+ ":\t"
+ type.getFullName()
+ "."
+ name;
String message = (tokenizer.getPreviousLine() + 1)
+ ":"
+ (tokenizer.getPreviousColumn() + 1)
+ ":\t"
+ type.getFullName()
+ "."
+ name;
unknownFields.add(new UnknownField(message, UnknownField.Type.FIELD));
}
}
@@ -1903,7 +1909,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.
detectSilentMarker(tokenizer, name);
detectSilentMarker(tokenizer);
if (tokenizer.tryConsume(":") && !tokenizer.lookingAt("{") && !tokenizer.lookingAt("<")) {
skipFieldValue(tokenizer);
} else {
@@ -1914,7 +1920,7 @@ public final class TextFormat {
// Handle potential ':'.
if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
detectSilentMarker(tokenizer, field.getFullName());
detectSilentMarker(tokenizer);
tokenizer.tryConsume(":"); // optional
if (parseTreeBuilder != null) {
TextFormatParseInfoTree.Builder childParseTreeBuilder =
@@ -1938,7 +1944,7 @@ public final class TextFormat {
unknownFields);
}
} else {
detectSilentMarker(tokenizer, field.getFullName());
detectSilentMarker(tokenizer);
tokenizer.consume(":"); // required
consumeFieldValues(
tokenizer,
@@ -1961,29 +1967,6 @@ public final class TextFormat {
}
}
private String consumeFullTypeName(Tokenizer tokenizer) throws ParseException {
// If there is not a leading `[`, this is just a type name.
if (!tokenizer.tryConsume("[")) {
return tokenizer.consumeIdentifier();
}
// Otherwise, this is an extension or google.protobuf.Any type URL: we consume proto path
// elements until we've addressed the type.
String name = tokenizer.consumeIdentifier();
while (tokenizer.tryConsume(".")) {
name += "." + tokenizer.consumeIdentifier();
}
if (tokenizer.tryConsume("/")) {
name += "/" + tokenizer.consumeIdentifier();
while (tokenizer.tryConsume(".")) {
name += "." + tokenizer.consumeIdentifier();
}
}
tokenizer.consume("]");
return name;
}
/**
* Parse a one or more field values from {@code tokenizer} and merge it into {@code builder}.
*/
@@ -2075,13 +2058,8 @@ public final class TextFormat {
// (java_proto_library for any_java_proto depends on the protobuf_impl).
Message anyBuilder = DynamicMessage.getDefaultInstance(field.getMessageType());
MessageReflection.MergeTarget anyField = target.newMergeTargetForField(field, anyBuilder);
mergeAnyFieldValue(
tokenizer,
extensionRegistry,
anyField,
parseTreeBuilder,
unknownFields,
field.getMessageType());
mergeAnyFieldValue(tokenizer, extensionRegistry, anyField, parseTreeBuilder,
unknownFields, field.getMessageType());
value = anyField.finish();
tokenizer.consume(endToken);
} else {
@@ -2228,7 +2206,7 @@ public final class TextFormat {
throw tokenizer.parseExceptionPreviousToken("Expected a valid type URL.");
}
}
detectSilentMarker(tokenizer, typeUrlBuilder.toString());
detectSilentMarker(tokenizer);
tokenizer.tryConsume(":");
final String anyEndToken;
if (tokenizer.tryConsume("<")) {
@@ -2266,7 +2244,15 @@ public final class TextFormat {
/** Skips the next field including the field's name and value. */
private void skipField(Tokenizer tokenizer) throws ParseException {
String name = consumeFullTypeName(tokenizer);
if (tokenizer.tryConsume("[")) {
// Extension name.
do {
tokenizer.consumeIdentifier();
} while (tokenizer.tryConsume("."));
tokenizer.consume("]");
} else {
tokenizer.consumeIdentifier();
}
// Try to guess the type of this field.
// If this field is not a message, there should be a ":" between the
@@ -2274,7 +2260,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.
detectSilentMarker(tokenizer, name);
detectSilentMarker(tokenizer);
if (tokenizer.tryConsume(":") && !tokenizer.lookingAt("<") && !tokenizer.lookingAt("{")) {
skipFieldValue(tokenizer);
} else {
@@ -2483,10 +2469,9 @@ public final class TextFormat {
}
Character.UnicodeBlock unicodeBlock = Character.UnicodeBlock.of(codepoint);
if (unicodeBlock != null
&& (unicodeBlock.equals(Character.UnicodeBlock.LOW_SURROGATES)
|| unicodeBlock.equals(Character.UnicodeBlock.HIGH_SURROGATES)
|| unicodeBlock.equals(
Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES))) {
&& (unicodeBlock.equals(Character.UnicodeBlock.LOW_SURROGATES)
|| unicodeBlock.equals(Character.UnicodeBlock.HIGH_SURROGATES)
|| unicodeBlock.equals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES))) {
throw new InvalidEscapeSequenceException(
"Invalid escape sequence: '\\U"
+ input.substring(i, i + 8).toStringUtf8()

View File

@@ -43,7 +43,7 @@ import java.nio.ByteBuffer;
* ByteString} can lead to unexpected and undesirable consequences in your application, and will
* likely be difficult to debug. Proceed with caution!
*
* <p>This can have a number of significant side effects that have spooky-action-at-a-distance-like
* <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>

View File

@@ -61,7 +61,6 @@ import protobuf_unittest.UnittestProto.TestExtremeDefaultValues;
import protobuf_unittest.UnittestProto.TestJsonName;
import protobuf_unittest.UnittestProto.TestMultipleExtensionRanges;
import protobuf_unittest.UnittestProto.TestRequired;
import protobuf_unittest.UnittestProto.TestReservedEnumFields;
import protobuf_unittest.UnittestProto.TestReservedFields;
import protobuf_unittest.UnittestProto.TestService;
import java.util.Collections;
@@ -464,15 +463,15 @@ public class DescriptorsTest {
/** Tests that parsing an unknown enum throws an exception */
@Test
public void testParseUnknownEnum() {
FieldDescriptorProto.Builder field =
FieldDescriptorProto.newBuilder()
.setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL)
.setTypeName("UnknownEnum")
.setType(FieldDescriptorProto.Type.TYPE_ENUM)
.setName("bar")
.setNumber(1);
DescriptorProto.Builder messageType =
DescriptorProto.newBuilder().setName("Foo").addField(field);
FieldDescriptorProto.Builder field = FieldDescriptorProto.newBuilder()
.setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL)
.setTypeName("UnknownEnum")
.setType(FieldDescriptorProto.Type.TYPE_ENUM)
.setName("bar")
.setNumber(1);
DescriptorProto.Builder messageType = DescriptorProto.newBuilder()
.setName("Foo")
.addField(field);
FileDescriptorProto fooProto =
FileDescriptorProto.newBuilder()
.setName("foo.proto")
@@ -487,6 +486,7 @@ public class DescriptorsTest {
}
}
/**
* Tests the translate/crosslink for an example where a message field's name and type name are the
* same.
@@ -560,10 +560,8 @@ public class DescriptorsTest {
Descriptors.FileDescriptor.buildFrom(barProto, new FileDescriptor[] {fooFile});
// Items in the FileDescriptor array can be in any order.
FileDescriptor unused1 =
Descriptors.FileDescriptor.buildFrom(bazProto, new FileDescriptor[] {fooFile, barFile});
FileDescriptor unused2 =
Descriptors.FileDescriptor.buildFrom(bazProto, new FileDescriptor[] {barFile, fooFile});
Descriptors.FileDescriptor.buildFrom(bazProto, new FileDescriptor[] {fooFile, barFile});
Descriptors.FileDescriptor.buildFrom(bazProto, new FileDescriptor[] {barFile, fooFile});
}
@Test
@@ -625,8 +623,7 @@ public class DescriptorsTest {
.setName("bar")
.setNumber(1)))
.build();
FileDescriptor unused =
Descriptors.FileDescriptor.buildFrom(fooProto, new FileDescriptor[0], true);
Descriptors.FileDescriptor.buildFrom(fooProto, new FileDescriptor[0], true);
}
@Test
@@ -660,8 +657,7 @@ public class DescriptorsTest {
Descriptors.FileDescriptor.buildFrom(forwardProto, new FileDescriptor[] {barFile});
try {
FileDescriptor unused =
Descriptors.FileDescriptor.buildFrom(fooProto, new FileDescriptor[] {forwardFile});
Descriptors.FileDescriptor.buildFrom(fooProto, new FileDescriptor[] {forwardFile});
assertWithMessage("DescriptorValidationException expected").fail();
} catch (DescriptorValidationException e) {
assertThat(e).hasMessageThat().contains("Bar");
@@ -699,8 +695,7 @@ public class DescriptorsTest {
FileDescriptor barFile = Descriptors.FileDescriptor.buildFrom(barProto, new FileDescriptor[0]);
FileDescriptor forwardFile =
Descriptors.FileDescriptor.buildFrom(forwardProto, new FileDescriptor[] {barFile});
FileDescriptor unused =
Descriptors.FileDescriptor.buildFrom(fooProto, new FileDescriptor[] {forwardFile});
Descriptors.FileDescriptor.buildFrom(fooProto, new FileDescriptor[] {forwardFile});
}
/** Tests the translate/crosslink for an example with a more complex namespace referencing. */
@@ -797,20 +792,6 @@ public class DescriptorsTest {
assertThat(d.isReservedName("baz")).isTrue();
}
@Test
public void testReservedEnumFields() {
EnumDescriptor d = TestReservedEnumFields.getDescriptor();
assertThat(d.isReservedNumber(2)).isTrue();
assertThat(d.isReservedNumber(8)).isFalse();
assertThat(d.isReservedNumber(9)).isTrue();
assertThat(d.isReservedNumber(10)).isTrue();
assertThat(d.isReservedNumber(11)).isTrue();
assertThat(d.isReservedNumber(12)).isFalse();
assertThat(d.isReservedName("foo")).isFalse();
assertThat(d.isReservedName("bar")).isTrue();
assertThat(d.isReservedName("baz")).isTrue();
}
@Test
public void testToString() {
assertThat(
@@ -845,8 +826,7 @@ public class DescriptorsTest {
.build())
.build())
.build();
FileDescriptor unused =
Descriptors.FileDescriptor.buildFrom(fileDescriptorProto, new FileDescriptor[0]);
Descriptors.FileDescriptor.buildFrom(fileDescriptorProto, new FileDescriptor[0]);
}
@Test

View File

@@ -44,7 +44,6 @@ import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestAllTypes.NestedMessage;
import protobuf_unittest.UnittestProto.TestEmptyMessage;
import protobuf_unittest.UnittestProto.TestPackedTypes;
import java.util.ArrayList;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;
import org.junit.runner.RunWith;
@@ -231,19 +230,6 @@ public class DynamicMessageTest {
assertThat(rawBytes).isEqualTo(TestUtil.getPackedSet().toByteString());
}
@Test
public void testDynamicMessagePackedEmptySerialization() throws Exception {
Message message =
DynamicMessage.newBuilder(TestPackedTypes.getDescriptor())
.setField(
TestPackedTypes.getDescriptor()
.findFieldByNumber(TestPackedTypes.PACKED_INT64_FIELD_NUMBER),
new ArrayList<Long>())
.build();
assertThat(message.toByteString()).isEqualTo(ByteString.EMPTY);
}
@Test
public void testDynamicMessagePackedParsing() throws Exception {
TestPackedTypes.Builder builder = TestPackedTypes.newBuilder();

View File

@@ -1529,7 +1529,7 @@ public class GeneratedMessageTest {
assertThat(builder.getFooInt()).isEqualTo(123);
TestOneof2 message = builder.buildPartial();
assertThat(message.hasFooInt()).isTrue();
assertThat(message.getFooInt()).isEqualTo(123);
assertThat(123).isEqualTo(message.getFooInt());
assertThat(builder.clearFooInt().hasFooInt()).isFalse();
TestOneof2 message2 = builder.build();
@@ -1943,7 +1943,7 @@ public class GeneratedMessageTest {
@Test
public void
extendableBuilder_extensionFieldContainingBuilder_setRepeatedFieldOverwritesElement() {
extendableBuilder_extensionFieldContainingBuilder_setRepeatedFieldOverwritesElement() {
TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
builder.addRepeatedField(REPEATED_NESTED_MESSAGE_EXTENSION, NestedMessage.getDefaultInstance());
// Calling getRepeatedFieldBuilder and ignoring the returned Builder should have no

View File

@@ -30,13 +30,14 @@
package com.google.protobuf;
import junit.framework.TestCase;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.Bar;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.BarPrime;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.Foo;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.TestOneofEquals;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.TestRecursiveOneof;
import junit.framework.TestCase;
/**
* Test generate equal and hash methods for the lite runtime.
*
@@ -119,6 +120,6 @@ public class LiteEqualsAndHashTest extends TestCase {
public void testRecursiveHashcode() {
// This tests that we don't infinite loop.
int unused = TestRecursiveOneof.getDefaultInstance().hashCode();
TestRecursiveOneof.getDefaultInstance().hashCode();
}
}

View File

@@ -33,6 +33,7 @@ package com.google.protobuf;
import static com.google.common.truth.Truth.assertThat;
import protobuf_unittest.Engine;
import protobuf_unittest.TimingBelt;
import protobuf_unittest.Vehicle;
import protobuf_unittest.Wheel;
import java.util.ArrayList;
@@ -48,6 +49,27 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class NestedBuildersTest {
@Test
public void test3LayerPropagationWithIntermediateClear() {
Vehicle.Builder vehicleBuilder = Vehicle.newBuilder();
vehicleBuilder.getEngineBuilder().getTimingBeltBuilder();
// This step detaches the TimingBelt.Builder (though it leaves a SingleFieldBuilder in place)
vehicleBuilder.getEngineBuilder().clear();
// These steps build the middle and top level messages, it used to leave the vestigial
// TimingBelt.Builder in a state where further changes didn't propagate anymore
Object unused = vehicleBuilder.getEngineBuilder().build();
unused = vehicleBuilder.build();
TimingBelt expected = TimingBelt.newBuilder().setNumberOfTeeth(124).build();
vehicleBuilder.getEngineBuilder().setTimingBelt(expected);
// Testing that b/254158939 is fixed. It used to be that the setTimingBelt call above didn't
// propagate a change notification and the call below would return a stale version of the timing
// belt.
assertThat(vehicleBuilder.getEngine().getTimingBelt()).isEqualTo(expected);
}
@Test
public void testMessagesAndBuilders() {
Vehicle.Builder vehicleBuilder = Vehicle.newBuilder();

View File

@@ -82,7 +82,7 @@ public class SingleFieldBuilderV3Test {
assertThat(mockParent.getInvalidationCount()).isEqualTo(0);
assertThat(builder.getBuilder().getOptionalInt32()).isEqualTo(1);
assertThat(builder.getMessage().getOptionalInt32()).isEqualTo(1);
TestAllTypes unused = builder.build();
builder.build();
builder.getBuilder().setOptionalInt32(2);
assertThat(builder.getBuilder().getOptionalInt32()).isEqualTo(2);
assertThat(builder.getMessage().getOptionalInt32()).isEqualTo(2);

View File

@@ -34,7 +34,6 @@ import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static java.lang.Math.min;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -49,6 +48,52 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class SmallSortedMapTest {
// java.util.AbstractMap.SimpleEntry is private in JDK 1.5. We re-implement it
// here for JDK 1.5 users.
private static class SimpleEntry<K, V> implements Map.Entry<K, V> {
private final K key;
private V value;
SimpleEntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
V oldValue = this.value;
this.value = value;
return oldValue;
}
private static boolean eq(Object o1, Object o2) {
return o1 == null ? o2 == null : o1.equals(o2);
}
@Override
public boolean equals(Object o) {
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());
}
}
@Test
public void testPutAndGetArrayEntriesOnly() {
@@ -197,8 +242,8 @@ public class SmallSortedMapTest {
}
Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet();
for (int i = 0; i < 6; i++) {
assertThat(entrySet).contains(new AbstractMap.SimpleEntry<Integer, Integer>(i, i + 1));
assertThat(entrySet).doesNotContain(new AbstractMap.SimpleEntry<Integer, Integer>(i, i));
assertThat(entrySet).contains(new SimpleEntry<Integer, Integer>(i, i + 1));
assertThat(entrySet).doesNotContain(new SimpleEntry<Integer, Integer>(i, i));
}
}
@@ -207,7 +252,7 @@ public class SmallSortedMapTest {
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 AbstractMap.SimpleEntry<>(i, i + 1);
Map.Entry<Integer, Integer> entry = new SimpleEntry<>(i, i + 1);
assertThat(entrySet.add(entry)).isTrue();
assertThat(entrySet.add(entry)).isFalse();
}
@@ -227,7 +272,7 @@ public class SmallSortedMapTest {
assertThat(map.put(i, i + 1)).isNull();
}
for (int i = 0; i < 6; i++) {
Map.Entry<Integer, Integer> entry = new AbstractMap.SimpleEntry<>(i, i + 1);
Map.Entry<Integer, Integer> entry = new SimpleEntry<>(i, i + 1);
assertThat(entrySet.remove(entry)).isTrue();
assertThat(entrySet.remove(entry)).isFalse();
}

View File

@@ -49,7 +49,7 @@ public class TestBadIdentifiers extends TestCase {
TestBadIdentifiersProto.Override.getDefaultInstance();
}
@SuppressWarnings({"IgnoredPureGetter", "CheckReturnValue"}) // TODO(b/221602772): Fix this
@SuppressWarnings("IgnoredPureGetter") // TODO(b/221602772): Fix this
public void testGetDescriptor() {
TestBadIdentifiersProto.getDescriptor();
TestBadIdentifiersProto.Descriptor.getDefaultInstance().getDescriptor();

View File

@@ -235,7 +235,6 @@ import protobuf_unittest.UnittestProto.TestRequired;
import protobuf_unittest.UnittestProto.TestUnpackedTypes;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Collections;
@@ -3843,11 +3842,7 @@ public final class TestUtil {
private static ByteString readBytesFromResource(String name) {
try {
InputStream in = TestUtil.class.getResourceAsStream(name);
if (in == null) { //
throw new RuntimeException("Tests data file " + name + " is missing.");
}
return ByteString.readFrom(in);
return ByteString.readFrom(TestUtil.class.getResourceAsStream(name));
} catch (IOException e) {
throw new RuntimeException(e);
}

View File

@@ -67,7 +67,9 @@ import org.junit.function.ThrowingRunnable;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Test case for {@link TextFormat}. */
/**
* Test case for {@link TextFormat}.
*/
@RunWith(JUnit4.class)
public class TextFormatTest {
@@ -823,7 +825,6 @@ public class TextFormatTest {
}
}
@CanIgnoreReturnValue
private TestAllTypes assertParseSuccessWithOverwriteForbidden(String text)
throws TextFormat.ParseException {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
@@ -1449,18 +1450,6 @@ public class TextFormatTest {
+ "unknown_field3: 3\n");
}
@Test
public void testParseUnknownExtensionWithAnyMessage() throws Exception {
assertParseSuccessWithUnknownExtensions(
"[unknown_extension]: { "
+ " any_value { "
+ " [type.googleapis.com/protobuf_unittest.OneString] { "
+ " data: 123 "
+ " } "
+ " } "
+ "}");
}
// See additional coverage in testOneofOverwriteForbidden and testMapOverwriteForbidden.
@Test
public void testParseNonRepeatedFields() throws Exception {
@@ -1773,7 +1762,6 @@ public class TextFormatTest {
}
}
@SuppressWarnings("LenientFormatStringValidation")
private void assertLocation(
TextFormatParseInfoTree tree,
final Descriptor descriptor,
@@ -1787,7 +1775,6 @@ public class TextFormatTest {
TextFormatParseLocation expected = TextFormatParseLocation.create(line, column);
assertThat(location).isEqualTo(expected);
} else if (line != -1 && column != -1) {
// Expected 0 args, but got 3.
assertWithMessage(
"Tree/descriptor/fieldname did not contain index %d, line %d column %d expected",
index, line, column)

View File

@@ -31,10 +31,7 @@
syntax = "proto2";
package map_for_proto2_lite_test;
option java_outer_classname = "MapForProto2TestProto";
option optimize_for = LITE_RUNTIME;
option java_package = "map_lite_test";
message TestMap {
message MessageValue {
@@ -128,3 +125,6 @@ message ReservedAsMapFieldWithEnumValue {
// null is not a 'reserved word' per se but as a literal needs similar care
map<string, SampleEnum> null = 10;
}
package map_for_proto2_lite_test;
option java_package = "map_lite_test";
option optimize_for = LITE_RUNTIME;

View File

@@ -45,6 +45,11 @@ message Vehicle {
message Engine {
optional int32 cylinder = 1;
optional int32 liters = 2;
optional TimingBelt timing_belt = 3;
}
message TimingBelt {
optional int32 number_of_teeth = 1;
}
message Wheel {

View File

@@ -36,6 +36,7 @@ package protobuf.experimental;
option java_package = "com.google.protobuf.testing";
option java_outer_classname = "Proto2Testing";
message Proto2SpecialFieldName {
optional double regular_name = 1;
optional int32 cached_size = 2;

View File

@@ -36,6 +36,7 @@ package protobuf.experimental.lite;
option java_package = "com.google.protobuf.testing";
option java_outer_classname = "Proto2TestingLite";
message Proto2MessageLite {
enum TestEnum {