• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 //
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file or at
6 // https://developers.google.com/open-source/licenses/bsd
7 
8 package com.google.protobuf;
9 
10 import com.google.protobuf.AbstractMessageLite.Builder.LimitedInputStream;
11 import com.google.protobuf.Internal.BooleanList;
12 import com.google.protobuf.Internal.DoubleList;
13 import com.google.protobuf.Internal.FloatList;
14 import com.google.protobuf.Internal.IntList;
15 import com.google.protobuf.Internal.LongList;
16 import com.google.protobuf.Internal.ProtobufList;
17 import com.google.protobuf.WireFormat.FieldType;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.ObjectStreamException;
21 import java.io.Serializable;
22 import java.lang.reflect.InvocationTargetException;
23 import java.lang.reflect.Method;
24 import java.nio.ByteBuffer;
25 import java.util.ArrayList;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.concurrent.ConcurrentHashMap;
30 
31 /**
32  * Lite version of {@link GeneratedMessage}.
33  *
34  * @author kenton@google.com Kenton Varda
35  */
36 public abstract class GeneratedMessageLite<
37         MessageType extends GeneratedMessageLite<MessageType, BuilderType>,
38         BuilderType extends GeneratedMessageLite.Builder<MessageType, BuilderType>>
39     extends AbstractMessageLite<MessageType, BuilderType> {
40 
41   /* For use by lite runtime only */
42   static final int UNINITIALIZED_SERIALIZED_SIZE = 0x7FFFFFFF;
43   private static final int MUTABLE_FLAG_MASK = 0x80000000;
44   private static final int MEMOIZED_SERIALIZED_SIZE_MASK = 0x7FFFFFFF;
45 
46   /**
47    * We use the high bit of memoizedSerializedSize as the explicit mutability flag. It didn't make
48    * sense to have negative sizes anyway. Messages start as mutable.
49    *
50    * <p>Adding a standalone boolean would have added 8 bytes to every message instance.
51    *
52    * <p>We also reserve 0x7FFFFFFF as the "uninitialized" value.
53    */
54   private int memoizedSerializedSize = MUTABLE_FLAG_MASK | UNINITIALIZED_SERIALIZED_SIZE;
55 
56   /* For use by the runtime only */
57   static final int UNINITIALIZED_HASH_CODE = 0;
58 
59   /** For use by generated code only. Lazily initialized to reduce allocations. */
60   protected UnknownFieldSetLite unknownFields = UnknownFieldSetLite.getDefaultInstance();
61 
isMutable()62   boolean isMutable() {
63     return (memoizedSerializedSize & MUTABLE_FLAG_MASK) != 0;
64   }
65 
markImmutable()66   void markImmutable() {
67     memoizedSerializedSize &= ~MUTABLE_FLAG_MASK;
68   }
69 
getMemoizedHashCode()70   int getMemoizedHashCode() {
71     return memoizedHashCode;
72   }
73 
setMemoizedHashCode(int value)74   void setMemoizedHashCode(int value) {
75     memoizedHashCode = value;
76   }
77 
clearMemoizedHashCode()78   void clearMemoizedHashCode() {
79     memoizedHashCode = UNINITIALIZED_HASH_CODE;
80   }
81 
hashCodeIsNotMemoized()82   boolean hashCodeIsNotMemoized() {
83     return UNINITIALIZED_HASH_CODE == getMemoizedHashCode();
84   }
85 
86   @Override
87   @SuppressWarnings("unchecked") // Guaranteed by runtime.
getParserForType()88   public final Parser<MessageType> getParserForType() {
89     return (Parser<MessageType>) dynamicMethod(MethodToInvoke.GET_PARSER);
90   }
91 
92   @Override
93   @SuppressWarnings("unchecked") // Guaranteed by runtime.
getDefaultInstanceForType()94   public final MessageType getDefaultInstanceForType() {
95     return (MessageType) dynamicMethod(MethodToInvoke.GET_DEFAULT_INSTANCE);
96   }
97 
98   @Override
99   @SuppressWarnings("unchecked") // Guaranteed by runtime.
newBuilderForType()100   public final BuilderType newBuilderForType() {
101     return (BuilderType) dynamicMethod(MethodToInvoke.NEW_BUILDER);
102   }
103 
newMutableInstance()104   MessageType newMutableInstance() {
105     return (MessageType) dynamicMethod(MethodToInvoke.NEW_MUTABLE_INSTANCE);
106   }
107 
108   /**
109    * A reflective toString function. This is primarily intended as a developer aid, while keeping
110    * binary size down. The first line of the {@code toString()} representation includes a commented
111    * version of {@code super.toString()} to act as an indicator that this should not be relied on
112    * for comparisons.
113    *
114    * <p>NOTE: This method relies on the field getter methods not being stripped or renamed by
115    * proguard. If they are, the fields will not be included in the returned string representation.
116    *
117    * <p>NOTE: This implementation is liable to change in the future, and should not be relied on in
118    * code.
119    */
120   @Override
toString()121   public String toString() {
122     return MessageLiteToString.toString(this, super.toString());
123   }
124 
125   @Override
hashCode()126   public int hashCode() {
127     if (isMutable()) {
128       return computeHashCode();
129     }
130 
131     if (hashCodeIsNotMemoized()) {
132       setMemoizedHashCode(computeHashCode());
133     }
134 
135     return getMemoizedHashCode();
136   }
137 
computeHashCode()138   int computeHashCode() {
139     return Protobuf.getInstance().schemaFor(this).hashCode(this);
140   }
141 
142   @SuppressWarnings("unchecked") // Guaranteed by isInstance + runtime
143   @Override
equals( Object other)144   public boolean equals(
145           Object other) {
146     if (this == other) {
147       return true;
148     }
149 
150     if (other == null) {
151       return false;
152     }
153 
154     if (this.getClass() != other.getClass()) {
155       return false;
156     }
157 
158     return Protobuf.getInstance().schemaFor(this).equals(this, (MessageType) other);
159   }
160 
161   // The general strategy for unknown fields is to use an UnknownFieldSetLite that is treated as
162   // mutable during the parsing constructor and immutable after. This allows us to avoid
163   // any unnecessary intermediary allocations while reducing the generated code size.
164 
165   /** Lazily initializes unknown fields. */
ensureUnknownFieldsInitialized()166   private void ensureUnknownFieldsInitialized() {
167     if (unknownFields == UnknownFieldSetLite.getDefaultInstance()) {
168       unknownFields = UnknownFieldSetLite.newInstance();
169     }
170   }
171 
172   /**
173    * Called by subclasses to parse an unknown field. For use by generated code only.
174    *
175    * @return {@code true} unless the tag is an end-group tag.
176    */
parseUnknownField(int tag, CodedInputStream input)177   protected boolean parseUnknownField(int tag, CodedInputStream input) throws IOException {
178     // This will avoid the allocation of unknown fields when a group tag is encountered.
179     if (WireFormat.getTagWireType(tag) == WireFormat.WIRETYPE_END_GROUP) {
180       return false;
181     }
182 
183     ensureUnknownFieldsInitialized();
184     return unknownFields.mergeFieldFrom(tag, input);
185   }
186 
187   /** Called by subclasses to parse an unknown field. For use by generated code only. */
mergeVarintField(int tag, int value)188   protected void mergeVarintField(int tag, int value) {
189     ensureUnknownFieldsInitialized();
190     unknownFields.mergeVarintField(tag, value);
191   }
192 
193   /** Called by subclasses to parse an unknown field. For use by generated code only. */
mergeLengthDelimitedField(int fieldNumber, ByteString value)194   protected void mergeLengthDelimitedField(int fieldNumber, ByteString value) {
195     ensureUnknownFieldsInitialized();
196     unknownFields.mergeLengthDelimitedField(fieldNumber, value);
197   }
198 
199   /** Called by subclasses to complete parsing. For use by generated code only. */
makeImmutable()200   protected void makeImmutable() {
201     Protobuf.getInstance().schemaFor(this).makeImmutable(this);
202     markImmutable();
203   }
204 
205   protected final <
206           MessageType extends GeneratedMessageLite<MessageType, BuilderType>,
207           BuilderType extends GeneratedMessageLite.Builder<MessageType, BuilderType>>
createBuilder()208       BuilderType createBuilder() {
209     return (BuilderType) dynamicMethod(MethodToInvoke.NEW_BUILDER);
210   }
211 
212   protected final <
213           MessageType extends GeneratedMessageLite<MessageType, BuilderType>,
214           BuilderType extends GeneratedMessageLite.Builder<MessageType, BuilderType>>
createBuilder(MessageType prototype)215       BuilderType createBuilder(MessageType prototype) {
216     return ((BuilderType) createBuilder()).mergeFrom(prototype);
217   }
218 
219   @Override
isInitialized()220   public final boolean isInitialized() {
221     return isInitialized((MessageType) this, /* shouldMemoize= */ true);
222   }
223 
224   @Override
225   @SuppressWarnings("unchecked")
toBuilder()226   public final BuilderType toBuilder() {
227     BuilderType builder = (BuilderType) dynamicMethod(MethodToInvoke.NEW_BUILDER);
228     return builder.mergeFrom((MessageType) this);
229   }
230 
231   /**
232    * Defines which method path to invoke in {@link GeneratedMessageLite
233    * #dynamicMethod(MethodToInvoke, Object...)}.
234    *
235    * <p>For use by generated code only.
236    */
237   public static enum MethodToInvoke {
238     // Rely on/modify instance state
239     GET_MEMOIZED_IS_INITIALIZED,
240     SET_MEMOIZED_IS_INITIALIZED,
241 
242     // Rely on static state
243     BUILD_MESSAGE_INFO,
244     NEW_MUTABLE_INSTANCE,
245     NEW_BUILDER,
246     GET_DEFAULT_INSTANCE,
247     GET_PARSER;
248   }
249 
250   /**
251    * A method that implements different types of operations described in {@link MethodToInvoke}.
252    * These different kinds of operations are required to implement message-level operations for
253    * builders in the runtime. This method bundles those operations to reduce the generated methods
254    * count.
255    *
256    * <ul>
257    *   <li>{@code NEW_INSTANCE} returns a new instance of the protocol buffer that has not yet been
258    *       made immutable. See {@code MAKE_IMMUTABLE}.
259    *   <li>{@code IS_INITIALIZED} returns {@code null} for false and the default instance for true.
260    *       It doesn't use or modify any memoized value.
261    *   <li>{@code GET_MEMOIZED_IS_INITIALIZED} returns the memoized {@code isInitialized} byte
262    *       value.
263    *   <li>{@code SET_MEMOIZED_IS_INITIALIZED} sets the memoized {@code isInitialized} byte value to
264    *       1 if the first parameter is not null, or to 0 if the first parameter is null.
265    *   <li>{@code NEW_BUILDER} returns a {@code BuilderType} instance.
266    * </ul>
267    *
268    * This method, plus the implementation of the Builder, enables the Builder class to be proguarded
269    * away entirely on Android.
270    *
271    * <p>For use by generated code only.
272    */
dynamicMethod( MethodToInvoke method, Object arg0, Object arg1)273   protected abstract Object dynamicMethod(
274       MethodToInvoke method,
275           Object arg0,
276           Object arg1);
277 
278   /** Same as {@link #dynamicMethod(MethodToInvoke, Object, Object)} with {@code null} padding. */
279   @CanIgnoreReturnValue
dynamicMethod( MethodToInvoke method, Object arg0)280   protected Object dynamicMethod(
281       MethodToInvoke method,
282           Object arg0) {
283     return dynamicMethod(method, arg0, null);
284   }
285 
286   /** Same as {@link #dynamicMethod(MethodToInvoke, Object, Object)} with {@code null} padding. */
dynamicMethod(MethodToInvoke method)287   protected Object dynamicMethod(MethodToInvoke method) {
288     return dynamicMethod(method, null, null);
289   }
290 
clearMemoizedSerializedSize()291   void clearMemoizedSerializedSize() {
292     setMemoizedSerializedSize(UNINITIALIZED_SERIALIZED_SIZE);
293   }
294 
295   @Override
getMemoizedSerializedSize()296   int getMemoizedSerializedSize() {
297     return memoizedSerializedSize & MEMOIZED_SERIALIZED_SIZE_MASK;
298   }
299 
300   @Override
setMemoizedSerializedSize(int size)301   void setMemoizedSerializedSize(int size) {
302     if (size < 0) {
303       throw new IllegalStateException("serialized size must be non-negative, was " + size);
304     }
305     memoizedSerializedSize =
306         (memoizedSerializedSize & MUTABLE_FLAG_MASK) | (size & MEMOIZED_SERIALIZED_SIZE_MASK);
307   }
308 
309   @Override
writeTo(CodedOutputStream output)310   public void writeTo(CodedOutputStream output) throws IOException {
311     Protobuf.getInstance()
312         .schemaFor(this)
313         .writeTo(this, CodedOutputStreamWriter.forCodedOutput(output));
314   }
315 
316   @Override
getSerializedSize( Schema schema)317   int getSerializedSize(
318           Schema schema) {
319     if (isMutable()) {
320       // The serialized size should never be memoized for mutable instances.
321       int size = computeSerializedSize(schema);
322       if (size < 0) {
323         throw new IllegalStateException("serialized size must be non-negative, was " + size);
324       }
325       return size;
326     }
327 
328     // If memoizedSerializedSize has already been set, return it.
329     if (getMemoizedSerializedSize() != UNINITIALIZED_SERIALIZED_SIZE) {
330       return getMemoizedSerializedSize();
331     }
332 
333     // Need to compute and memoize the serialized size.
334     int size = computeSerializedSize(schema);
335     setMemoizedSerializedSize(size);
336     return size;
337   }
338 
339   @Override
getSerializedSize()340   public int getSerializedSize() {
341     // Calling this with 'null' to delay schema lookup in case the serializedSize is already
342     // memoized.
343     return getSerializedSize(null);
344   }
345 
computeSerializedSize( Schema<?> nullableSchema)346   private int computeSerializedSize(
347           Schema<?> nullableSchema) {
348     if (nullableSchema == null) {
349       return Protobuf.getInstance().schemaFor(this).getSerializedSize(this);
350     } else {
351       return ((Schema<GeneratedMessageLite<MessageType, BuilderType>>) nullableSchema)
352           .getSerializedSize(this);
353     }
354   }
355 
356   /** Constructs a {@link MessageInfo} for this message type. */
buildMessageInfo()357   Object buildMessageInfo() throws Exception {
358     return dynamicMethod(MethodToInvoke.BUILD_MESSAGE_INFO);
359   }
360 
361   private static Map<Class<?>, GeneratedMessageLite<?, ?>> defaultInstanceMap =
362       new ConcurrentHashMap<>();
363 
364   @SuppressWarnings("unchecked")
getDefaultInstance(Class<T> clazz)365   static <T extends GeneratedMessageLite<?, ?>> T getDefaultInstance(Class<T> clazz) {
366     T result = (T) defaultInstanceMap.get(clazz);
367     if (result == null) {
368       // Foo.class does not initialize the class so we need to force the initialization in order to
369       // get the default instance registered.
370       try {
371         Class.forName(clazz.getName(), true, clazz.getClassLoader());
372       } catch (ClassNotFoundException e) {
373         throw new IllegalStateException("Class initialization cannot fail.", e);
374       }
375       result = (T) defaultInstanceMap.get(clazz);
376     }
377     if (result == null) {
378       // On some Samsung devices, this still doesn't return a valid value for some reason. We add a
379       // reflective fallback to keep the device running. See b/114675342.
380       result = (T) UnsafeUtil.allocateInstance(clazz).getDefaultInstanceForType();
381       // A sanity check to ensure that <clinit> was actually invoked.
382       if (result == null) {
383         throw new IllegalStateException();
384       }
385       defaultInstanceMap.put(clazz, result);
386     }
387     return result;
388   }
389 
registerDefaultInstance( Class<T> clazz, T defaultInstance)390   protected static <T extends GeneratedMessageLite<?, ?>> void registerDefaultInstance(
391       Class<T> clazz, T defaultInstance) {
392     // Default instances must be immutable.
393     // Marking immutable here to avoid extra bytecode in every generated message class.
394     // Only calling "markImmutable" rather than "makeImmutable" because for Default Instances:
395     // 1. All sub-messages are initialized to null / default instances and thus immutable
396     // 2. All lists are initialized to default instance empty lists which are also immutable.
397     defaultInstance.markImmutable();
398     defaultInstanceMap.put(clazz, defaultInstance);
399   }
400 
newMessageInfo( MessageLite defaultInstance, String info, Object[] objects)401   protected static Object newMessageInfo(
402       MessageLite defaultInstance, String info, Object[] objects) {
403     return new RawMessageInfo(defaultInstance, info, objects);
404   }
405 
406   /**
407    * Merge some unknown fields into the {@link UnknownFieldSetLite} for this message.
408    *
409    * <p>For use by generated code only.
410    */
mergeUnknownFields(UnknownFieldSetLite unknownFields)411   protected final void mergeUnknownFields(UnknownFieldSetLite unknownFields) {
412     this.unknownFields = UnknownFieldSetLite.mutableCopyOf(this.unknownFields, unknownFields);
413   }
414 
415   @SuppressWarnings("unchecked")
416   public abstract static class Builder<
417           MessageType extends GeneratedMessageLite<MessageType, BuilderType>,
418           BuilderType extends Builder<MessageType, BuilderType>>
419       extends AbstractMessageLite.Builder<MessageType, BuilderType> {
420 
421     private final MessageType defaultInstance;
422     protected MessageType instance;
423 
Builder(MessageType defaultInstance)424     protected Builder(MessageType defaultInstance) {
425       this.defaultInstance = defaultInstance;
426       if (defaultInstance.isMutable()) {
427         throw new IllegalArgumentException("Default instance must be immutable.");
428       }
429       // this.instance should be set to defaultInstance but some tests rely on newBuilder().build()
430       // creating unique instances.
431       this.instance = newMutableInstance();
432     }
433 
newMutableInstance()434     private MessageType newMutableInstance() {
435       return defaultInstance.newMutableInstance();
436     }
437 
438     /**
439      * Called before any method that would mutate the builder to ensure that it correctly copies any
440      * state before the write happens to preserve immutability guarantees.
441      */
copyOnWrite()442     protected final void copyOnWrite() {
443       if (!instance.isMutable()) {
444         copyOnWriteInternal();
445       }
446     }
447 
copyOnWriteInternal()448     protected void copyOnWriteInternal() {
449       MessageType newInstance = newMutableInstance();
450       mergeFromInstance(newInstance, instance);
451       instance = newInstance;
452     }
453 
454     @Override
isInitialized()455     public final boolean isInitialized() {
456       return GeneratedMessageLite.isInitialized(instance, /* shouldMemoize= */ false);
457     }
458 
459     @Override
clear()460     public final BuilderType clear() {
461       // No need to copy on write since we're dropping the instance anyway.
462       if (defaultInstance.isMutable()) {
463         throw new IllegalArgumentException("Default instance must be immutable.");
464       }
465       instance = newMutableInstance(); // should be defaultInstance;
466       return (BuilderType) this;
467     }
468 
469     @Override
clone()470     public BuilderType clone() {
471       BuilderType builder = (BuilderType) getDefaultInstanceForType().newBuilderForType();
472       builder.instance = buildPartial();
473       return builder;
474     }
475 
476     @Override
buildPartial()477     public MessageType buildPartial() {
478       if (!instance.isMutable()) {
479         return instance;
480       }
481 
482       instance.makeImmutable();
483       return instance;
484     }
485 
486     @Override
build()487     public final MessageType build() {
488       MessageType result = buildPartial();
489       if (!result.isInitialized()) {
490         throw newUninitializedMessageException(result);
491       }
492       return result;
493     }
494 
495     @Override
internalMergeFrom(MessageType message)496     protected BuilderType internalMergeFrom(MessageType message) {
497       return mergeFrom(message);
498     }
499 
500     /** All subclasses implement this. */
mergeFrom(MessageType message)501     public BuilderType mergeFrom(MessageType message) {
502       if (getDefaultInstanceForType().equals(message)) {
503         return (BuilderType) this;
504       }
505       copyOnWrite();
506       mergeFromInstance(instance, message);
507       return (BuilderType) this;
508     }
509 
mergeFromInstance(MessageType dest, MessageType src)510     private static <MessageType> void mergeFromInstance(MessageType dest, MessageType src) {
511       Protobuf.getInstance().schemaFor(dest).mergeFrom(dest, src);
512     }
513 
514     @Override
getDefaultInstanceForType()515     public MessageType getDefaultInstanceForType() {
516       return defaultInstance;
517     }
518 
519     @Override
mergeFrom( byte[] input, int offset, int length, ExtensionRegistryLite extensionRegistry)520     public BuilderType mergeFrom(
521         byte[] input, int offset, int length, ExtensionRegistryLite extensionRegistry)
522         throws InvalidProtocolBufferException {
523       copyOnWrite();
524       try {
525         Protobuf.getInstance().schemaFor(instance).mergeFrom(
526             instance, input, offset, offset + length,
527             new ArrayDecoders.Registers(extensionRegistry));
528       } catch (InvalidProtocolBufferException e) {
529         throw e;
530       } catch (IndexOutOfBoundsException e) {
531         throw InvalidProtocolBufferException.truncatedMessage();
532       } catch (IOException e) {
533         throw new RuntimeException("Reading from byte array should not throw IOException.", e);
534       }
535       return (BuilderType) this;
536     }
537 
538     @Override
mergeFrom( byte[] input, int offset, int length)539     public BuilderType mergeFrom(
540         byte[] input, int offset, int length)
541         throws InvalidProtocolBufferException {
542       return mergeFrom(input, offset, length, ExtensionRegistryLite.getEmptyRegistry());
543     }
544 
545     @Override
mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)546     public BuilderType mergeFrom(
547         com.google.protobuf.CodedInputStream input,
548         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
549         throws IOException {
550       copyOnWrite();
551       try {
552         // TODO: Try to make input with type CodedInputStream.ArrayDecoder use
553         // fast path.
554         Protobuf.getInstance().schemaFor(instance).mergeFrom(
555             instance, CodedInputStreamReader.forCodedInput(input), extensionRegistry);
556       } catch (RuntimeException e) {
557         if (e.getCause() instanceof IOException) {
558           throw (IOException) e.getCause();
559         }
560         throw e;
561       }
562       return (BuilderType) this;
563     }
564   }
565 
566   // =================================================================
567   // Extensions-related stuff
568 
569   /** Lite equivalent of {@link com.google.protobuf.GeneratedMessage.ExtendableMessageOrBuilder}. */
570   public interface ExtendableMessageOrBuilder<
571           MessageType extends ExtendableMessage<MessageType, BuilderType>,
572           BuilderType extends ExtendableBuilder<MessageType, BuilderType>>
573       extends MessageLiteOrBuilder {
574 
575     /** Check if a singular extension is present. */
hasExtension(ExtensionLite<MessageType, Type> extension)576     <Type> boolean hasExtension(ExtensionLite<MessageType, Type> extension);
577 
578     /** Get the number of elements in a repeated extension. */
getExtensionCount(ExtensionLite<MessageType, List<Type>> extension)579     <Type> int getExtensionCount(ExtensionLite<MessageType, List<Type>> extension);
580 
581     /** Get the value of an extension. */
getExtension(ExtensionLite<MessageType, Type> extension)582     <Type> Type getExtension(ExtensionLite<MessageType, Type> extension);
583 
584     /** Get one element of a repeated extension. */
getExtension(ExtensionLite<MessageType, List<Type>> extension, int index)585     <Type> Type getExtension(ExtensionLite<MessageType, List<Type>> extension, int index);
586   }
587 
588   /** Lite equivalent of {@link GeneratedMessage.ExtendableMessage}. */
589   public abstract static class ExtendableMessage<
590           MessageType extends ExtendableMessage<MessageType, BuilderType>,
591           BuilderType extends ExtendableBuilder<MessageType, BuilderType>>
592       extends GeneratedMessageLite<MessageType, BuilderType>
593       implements ExtendableMessageOrBuilder<MessageType, BuilderType> {
594 
595     /** Represents the set of extensions on this message. For use by generated code only. */
596     protected FieldSet<ExtensionDescriptor> extensions = FieldSet.emptySet();
597 
598     @SuppressWarnings("unchecked")
mergeExtensionFields(final MessageType other)599     protected final void mergeExtensionFields(final MessageType other) {
600       if (extensions.isImmutable()) {
601         extensions = extensions.clone();
602       }
603       extensions.mergeFrom(((ExtendableMessage) other).extensions);
604     }
605 
606     /**
607      * Parse an unknown field or an extension. For use by generated code only.
608      *
609      * <p>For use by generated code only.
610      *
611      * @return {@code true} unless the tag is an end-group tag.
612      */
parseUnknownField( MessageType defaultInstance, CodedInputStream input, ExtensionRegistryLite extensionRegistry, int tag)613     protected <MessageType extends MessageLite> boolean parseUnknownField(
614         MessageType defaultInstance,
615         CodedInputStream input,
616         ExtensionRegistryLite extensionRegistry,
617         int tag)
618         throws IOException {
619       int fieldNumber = WireFormat.getTagFieldNumber(tag);
620 
621       // TODO: How much bytecode would be saved by not requiring the generated code to
622       //     provide the default instance?
623       GeneratedExtension<MessageType, ?> extension =
624           extensionRegistry.findLiteExtensionByNumber(defaultInstance, fieldNumber);
625 
626       return parseExtension(input, extensionRegistry, extension, tag, fieldNumber);
627     }
628 
parseExtension( CodedInputStream input, ExtensionRegistryLite extensionRegistry, GeneratedExtension<?, ?> extension, int tag, int fieldNumber)629     private boolean parseExtension(
630         CodedInputStream input,
631         ExtensionRegistryLite extensionRegistry,
632         GeneratedExtension<?, ?> extension,
633         int tag,
634         int fieldNumber)
635         throws IOException {
636       int wireType = WireFormat.getTagWireType(tag);
637       boolean unknown = false;
638       boolean packed = false;
639       if (extension == null) {
640         unknown = true; // Unknown field.
641       } else if (wireType
642           == FieldSet.getWireFormatForFieldType(
643               extension.descriptor.getLiteType(), /* isPacked= */ false)) {
644         packed = false; // Normal, unpacked value.
645       } else if (extension.descriptor.isRepeated
646           && extension.descriptor.type.isPackable()
647           && wireType
648               == FieldSet.getWireFormatForFieldType(
649                   extension.descriptor.getLiteType(), /* isPacked= */ true)) {
650         packed = true; // Packed value.
651       } else {
652         unknown = true; // Wrong wire type.
653       }
654 
655       if (unknown) { // Unknown field or wrong wire type.  Skip.
656         return parseUnknownField(tag, input);
657       }
658 
659       // TODO: remove the unused variable
660       FieldSet<ExtensionDescriptor> unused = ensureExtensionsAreMutable();
661 
662       if (packed) {
663         int length = input.readRawVarint32();
664         int limit = input.pushLimit(length);
665         if (extension.descriptor.getLiteType() == WireFormat.FieldType.ENUM) {
666           while (input.getBytesUntilLimit() > 0) {
667             int rawValue = input.readEnum();
668             Object value = extension.descriptor.getEnumType().findValueByNumber(rawValue);
669             if (value == null) {
670               // If the number isn't recognized as a valid value for this
671               // enum, drop it (don't even add it to unknownFields).
672               return true;
673             }
674             extensions.addRepeatedField(
675                 extension.descriptor, extension.singularToFieldSetType(value));
676           }
677         } else {
678           while (input.getBytesUntilLimit() > 0) {
679             Object value =
680                 FieldSet.readPrimitiveField(
681                     input, extension.descriptor.getLiteType(), /*checkUtf8=*/ false);
682             extensions.addRepeatedField(extension.descriptor, value);
683           }
684         }
685         input.popLimit(limit);
686       } else {
687         Object value;
688         switch (extension.descriptor.getLiteJavaType()) {
689           case MESSAGE:
690             {
691               MessageLite.Builder subBuilder = null;
692               if (!extension.descriptor.isRepeated()) {
693                 MessageLite existingValue = (MessageLite) extensions.getField(extension.descriptor);
694                 if (existingValue != null) {
695                   subBuilder = existingValue.toBuilder();
696                 }
697               }
698               if (subBuilder == null) {
699                 subBuilder = extension.getMessageDefaultInstance().newBuilderForType();
700               }
701               if (extension.descriptor.getLiteType() == WireFormat.FieldType.GROUP) {
702                 input.readGroup(extension.getNumber(), subBuilder, extensionRegistry);
703               } else {
704                 input.readMessage(subBuilder, extensionRegistry);
705               }
706               value = subBuilder.build();
707               break;
708             }
709           case ENUM:
710             int rawValue = input.readEnum();
711             value = extension.descriptor.getEnumType().findValueByNumber(rawValue);
712             // If the number isn't recognized as a valid value for this enum,
713             // write it to unknown fields object.
714             if (value == null) {
715               mergeVarintField(fieldNumber, rawValue);
716               return true;
717             }
718             break;
719           default:
720             value =
721                 FieldSet.readPrimitiveField(
722                     input, extension.descriptor.getLiteType(), /*checkUtf8=*/ false);
723             break;
724         }
725 
726         if (extension.descriptor.isRepeated()) {
727           extensions.addRepeatedField(
728               extension.descriptor, extension.singularToFieldSetType(value));
729         } else {
730           extensions.setField(extension.descriptor, extension.singularToFieldSetType(value));
731         }
732       }
733       return true;
734     }
735 
736     /**
737      * Parse an unknown field or an extension. For use by generated code only.
738      *
739      * <p>For use by generated code only.
740      *
741      * @return {@code true} unless the tag is an end-group tag.
742      */
parseUnknownFieldAsMessageSet( MessageType defaultInstance, CodedInputStream input, ExtensionRegistryLite extensionRegistry, int tag)743     protected <MessageType extends MessageLite> boolean parseUnknownFieldAsMessageSet(
744         MessageType defaultInstance,
745         CodedInputStream input,
746         ExtensionRegistryLite extensionRegistry,
747         int tag)
748         throws IOException {
749 
750       if (tag == WireFormat.MESSAGE_SET_ITEM_TAG) {
751         mergeMessageSetExtensionFromCodedStream(defaultInstance, input, extensionRegistry);
752         return true;
753       }
754 
755       // TODO: Do we really want to support non message set wire format in message sets?
756       // Full runtime does... So we do for now.
757       int wireType = WireFormat.getTagWireType(tag);
758       if (wireType == WireFormat.WIRETYPE_LENGTH_DELIMITED) {
759         return parseUnknownField(defaultInstance, input, extensionRegistry, tag);
760       } else {
761         // TODO: Should we throw on invalid input? Full runtime does not...
762         return input.skipField(tag);
763       }
764     }
765 
766     /**
767      * Merges the message set from the input stream; requires message set wire format.
768      *
769      * @param defaultInstance the default instance of the containing message we are parsing in
770      * @param input the stream to parse from
771      * @param extensionRegistry the registry to use when parsing
772      */
mergeMessageSetExtensionFromCodedStream( MessageType defaultInstance, CodedInputStream input, ExtensionRegistryLite extensionRegistry)773     private <MessageType extends MessageLite> void mergeMessageSetExtensionFromCodedStream(
774         MessageType defaultInstance,
775         CodedInputStream input,
776         ExtensionRegistryLite extensionRegistry)
777         throws IOException {
778       // The wire format for MessageSet is:
779       //   message MessageSet {
780       //     repeated group Item = 1 {
781       //       required uint32 typeId = 2;
782       //       required bytes message = 3;
783       //     }
784       //   }
785       // "typeId" is the extension's field number.  The extension can only be
786       // a message type, where "message" contains the encoded bytes of that
787       // message.
788       //
789       // In practice, we will probably never see a MessageSet item in which
790       // the message appears before the type ID, or where either field does not
791       // appear exactly once.  However, in theory such cases are valid, so we
792       // should be prepared to accept them.
793 
794       int typeId = 0;
795       ByteString rawBytes = null; // If we encounter "message" before "typeId"
796       GeneratedExtension<?, ?> extension = null;
797 
798       // Read bytes from input, if we get it's type first then parse it eagerly,
799       // otherwise we store the raw bytes in a local variable.
800       while (true) {
801         final int tag = input.readTag();
802         if (tag == 0) {
803           break;
804         }
805 
806         if (tag == WireFormat.MESSAGE_SET_TYPE_ID_TAG) {
807           typeId = input.readUInt32();
808           if (typeId != 0) {
809             extension = extensionRegistry.findLiteExtensionByNumber(defaultInstance, typeId);
810           }
811 
812         } else if (tag == WireFormat.MESSAGE_SET_MESSAGE_TAG) {
813           if (typeId != 0) {
814             if (extension != null) {
815               // We already know the type, so we can parse directly from the
816               // input with no copying.  Hooray!
817               eagerlyMergeMessageSetExtension(input, extension, extensionRegistry, typeId);
818               rawBytes = null;
819               continue;
820             }
821           }
822           // We haven't seen a type ID yet or we want parse message lazily.
823           rawBytes = input.readBytes();
824 
825         } else { // Unknown tag. Skip it.
826           if (!input.skipField(tag)) {
827             break; // End of group
828           }
829         }
830       }
831       input.checkLastTagWas(WireFormat.MESSAGE_SET_ITEM_END_TAG);
832 
833       // Process the raw bytes.
834       if (rawBytes != null && typeId != 0) { // Zero is not a valid type ID.
835         if (extension != null) { // We known the type
836           mergeMessageSetExtensionFromBytes(rawBytes, extensionRegistry, extension);
837         } else { // We don't know how to parse this. Ignore it.
838           if (rawBytes != null) {
839             mergeLengthDelimitedField(typeId, rawBytes);
840           }
841         }
842       }
843     }
844 
eagerlyMergeMessageSetExtension( CodedInputStream input, GeneratedExtension<?, ?> extension, ExtensionRegistryLite extensionRegistry, int typeId)845     private void eagerlyMergeMessageSetExtension(
846         CodedInputStream input,
847         GeneratedExtension<?, ?> extension,
848         ExtensionRegistryLite extensionRegistry,
849         int typeId)
850         throws IOException {
851       int fieldNumber = typeId;
852       int tag = WireFormat.makeTag(typeId, WireFormat.WIRETYPE_LENGTH_DELIMITED);
853       // TODO: remove the unused variable
854       boolean unused = parseExtension(input, extensionRegistry, extension, tag, fieldNumber);
855     }
856 
mergeMessageSetExtensionFromBytes( ByteString rawBytes, ExtensionRegistryLite extensionRegistry, GeneratedExtension<?, ?> extension)857     private void mergeMessageSetExtensionFromBytes(
858         ByteString rawBytes,
859         ExtensionRegistryLite extensionRegistry,
860         GeneratedExtension<?, ?> extension)
861         throws IOException {
862       MessageLite.Builder subBuilder = null;
863       MessageLite existingValue = (MessageLite) extensions.getField(extension.descriptor);
864       if (existingValue != null) {
865         subBuilder = existingValue.toBuilder();
866       }
867       if (subBuilder == null) {
868         subBuilder = extension.getMessageDefaultInstance().newBuilderForType();
869       }
870       subBuilder.mergeFrom(rawBytes, extensionRegistry);
871       MessageLite value = subBuilder.build();
872 
873       ensureExtensionsAreMutable()
874           .setField(extension.descriptor, extension.singularToFieldSetType(value));
875     }
876 
877     @CanIgnoreReturnValue
ensureExtensionsAreMutable()878     FieldSet<ExtensionDescriptor> ensureExtensionsAreMutable() {
879       if (extensions.isImmutable()) {
880         extensions = extensions.clone();
881       }
882       return extensions;
883     }
884 
verifyExtensionContainingType(final GeneratedExtension<MessageType, ?> extension)885     private void verifyExtensionContainingType(final GeneratedExtension<MessageType, ?> extension) {
886       if (extension.getContainingTypeDefaultInstance() != getDefaultInstanceForType()) {
887         // This can only happen if someone uses unchecked operations.
888         throw new IllegalArgumentException(
889             "This extension is for a different message type.  Please make "
890                 + "sure that you are not suppressing any generics type warnings.");
891       }
892     }
893 
894     /** Check if a singular extension is present. */
895     @Override
hasExtension(final ExtensionLite<MessageType, Type> extension)896     public final <Type> boolean hasExtension(final ExtensionLite<MessageType, Type> extension) {
897       GeneratedExtension<MessageType, Type> extensionLite = checkIsLite(extension);
898 
899       verifyExtensionContainingType(extensionLite);
900       return extensions.hasField(extensionLite.descriptor);
901     }
902 
903     /** Get the number of elements in a repeated extension. */
904     @Override
getExtensionCount( final ExtensionLite<MessageType, List<Type>> extension)905     public final <Type> int getExtensionCount(
906         final ExtensionLite<MessageType, List<Type>> extension) {
907       GeneratedExtension<MessageType, List<Type>> extensionLite = checkIsLite(extension);
908 
909       verifyExtensionContainingType(extensionLite);
910       return extensions.getRepeatedFieldCount(extensionLite.descriptor);
911     }
912 
913     /** Get the value of an extension. */
914     @Override
915     @SuppressWarnings("unchecked")
getExtension(final ExtensionLite<MessageType, Type> extension)916     public final <Type> Type getExtension(final ExtensionLite<MessageType, Type> extension) {
917       GeneratedExtension<MessageType, Type> extensionLite = checkIsLite(extension);
918 
919       verifyExtensionContainingType(extensionLite);
920       final Object value = extensions.getField(extensionLite.descriptor);
921       if (value == null) {
922         return extensionLite.defaultValue;
923       } else {
924         return (Type) extensionLite.fromFieldSetType(value);
925       }
926     }
927 
928     /** Get one element of a repeated extension. */
929     @Override
930     @SuppressWarnings("unchecked")
getExtension( final ExtensionLite<MessageType, List<Type>> extension, final int index)931     public final <Type> Type getExtension(
932         final ExtensionLite<MessageType, List<Type>> extension, final int index) {
933       GeneratedExtension<MessageType, List<Type>> extensionLite = checkIsLite(extension);
934 
935       verifyExtensionContainingType(extensionLite);
936       return (Type)
937           extensionLite.singularFromFieldSetType(
938               extensions.getRepeatedField(extensionLite.descriptor, index));
939     }
940 
941     /** Called by subclasses to check if all extensions are initialized. */
extensionsAreInitialized()942     protected boolean extensionsAreInitialized() {
943       return extensions.isInitialized();
944     }
945 
946     /**
947      * Used by subclasses to serialize extensions. Extension ranges may be interleaved with field
948      * numbers, but we must write them in canonical (sorted by field number) order. ExtensionWriter
949      * helps us write individual ranges of extensions at once.
950      */
951     protected class ExtensionWriter {
952       // Imagine how much simpler this code would be if Java iterators had
953       // a way to get the next element without advancing the iterator.
954 
955       private final Iterator<Map.Entry<ExtensionDescriptor, Object>> iter = extensions.iterator();
956       private Map.Entry<ExtensionDescriptor, Object> next;
957       private final boolean messageSetWireFormat;
958 
ExtensionWriter(boolean messageSetWireFormat)959       private ExtensionWriter(boolean messageSetWireFormat) {
960         if (iter.hasNext()) {
961           next = iter.next();
962         }
963         this.messageSetWireFormat = messageSetWireFormat;
964       }
965 
writeUntil(final int end, final CodedOutputStream output)966       public void writeUntil(final int end, final CodedOutputStream output) throws IOException {
967         while (next != null && next.getKey().getNumber() < end) {
968           ExtensionDescriptor extension = next.getKey();
969           if (messageSetWireFormat
970               && extension.getLiteJavaType() == WireFormat.JavaType.MESSAGE
971               && !extension.isRepeated()) {
972             output.writeMessageSetExtension(extension.getNumber(), (MessageLite) next.getValue());
973           } else {
974             FieldSet.writeField(extension, next.getValue(), output);
975           }
976           if (iter.hasNext()) {
977             next = iter.next();
978           } else {
979             next = null;
980           }
981         }
982       }
983     }
984 
newExtensionWriter()985     protected ExtensionWriter newExtensionWriter() {
986       return new ExtensionWriter(false);
987     }
988 
newMessageSetExtensionWriter()989     protected ExtensionWriter newMessageSetExtensionWriter() {
990       return new ExtensionWriter(true);
991     }
992 
993     /** Called by subclasses to compute the size of extensions. */
extensionsSerializedSize()994     protected int extensionsSerializedSize() {
995       return extensions.getSerializedSize();
996     }
997 
extensionsSerializedSizeAsMessageSet()998     protected int extensionsSerializedSizeAsMessageSet() {
999       return extensions.getMessageSetSerializedSize();
1000     }
1001   }
1002 
1003   /** Lite equivalent of {@link GeneratedMessage.ExtendableBuilder}. */
1004   @SuppressWarnings("unchecked")
1005   public abstract static class ExtendableBuilder<
1006           MessageType extends ExtendableMessage<MessageType, BuilderType>,
1007           BuilderType extends ExtendableBuilder<MessageType, BuilderType>>
1008       extends Builder<MessageType, BuilderType>
1009       implements ExtendableMessageOrBuilder<MessageType, BuilderType> {
ExtendableBuilder(MessageType defaultInstance)1010     protected ExtendableBuilder(MessageType defaultInstance) {
1011       super(defaultInstance);
1012     }
1013 
1014     // For immutable message conversion.
internalSetExtensionSet(FieldSet<ExtensionDescriptor> extensions)1015     void internalSetExtensionSet(FieldSet<ExtensionDescriptor> extensions) {
1016       copyOnWrite();
1017       instance.extensions = extensions;
1018     }
1019 
1020     @Override
copyOnWriteInternal()1021     protected void copyOnWriteInternal() {
1022       super.copyOnWriteInternal();
1023       if (instance.extensions != FieldSet.emptySet()) {
1024         instance.extensions = instance.extensions.clone();
1025       }
1026     }
1027 
ensureExtensionsAreMutable()1028     private FieldSet<ExtensionDescriptor> ensureExtensionsAreMutable() {
1029       FieldSet<ExtensionDescriptor> extensions = instance.extensions;
1030       if (extensions.isImmutable()) {
1031         extensions = extensions.clone();
1032         instance.extensions = extensions;
1033       }
1034       return extensions;
1035     }
1036 
1037     @Override
buildPartial()1038     public final MessageType buildPartial() {
1039       if (!instance.isMutable()) {
1040         return instance;
1041       }
1042 
1043       instance.extensions.makeImmutable();
1044       return super.buildPartial();
1045     }
1046 
verifyExtensionContainingType(final GeneratedExtension<MessageType, ?> extension)1047     private void verifyExtensionContainingType(final GeneratedExtension<MessageType, ?> extension) {
1048       if (extension.getContainingTypeDefaultInstance() != getDefaultInstanceForType()) {
1049         // This can only happen if someone uses unchecked operations.
1050         throw new IllegalArgumentException(
1051             "This extension is for a different message type.  Please make "
1052                 + "sure that you are not suppressing any generics type warnings.");
1053       }
1054     }
1055 
1056     /** Check if a singular extension is present. */
1057     @Override
hasExtension(final ExtensionLite<MessageType, Type> extension)1058     public final <Type> boolean hasExtension(final ExtensionLite<MessageType, Type> extension) {
1059       return instance.hasExtension(extension);
1060     }
1061 
1062     /** Get the number of elements in a repeated extension. */
1063     @Override
getExtensionCount( final ExtensionLite<MessageType, List<Type>> extension)1064     public final <Type> int getExtensionCount(
1065         final ExtensionLite<MessageType, List<Type>> extension) {
1066       return instance.getExtensionCount(extension);
1067     }
1068 
1069     /** Get the value of an extension. */
1070     @Override
getExtension(final ExtensionLite<MessageType, Type> extension)1071     public final <Type> Type getExtension(final ExtensionLite<MessageType, Type> extension) {
1072       return instance.getExtension(extension);
1073     }
1074 
1075     /** Get one element of a repeated extension. */
1076     @Override
getExtension( final ExtensionLite<MessageType, List<Type>> extension, final int index)1077     public final <Type> Type getExtension(
1078         final ExtensionLite<MessageType, List<Type>> extension, final int index) {
1079       return instance.getExtension(extension, index);
1080     }
1081 
1082     /** Set the value of an extension. */
setExtension( final ExtensionLite<MessageType, Type> extension, final Type value)1083     public final <Type> BuilderType setExtension(
1084         final ExtensionLite<MessageType, Type> extension, final Type value) {
1085       GeneratedExtension<MessageType, Type> extensionLite = checkIsLite(extension);
1086 
1087       verifyExtensionContainingType(extensionLite);
1088       copyOnWrite();
1089       ensureExtensionsAreMutable()
1090           .setField(extensionLite.descriptor, extensionLite.toFieldSetType(value));
1091       return (BuilderType) this;
1092     }
1093 
1094     /** Set the value of one element of a repeated extension. */
setExtension( final ExtensionLite<MessageType, List<Type>> extension, final int index, final Type value)1095     public final <Type> BuilderType setExtension(
1096         final ExtensionLite<MessageType, List<Type>> extension, final int index, final Type value) {
1097       GeneratedExtension<MessageType, List<Type>> extensionLite = checkIsLite(extension);
1098 
1099       verifyExtensionContainingType(extensionLite);
1100       copyOnWrite();
1101       ensureExtensionsAreMutable()
1102           .setRepeatedField(
1103               extensionLite.descriptor, index, extensionLite.singularToFieldSetType(value));
1104       return (BuilderType) this;
1105     }
1106 
1107     /** Append a value to a repeated extension. */
addExtension( final ExtensionLite<MessageType, List<Type>> extension, final Type value)1108     public final <Type> BuilderType addExtension(
1109         final ExtensionLite<MessageType, List<Type>> extension, final Type value) {
1110       GeneratedExtension<MessageType, List<Type>> extensionLite = checkIsLite(extension);
1111 
1112       verifyExtensionContainingType(extensionLite);
1113       copyOnWrite();
1114       ensureExtensionsAreMutable()
1115           .addRepeatedField(extensionLite.descriptor, extensionLite.singularToFieldSetType(value));
1116       return (BuilderType) this;
1117     }
1118 
1119     /** Clear an extension. */
clearExtension(final ExtensionLite<MessageType, ?> extension)1120     public final BuilderType clearExtension(final ExtensionLite<MessageType, ?> extension) {
1121       GeneratedExtension<MessageType, ?> extensionLite = checkIsLite(extension);
1122 
1123       verifyExtensionContainingType(extensionLite);
1124       copyOnWrite();
1125       ensureExtensionsAreMutable().clearField(extensionLite.descriptor);
1126       return (BuilderType) this;
1127     }
1128   }
1129 
1130   // -----------------------------------------------------------------
1131 
1132   /** For use by generated code only. */
1133   public static <ContainingType extends MessageLite, 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)1134       GeneratedExtension<ContainingType, Type> newSingularGeneratedExtension(
1135           final ContainingType containingTypeDefaultInstance,
1136           final Type defaultValue,
1137           final MessageLite messageDefaultInstance,
1138           final Internal.EnumLiteMap<?> enumTypeMap,
1139           final int number,
1140           final WireFormat.FieldType type,
1141           final Class singularType) {
1142     return new GeneratedExtension<ContainingType, Type>(
1143         containingTypeDefaultInstance,
1144         defaultValue,
1145         messageDefaultInstance,
1146         new ExtensionDescriptor(
1147             enumTypeMap, number, type, /* isRepeated= */ false, /* isPacked= */ false),
1148         singularType);
1149   }
1150 
1151   /** For use by generated code only. */
1152   public static <ContainingType extends MessageLite, 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)1153       GeneratedExtension<ContainingType, Type> newRepeatedGeneratedExtension(
1154           final ContainingType containingTypeDefaultInstance,
1155           final MessageLite messageDefaultInstance,
1156           final Internal.EnumLiteMap<?> enumTypeMap,
1157           final int number,
1158           final WireFormat.FieldType type,
1159           final boolean isPacked,
1160           final Class singularType) {
1161     @SuppressWarnings("unchecked") // Subclasses ensure Type is a List
1162     Type emptyList = (Type) ProtobufArrayList.emptyList();
1163     return new GeneratedExtension<ContainingType, Type>(
1164         containingTypeDefaultInstance,
1165         emptyList,
1166         messageDefaultInstance,
1167         new ExtensionDescriptor(enumTypeMap, number, type, /* isRepeated= */ true, isPacked),
1168         singularType);
1169   }
1170 
1171   static final class ExtensionDescriptor
1172       implements FieldSet.FieldDescriptorLite<ExtensionDescriptor> {
ExtensionDescriptor( final Internal.EnumLiteMap<?> enumTypeMap, final int number, final WireFormat.FieldType type, final boolean isRepeated, final boolean isPacked)1173     ExtensionDescriptor(
1174         final Internal.EnumLiteMap<?> enumTypeMap,
1175         final int number,
1176         final WireFormat.FieldType type,
1177         final boolean isRepeated,
1178         final boolean isPacked) {
1179       this.enumTypeMap = enumTypeMap;
1180       this.number = number;
1181       this.type = type;
1182       this.isRepeated = isRepeated;
1183       this.isPacked = isPacked;
1184     }
1185 
1186     final Internal.EnumLiteMap<?> enumTypeMap;
1187     final int number;
1188     final WireFormat.FieldType type;
1189     final boolean isRepeated;
1190     final boolean isPacked;
1191 
1192     @Override
getNumber()1193     public int getNumber() {
1194       return number;
1195     }
1196 
1197     @Override
getLiteType()1198     public WireFormat.FieldType getLiteType() {
1199       return type;
1200     }
1201 
1202     @Override
getLiteJavaType()1203     public WireFormat.JavaType getLiteJavaType() {
1204       return type.getJavaType();
1205     }
1206 
1207     @Override
isRepeated()1208     public boolean isRepeated() {
1209       return isRepeated;
1210     }
1211 
1212     @Override
isPacked()1213     public boolean isPacked() {
1214       return isPacked;
1215     }
1216 
1217     @Override
getEnumType()1218     public Internal.EnumLiteMap<?> getEnumType() {
1219       return enumTypeMap;
1220     }
1221 
1222     @Override
1223     @SuppressWarnings("unchecked")
internalMergeFrom(MessageLite.Builder to, MessageLite from)1224     public MessageLite.Builder internalMergeFrom(MessageLite.Builder to, MessageLite from) {
1225       return ((Builder) to).mergeFrom((GeneratedMessageLite) from);
1226     }
1227 
1228     @Override
compareTo(ExtensionDescriptor other)1229     public int compareTo(ExtensionDescriptor other) {
1230       return number - other.number;
1231     }
1232   }
1233 
1234   // =================================================================
1235 
1236   /** Calls Class.getMethod and throws a RuntimeException if it fails. */
1237   @SuppressWarnings("unchecked")
getMethodOrDie(Class clazz, String name, Class... params)1238   static Method getMethodOrDie(Class clazz, String name, Class... params) {
1239     try {
1240       return clazz.getMethod(name, params);
1241     } catch (NoSuchMethodException e) {
1242       throw new RuntimeException(
1243           "Generated message class \"" + clazz.getName() + "\" missing method \"" + name + "\".",
1244           e);
1245     }
1246   }
1247 
1248   /** Calls invoke and throws a RuntimeException if it fails. */
invokeOrDie(Method method, Object object, Object... params)1249   static Object invokeOrDie(Method method, Object object, Object... params) {
1250     try {
1251       return method.invoke(object, params);
1252     } catch (IllegalAccessException e) {
1253       throw new RuntimeException(
1254           "Couldn't use Java reflection to implement protocol message reflection.", e);
1255     } catch (InvocationTargetException e) {
1256       final Throwable cause = e.getCause();
1257       if (cause instanceof RuntimeException) {
1258         throw (RuntimeException) cause;
1259       } else if (cause instanceof Error) {
1260         throw (Error) cause;
1261       } else {
1262         throw new RuntimeException(
1263             "Unexpected exception thrown by generated accessor method.", cause);
1264       }
1265     }
1266   }
1267 
1268   /**
1269    * Lite equivalent to {@link GeneratedMessage.GeneratedExtension}.
1270    *
1271    * <p>Users should ignore the contents of this class and only use objects of this type as
1272    * parameters to extension accessors and ExtensionRegistry.add().
1273    */
1274   public static class GeneratedExtension<ContainingType extends MessageLite, Type>
1275       extends ExtensionLite<ContainingType, Type> {
1276 
1277     /**
1278      * Create a new instance with the given parameters.
1279      *
1280      * <p>The last parameter {@code singularType} is only needed for enum types. We store integer
1281      * values for enum types in a {@link ExtendableMessage} and use Java reflection to convert an
1282      * integer value back into a concrete enum object.
1283      */
GeneratedExtension( final ContainingType containingTypeDefaultInstance, final Type defaultValue, final MessageLite messageDefaultInstance, final ExtensionDescriptor descriptor, final Class singularType)1284     GeneratedExtension(
1285         final ContainingType containingTypeDefaultInstance,
1286         final Type defaultValue,
1287         final MessageLite messageDefaultInstance,
1288         final ExtensionDescriptor descriptor,
1289         final Class singularType) {
1290       // Defensive checks to verify the correct initialization order of
1291       // GeneratedExtensions and their related GeneratedMessages.
1292       if (containingTypeDefaultInstance == null) {
1293         throw new IllegalArgumentException("Null containingTypeDefaultInstance");
1294       }
1295       if (descriptor.getLiteType() == WireFormat.FieldType.MESSAGE
1296           && messageDefaultInstance == null) {
1297         throw new IllegalArgumentException("Null messageDefaultInstance");
1298       }
1299       this.containingTypeDefaultInstance = containingTypeDefaultInstance;
1300       this.defaultValue = defaultValue;
1301       this.messageDefaultInstance = messageDefaultInstance;
1302       this.descriptor = descriptor;
1303     }
1304 
1305     final ContainingType containingTypeDefaultInstance;
1306     final Type defaultValue;
1307     final MessageLite messageDefaultInstance;
1308     final ExtensionDescriptor descriptor;
1309 
1310     /** Default instance of the type being extended, used to identify that type. */
getContainingTypeDefaultInstance()1311     public ContainingType getContainingTypeDefaultInstance() {
1312       return containingTypeDefaultInstance;
1313     }
1314 
1315     /** Get the field number. */
1316     @Override
getNumber()1317     public int getNumber() {
1318       return descriptor.getNumber();
1319     }
1320 
1321     /**
1322      * If the extension is an embedded message or group, returns the default instance of the
1323      * message.
1324      */
1325     @Override
getMessageDefaultInstance()1326     public MessageLite getMessageDefaultInstance() {
1327       return messageDefaultInstance;
1328     }
1329 
fromFieldSetType(Object value)1330     Object fromFieldSetType(Object value) {
1331       if (descriptor.isRepeated()) {
1332         if (descriptor.getLiteJavaType() == WireFormat.JavaType.ENUM) {
1333           ProtobufArrayList<Object> result = new ProtobufArrayList<>();
1334           result.ensureCapacity(((List<?>) value).size());
1335           for (Object element : (List) value) {
1336             result.add(singularFromFieldSetType(element));
1337           }
1338           result.makeImmutable();
1339           return result;
1340         } else {
1341           return value;
1342         }
1343       } else {
1344         return singularFromFieldSetType(value);
1345       }
1346     }
1347 
singularFromFieldSetType(Object value)1348     Object singularFromFieldSetType(Object value) {
1349       if (descriptor.getLiteJavaType() == WireFormat.JavaType.ENUM) {
1350         return descriptor.enumTypeMap.findValueByNumber((Integer) value);
1351       } else {
1352         return value;
1353       }
1354     }
1355 
toFieldSetType(Object value)1356     Object toFieldSetType(Object value) {
1357       if (descriptor.isRepeated()) {
1358         if (descriptor.getLiteJavaType() == WireFormat.JavaType.ENUM) {
1359           List<Object> result = new ArrayList<>();
1360           for (Object element : (List) value) {
1361             result.add(singularToFieldSetType(element));
1362           }
1363           return result;
1364         } else {
1365           return value;
1366         }
1367       } else {
1368         return singularToFieldSetType(value);
1369       }
1370     }
1371 
singularToFieldSetType(Object value)1372     Object singularToFieldSetType(Object value) {
1373       if (descriptor.getLiteJavaType() == WireFormat.JavaType.ENUM) {
1374         return ((Internal.EnumLite) value).getNumber();
1375       } else {
1376         return value;
1377       }
1378     }
1379 
1380     @Override
getLiteType()1381     public FieldType getLiteType() {
1382       return descriptor.getLiteType();
1383     }
1384 
1385     @Override
isRepeated()1386     public boolean isRepeated() {
1387       return descriptor.isRepeated;
1388     }
1389 
1390     @Override
getDefaultValue()1391     public Type getDefaultValue() {
1392       return defaultValue;
1393     }
1394   }
1395 
1396   /**
1397    * A serialized (serializable) form of the generated message. Stores the message as a class name
1398    * and a byte array.
1399    */
1400   protected static final class SerializedForm implements Serializable {
1401 
of(MessageLite message)1402     public static SerializedForm of(MessageLite message) {
1403       return new SerializedForm(message);
1404     }
1405 
1406     private static final long serialVersionUID = 0L;
1407 
1408     // since v3.6.1
1409     private final Class<?> messageClass;
1410     private final String messageClassName;
1411     private final byte[] asBytes;
1412 
1413     /**
1414      * Creates the serialized form by calling {@link com.google.protobuf.MessageLite#toByteArray}.
1415      *
1416      * @param regularForm the message to serialize
1417      */
SerializedForm(MessageLite regularForm)1418     SerializedForm(MessageLite regularForm) {
1419       messageClass = regularForm.getClass();
1420       messageClassName = regularForm.getClass().getName();
1421       asBytes = regularForm.toByteArray();
1422     }
1423 
1424     /**
1425      * When read from an ObjectInputStream, this method converts this object back to the regular
1426      * form. Part of Java's serialization magic.
1427      *
1428      * @return a GeneratedMessage of the type that was serialized
1429      */
readResolve()1430     protected Object readResolve() throws ObjectStreamException {
1431       try {
1432         Class<?> messageClass = resolveMessageClass();
1433         java.lang.reflect.Field defaultInstanceField =
1434             messageClass.getDeclaredField("DEFAULT_INSTANCE");
1435         defaultInstanceField.setAccessible(true);
1436         MessageLite defaultInstance = (MessageLite) defaultInstanceField.get(null);
1437         return defaultInstance.newBuilderForType().mergeFrom(asBytes).buildPartial();
1438       } catch (ClassNotFoundException e) {
1439         throw new RuntimeException("Unable to find proto buffer class: " + messageClassName, e);
1440       } catch (NoSuchFieldException e) {
1441         throw new RuntimeException("Unable to find DEFAULT_INSTANCE in " + messageClassName, e);
1442       } catch (SecurityException e) {
1443         throw new RuntimeException("Unable to call DEFAULT_INSTANCE in " + messageClassName, e);
1444       } catch (IllegalAccessException e) {
1445         throw new RuntimeException("Unable to call parsePartialFrom", e);
1446       } catch (InvalidProtocolBufferException e) {
1447         throw new RuntimeException("Unable to understand proto buffer", e);
1448       }
1449     }
1450 
resolveMessageClass()1451     private Class<?> resolveMessageClass() throws ClassNotFoundException {
1452       return messageClass != null ? messageClass : Class.forName(messageClassName);
1453     }
1454   }
1455 
1456   /** Checks that the {@link Extension} is Lite and returns it as a {@link GeneratedExtension}. */
1457   private static <
1458           MessageType extends ExtendableMessage<MessageType, BuilderType>,
1459           BuilderType extends ExtendableBuilder<MessageType, BuilderType>,
1460           T>
checkIsLite(ExtensionLite<MessageType, T> extension)1461       GeneratedExtension<MessageType, T> checkIsLite(ExtensionLite<MessageType, T> extension) {
1462     if (!extension.isLite()) {
1463       throw new IllegalArgumentException("Expected a lite extension.");
1464     }
1465 
1466     return (GeneratedExtension<MessageType, T>) extension;
1467   }
1468 
1469   /**
1470    * A static helper method for checking if a message is initialized, optionally memoizing.
1471    *
1472    * <p>For use by generated code only.
1473    */
isInitialized( T message, boolean shouldMemoize)1474   protected static final <T extends GeneratedMessageLite<T, ?>> boolean isInitialized(
1475       T message, boolean shouldMemoize) {
1476     byte memoizedIsInitialized =
1477         (Byte) message.dynamicMethod(MethodToInvoke.GET_MEMOIZED_IS_INITIALIZED);
1478     if (memoizedIsInitialized == 1) {
1479       return true;
1480     }
1481     if (memoizedIsInitialized == 0) {
1482       return false;
1483     }
1484     boolean isInitialized = Protobuf.getInstance().schemaFor(message).isInitialized(message);
1485     if (shouldMemoize) {
1486       // TODO: remove the unused variable
1487       Object unused =
1488           message.dynamicMethod(
1489               MethodToInvoke.SET_MEMOIZED_IS_INITIALIZED, isInitialized ? message : null);
1490     }
1491     return isInitialized;
1492   }
1493 
emptyIntList()1494   protected static IntList emptyIntList() {
1495     return IntArrayList.emptyList();
1496   }
1497 
mutableCopy(IntList list)1498   protected static IntList mutableCopy(IntList list) {
1499     int size = list.size();
1500     return list.mutableCopyWithCapacity(size * 2);
1501   }
1502 
emptyLongList()1503   protected static LongList emptyLongList() {
1504     return LongArrayList.emptyList();
1505   }
1506 
mutableCopy(LongList list)1507   protected static LongList mutableCopy(LongList list) {
1508     int size = list.size();
1509     return list.mutableCopyWithCapacity(size * 2);
1510   }
1511 
emptyFloatList()1512   protected static FloatList emptyFloatList() {
1513     return FloatArrayList.emptyList();
1514   }
1515 
mutableCopy(FloatList list)1516   protected static FloatList mutableCopy(FloatList list) {
1517     int size = list.size();
1518     return list.mutableCopyWithCapacity(size * 2);
1519   }
1520 
emptyDoubleList()1521   protected static DoubleList emptyDoubleList() {
1522     return DoubleArrayList.emptyList();
1523   }
1524 
mutableCopy(DoubleList list)1525   protected static DoubleList mutableCopy(DoubleList list) {
1526     int size = list.size();
1527     return list.mutableCopyWithCapacity(size * 2);
1528   }
1529 
emptyBooleanList()1530   protected static BooleanList emptyBooleanList() {
1531     return BooleanArrayList.emptyList();
1532   }
1533 
mutableCopy(BooleanList list)1534   protected static BooleanList mutableCopy(BooleanList list) {
1535     int size = list.size();
1536     return list.mutableCopyWithCapacity(size * 2);
1537   }
1538 
emptyProtobufList()1539   protected static <E> ProtobufList<E> emptyProtobufList() {
1540     return ProtobufArrayList.emptyList();
1541   }
1542 
mutableCopy(ProtobufList<E> list)1543   protected static <E> ProtobufList<E> mutableCopy(ProtobufList<E> list) {
1544     int size = list.size();
1545     return list.mutableCopyWithCapacity(size * 2);
1546   }
1547 
1548   /**
1549    * A {@link Parser} implementation that delegates to the default instance.
1550    *
1551    * <p>For use by generated code only.
1552    */
1553   protected static class DefaultInstanceBasedParser<T extends GeneratedMessageLite<T, ?>>
1554       extends AbstractParser<T> {
1555 
1556     private final T defaultInstance;
1557 
DefaultInstanceBasedParser(T defaultInstance)1558     public DefaultInstanceBasedParser(T defaultInstance) {
1559       this.defaultInstance = defaultInstance;
1560     }
1561 
1562     @Override
parsePartialFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry)1563     public T parsePartialFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry)
1564         throws InvalidProtocolBufferException {
1565       return GeneratedMessageLite.parsePartialFrom(defaultInstance, input, extensionRegistry);
1566     }
1567 
1568     @Override
parsePartialFrom( byte[] input, int offset, int length, ExtensionRegistryLite extensionRegistry)1569     public T parsePartialFrom(
1570         byte[] input, int offset, int length, ExtensionRegistryLite extensionRegistry)
1571         throws InvalidProtocolBufferException {
1572       return GeneratedMessageLite.parsePartialFrom(
1573           defaultInstance, input, offset, length, extensionRegistry);
1574     }
1575   }
1576 
1577   /**
1578    * A static helper method for parsing a partial from input using the extension registry and the
1579    * instance.
1580    */
1581   // TODO: Should this verify that the last tag was 0?
parsePartialFrom( T instance, CodedInputStream input, ExtensionRegistryLite extensionRegistry)1582   static <T extends GeneratedMessageLite<T, ?>> T parsePartialFrom(
1583       T instance, CodedInputStream input, ExtensionRegistryLite extensionRegistry)
1584       throws InvalidProtocolBufferException {
1585     T result = instance.newMutableInstance();
1586     try {
1587       // TODO: Try to make input with type CodedInputStream.ArrayDecoder use
1588       // fast path.
1589       Schema<T> schema = Protobuf.getInstance().schemaFor(result);
1590       schema.mergeFrom(result, CodedInputStreamReader.forCodedInput(input), extensionRegistry);
1591       schema.makeImmutable(result);
1592     } catch (InvalidProtocolBufferException e) {
1593       if (e.getThrownFromInputStream()) {
1594         e = new InvalidProtocolBufferException(e);
1595       }
1596       throw e.setUnfinishedMessage(result);
1597     } catch (UninitializedMessageException e) {
1598       throw e.asInvalidProtocolBufferException().setUnfinishedMessage(result);
1599     } catch (IOException e) {
1600       if (e.getCause() instanceof InvalidProtocolBufferException) {
1601         throw (InvalidProtocolBufferException) e.getCause();
1602       }
1603       throw new InvalidProtocolBufferException(e).setUnfinishedMessage(result);
1604     } catch (RuntimeException e) {
1605       if (e.getCause() instanceof InvalidProtocolBufferException) {
1606         throw (InvalidProtocolBufferException) e.getCause();
1607       }
1608       throw e;
1609     }
1610     return result;
1611   }
1612 
1613   /** A static helper method for parsing a partial from byte array. */
parsePartialFrom( T defaultInstance, byte[] input, int offset, int length, ExtensionRegistryLite extensionRegistry)1614   private static <T extends GeneratedMessageLite<T, ?>> T parsePartialFrom(
1615       T defaultInstance,
1616       byte[] input,
1617       int offset,
1618       int length,
1619       ExtensionRegistryLite extensionRegistry)
1620       throws InvalidProtocolBufferException {
1621     if (length == 0) {
1622       return defaultInstance;
1623     }
1624     T result = defaultInstance.newMutableInstance();
1625     try {
1626       Schema<T> schema = Protobuf.getInstance().schemaFor(result);
1627       schema.mergeFrom(
1628           result, input, offset, offset + length, new ArrayDecoders.Registers(extensionRegistry));
1629       schema.makeImmutable(result);
1630     } catch (InvalidProtocolBufferException e) {
1631       if (e.getThrownFromInputStream()) {
1632         e = new InvalidProtocolBufferException(e);
1633       }
1634       throw e.setUnfinishedMessage(result);
1635     } catch (UninitializedMessageException e) {
1636       throw e.asInvalidProtocolBufferException().setUnfinishedMessage(result);
1637     } catch (IOException e) {
1638       if (e.getCause() instanceof InvalidProtocolBufferException) {
1639         throw (InvalidProtocolBufferException) e.getCause();
1640       }
1641       throw new InvalidProtocolBufferException(e).setUnfinishedMessage(result);
1642     } catch (IndexOutOfBoundsException e) {
1643       throw InvalidProtocolBufferException.truncatedMessage().setUnfinishedMessage(result);
1644     }
1645     return result;
1646   }
1647 
parsePartialFrom( T defaultInstance, CodedInputStream input)1648   protected static <T extends GeneratedMessageLite<T, ?>> T parsePartialFrom(
1649       T defaultInstance, CodedInputStream input) throws InvalidProtocolBufferException {
1650     return parsePartialFrom(defaultInstance, input, ExtensionRegistryLite.getEmptyRegistry());
1651   }
1652 
1653   /**
1654    * Helper method to check if message is initialized.
1655    *
1656    * @throws InvalidProtocolBufferException if it is not initialized.
1657    * @return The message to check.
1658    */
checkMessageInitialized(T message)1659   private static <T extends GeneratedMessageLite<T, ?>> T checkMessageInitialized(T message)
1660       throws InvalidProtocolBufferException {
1661     if (message != null && !message.isInitialized()) {
1662       throw message
1663           .newUninitializedMessageException()
1664           .asInvalidProtocolBufferException()
1665           .setUnfinishedMessage(message);
1666     }
1667     return message;
1668   }
1669 
1670   // Validates last tag.
parseFrom( T defaultInstance, ByteBuffer data, ExtensionRegistryLite extensionRegistry)1671   protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
1672       T defaultInstance, ByteBuffer data, ExtensionRegistryLite extensionRegistry)
1673       throws InvalidProtocolBufferException {
1674     return checkMessageInitialized(
1675         parseFrom(defaultInstance, CodedInputStream.newInstance(data), extensionRegistry));
1676   }
1677 
1678   // Validates last tag.
parseFrom( T defaultInstance, ByteBuffer data)1679   protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
1680       T defaultInstance, ByteBuffer data) throws InvalidProtocolBufferException {
1681     return parseFrom(defaultInstance, data, ExtensionRegistryLite.getEmptyRegistry());
1682   }
1683 
1684   // Validates last tag.
parseFrom( T defaultInstance, ByteString data)1685   protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
1686       T defaultInstance, ByteString data) throws InvalidProtocolBufferException {
1687     return checkMessageInitialized(
1688         parseFrom(defaultInstance, data, ExtensionRegistryLite.getEmptyRegistry()));
1689   }
1690 
1691   // Validates last tag.
parseFrom( T defaultInstance, ByteString data, ExtensionRegistryLite extensionRegistry)1692   protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
1693       T defaultInstance, ByteString data, ExtensionRegistryLite extensionRegistry)
1694       throws InvalidProtocolBufferException {
1695     return checkMessageInitialized(parsePartialFrom(defaultInstance, data, extensionRegistry));
1696   }
1697 
1698   // This is a special case since we want to verify that the last tag is 0. We assume we exhaust the
1699   // ByteString.
parsePartialFrom( T defaultInstance, ByteString data, ExtensionRegistryLite extensionRegistry)1700   private static <T extends GeneratedMessageLite<T, ?>> T parsePartialFrom(
1701       T defaultInstance, ByteString data, ExtensionRegistryLite extensionRegistry)
1702       throws InvalidProtocolBufferException {
1703     CodedInputStream input = data.newCodedInput();
1704     T message = parsePartialFrom(defaultInstance, input, extensionRegistry);
1705     try {
1706       input.checkLastTagWas(0);
1707     } catch (InvalidProtocolBufferException e) {
1708       throw e.setUnfinishedMessage(message);
1709     }
1710     return message;
1711   }
1712 
1713   // Validates last tag.
parseFrom( T defaultInstance, byte[] data)1714   protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
1715       T defaultInstance, byte[] data) throws InvalidProtocolBufferException {
1716     return checkMessageInitialized(parsePartialFrom(
1717         defaultInstance, data, 0, data.length, ExtensionRegistryLite.getEmptyRegistry()));
1718   }
1719 
1720   // Validates last tag.
parseFrom( T defaultInstance, byte[] data, ExtensionRegistryLite extensionRegistry)1721   protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
1722       T defaultInstance, byte[] data, ExtensionRegistryLite extensionRegistry)
1723       throws InvalidProtocolBufferException {
1724     return checkMessageInitialized(
1725         parsePartialFrom(defaultInstance, data, 0, data.length, extensionRegistry));
1726   }
1727 
1728   // Does not validate last tag.
parseFrom( T defaultInstance, InputStream input)1729   protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
1730       T defaultInstance, InputStream input) throws InvalidProtocolBufferException {
1731     return checkMessageInitialized(
1732         parsePartialFrom(
1733             defaultInstance,
1734             CodedInputStream.newInstance(input),
1735             ExtensionRegistryLite.getEmptyRegistry()));
1736   }
1737 
1738   // Does not validate last tag.
parseFrom( T defaultInstance, InputStream input, ExtensionRegistryLite extensionRegistry)1739   protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
1740       T defaultInstance, InputStream input, ExtensionRegistryLite extensionRegistry)
1741       throws InvalidProtocolBufferException {
1742     return checkMessageInitialized(
1743         parsePartialFrom(defaultInstance, CodedInputStream.newInstance(input), extensionRegistry));
1744   }
1745 
1746   // Does not validate last tag.
parseFrom( T defaultInstance, CodedInputStream input)1747   protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
1748       T defaultInstance, CodedInputStream input) throws InvalidProtocolBufferException {
1749     return parseFrom(defaultInstance, input, ExtensionRegistryLite.getEmptyRegistry());
1750   }
1751 
1752   // Does not validate last tag.
parseFrom( T defaultInstance, CodedInputStream input, ExtensionRegistryLite extensionRegistry)1753   protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
1754       T defaultInstance, CodedInputStream input, ExtensionRegistryLite extensionRegistry)
1755       throws InvalidProtocolBufferException {
1756     return checkMessageInitialized(parsePartialFrom(defaultInstance, input, extensionRegistry));
1757   }
1758 
1759   // Validates last tag.
parseDelimitedFrom( T defaultInstance, InputStream input)1760   protected static <T extends GeneratedMessageLite<T, ?>> T parseDelimitedFrom(
1761       T defaultInstance, InputStream input) throws InvalidProtocolBufferException {
1762     return checkMessageInitialized(
1763         parsePartialDelimitedFrom(
1764             defaultInstance, input, ExtensionRegistryLite.getEmptyRegistry()));
1765   }
1766 
1767   // Validates last tag.
parseDelimitedFrom( T defaultInstance, InputStream input, ExtensionRegistryLite extensionRegistry)1768   protected static <T extends GeneratedMessageLite<T, ?>> T parseDelimitedFrom(
1769       T defaultInstance, InputStream input, ExtensionRegistryLite extensionRegistry)
1770       throws InvalidProtocolBufferException {
1771     return checkMessageInitialized(
1772         parsePartialDelimitedFrom(defaultInstance, input, extensionRegistry));
1773   }
1774 
parsePartialDelimitedFrom( T defaultInstance, InputStream input, ExtensionRegistryLite extensionRegistry)1775   private static <T extends GeneratedMessageLite<T, ?>> T parsePartialDelimitedFrom(
1776       T defaultInstance, InputStream input, ExtensionRegistryLite extensionRegistry)
1777       throws InvalidProtocolBufferException {
1778     int size;
1779     try {
1780       int firstByte = input.read();
1781       if (firstByte == -1) {
1782         return null;
1783       }
1784       size = CodedInputStream.readRawVarint32(firstByte, input);
1785     } catch (InvalidProtocolBufferException e) {
1786       if (e.getThrownFromInputStream()) {
1787         e = new InvalidProtocolBufferException(e);
1788       }
1789       throw e;
1790     } catch (IOException e) {
1791       throw new InvalidProtocolBufferException(e);
1792     }
1793     InputStream limitedInput = new LimitedInputStream(input, size);
1794     CodedInputStream codedInput = CodedInputStream.newInstance(limitedInput);
1795     T message = parsePartialFrom(defaultInstance, codedInput, extensionRegistry);
1796     try {
1797       codedInput.checkLastTagWas(0);
1798     } catch (InvalidProtocolBufferException e) {
1799       throw e.setUnfinishedMessage(message);
1800     }
1801     return message;
1802   }
1803 }
1804