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