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