• 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.GeneratedMessageLite.EqualsVisitor.NotEqualsException;
35 import com.google.protobuf.Internal.BooleanList;
36 import com.google.protobuf.Internal.DoubleList;
37 import com.google.protobuf.Internal.FloatList;
38 import com.google.protobuf.Internal.IntList;
39 import com.google.protobuf.Internal.LongList;
40 import com.google.protobuf.Internal.ProtobufList;
41 import com.google.protobuf.WireFormat.FieldType;
42 
43 import java.io.IOException;
44 import java.io.InputStream;
45 import java.io.ObjectStreamException;
46 import java.io.Serializable;
47 import java.lang.reflect.InvocationTargetException;
48 import java.lang.reflect.Method;
49 import java.util.ArrayList;
50 import java.util.Collections;
51 import java.util.Iterator;
52 import java.util.List;
53 import java.util.Map;
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    * <p>
95    * NOTE: This method relies on the field getter methods not being stripped or renamed by proguard.
96    * If they are, the fields will not be included in the returned string representation.
97    * <p>
98    * 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       HashCodeVisitor visitor = new HashCodeVisitor();
111       visit(visitor, (MessageType) this);
112       memoizedHashCode = visitor.hashCode;
113     }
114     return memoizedHashCode;
115   }
116 
117   @SuppressWarnings("unchecked") // Guaranteed by runtime
hashCode(HashCodeVisitor visitor)118   int hashCode(HashCodeVisitor visitor) {
119     if (memoizedHashCode == 0) {
120       int inProgressHashCode = visitor.hashCode;
121       visitor.hashCode = 0;
122       visit(visitor, (MessageType) this);
123       memoizedHashCode = visitor.hashCode;
124       visitor.hashCode = inProgressHashCode;
125     }
126     return memoizedHashCode;
127   }
128 
129   @SuppressWarnings("unchecked") // Guaranteed by isInstance + runtime
130   @Override
equals(Object other)131   public boolean equals(Object other) {
132     if (this == other) {
133       return true;
134     }
135 
136     if (!getDefaultInstanceForType().getClass().isInstance(other)) {
137       return false;
138     }
139 
140     try {
141       visit(EqualsVisitor.INSTANCE, (MessageType) other);
142     } catch (NotEqualsException e) {
143       return false;
144     }
145     return true;
146   }
147 
148   /**
149    * Same as {@link #equals(Object)} but throws {@code NotEqualsException}.
150    */
151   @SuppressWarnings("unchecked") // Guaranteed by isInstance + runtime
equals(EqualsVisitor visitor, MessageLite other)152   boolean equals(EqualsVisitor visitor, MessageLite other) {
153     if (this == other) {
154       return true;
155     }
156 
157     if (!getDefaultInstanceForType().getClass().isInstance(other)) {
158       return false;
159     }
160 
161     visit(visitor, (MessageType) other);
162     return true;
163   }
164 
165   // The general strategy for unknown fields is to use an UnknownFieldSetLite that is treated as
166   // mutable during the parsing constructor and immutable after. This allows us to avoid
167   // any unnecessary intermediary allocations while reducing the generated code size.
168 
169   /**
170    * Lazily initializes unknown fields.
171    */
ensureUnknownFieldsInitialized()172   private final void ensureUnknownFieldsInitialized() {
173     if (unknownFields == UnknownFieldSetLite.getDefaultInstance()) {
174       unknownFields = UnknownFieldSetLite.newInstance();
175     }
176   }
177 
178   /**
179    * Called by subclasses to parse an unknown field. For use by generated code only.
180    *
181    * @return {@code true} unless the tag is an end-group tag.
182    */
parseUnknownField(int tag, CodedInputStream input)183   protected boolean parseUnknownField(int tag, CodedInputStream input) throws IOException {
184     // This will avoid the allocation of unknown fields when a group tag is encountered.
185     if (WireFormat.getTagWireType(tag) == WireFormat.WIRETYPE_END_GROUP) {
186       return false;
187     }
188 
189     ensureUnknownFieldsInitialized();
190     return unknownFields.mergeFieldFrom(tag, input);
191   }
192 
193   /**
194    * Called by subclasses to parse an unknown field. For use by generated code only.
195    */
mergeVarintField(int tag, int value)196   protected void mergeVarintField(int tag, int value) {
197     ensureUnknownFieldsInitialized();
198     unknownFields.mergeVarintField(tag, value);
199   }
200 
201   /**
202    * Called by subclasses to parse an unknown field. For use by generated code only.
203    */
mergeLengthDelimitedField(int fieldNumber, ByteString value)204   protected void mergeLengthDelimitedField(int fieldNumber, ByteString value) {
205     ensureUnknownFieldsInitialized();
206     unknownFields.mergeLengthDelimitedField(fieldNumber, value);
207   }
208 
209   /**
210    * Called by subclasses to complete parsing. For use by generated code only.
211    */
makeImmutable()212   protected void makeImmutable() {
213     dynamicMethod(MethodToInvoke.MAKE_IMMUTABLE);
214 
215     unknownFields.makeImmutable();
216   }
217 
218   @Override
isInitialized()219   public final boolean isInitialized() {
220     return dynamicMethod(MethodToInvoke.IS_INITIALIZED, Boolean.TRUE) != null;
221   }
222 
223   @Override
toBuilder()224   public final BuilderType toBuilder() {
225     BuilderType builder = (BuilderType) dynamicMethod(MethodToInvoke.NEW_BUILDER);
226     builder.mergeFrom((MessageType) this);
227     return builder;
228   }
229 
230   /**
231    * Defines which method path to invoke in {@link GeneratedMessageLite
232    * #dynamicMethod(MethodToInvoke, Object...)}.
233    * <p>
234    * For use by generated code only.
235    */
236   public static enum MethodToInvoke {
237     // Rely on/modify instance state
238     IS_INITIALIZED,
239     VISIT,
240     MERGE_FROM_STREAM,
241     MAKE_IMMUTABLE,
242 
243     // Rely on static state
244     NEW_MUTABLE_INSTANCE,
245     NEW_BUILDER,
246     GET_DEFAULT_INSTANCE,
247     GET_PARSER;
248   }
249 
250   /**
251    * A method that implements different types of operations described in {@link MethodToInvoke}.
252    * Theses different kinds of operations are required to implement message-level operations for
253    * builders in the runtime. This method bundles those operations to reduce the generated methods
254    * count.
255    * <ul>
256    * <li>{@code MERGE_FROM_STREAM} is parameterized with an {@link CodedInputStream} and
257    * {@link ExtensionRegistryLite}. It consumes the input stream, parsing the contents into the
258    * returned protocol buffer. If parsing throws an {@link InvalidProtocolBufferException}, the
259    * implementation wraps it in a RuntimeException.
260    * <li>{@code NEW_INSTANCE} returns a new instance of the protocol buffer that has not yet been
261    * made immutable. See {@code MAKE_IMMUTABLE}.
262    * <li>{@code IS_INITIALIZED} is parameterized with a {@code Boolean} detailing whether to
263    * memoize. It returns {@code null} for false and the default instance for true. We optionally
264    * memoize to support the Builder case, where memoization is not desired.
265    * <li>{@code NEW_BUILDER} returns a {@code BuilderType} instance.
266    * <li>{@code VISIT} is parameterized with a {@code Visitor} and a {@code MessageType} and
267    * recursively iterates through the fields side by side between this and the instance.
268    * <li>{@code MAKE_IMMUTABLE} sets all internal fields to an immutable state.
269    * </ul>
270    * This method, plus the implementation of the Builder, enables the Builder class to be proguarded
271    * away entirely on Android.
272    * <p>
273    * For use by generated code only.
274    */
dynamicMethod(MethodToInvoke method, Object arg0, Object arg1)275   protected abstract Object dynamicMethod(MethodToInvoke method, Object arg0, Object arg1);
276 
277   /**
278    * Same as {@link #dynamicMethod(MethodToInvoke, Object, Object)} with {@code null} padding.
279    */
dynamicMethod(MethodToInvoke method, Object arg0)280   protected Object dynamicMethod(MethodToInvoke method, Object arg0) {
281     return dynamicMethod(method, arg0, null);
282   }
283 
284   /**
285    * Same as {@link #dynamicMethod(MethodToInvoke, Object, Object)} with {@code null} padding.
286    */
dynamicMethod(MethodToInvoke method)287   protected Object dynamicMethod(MethodToInvoke method) {
288     return dynamicMethod(method, null, null);
289   }
290 
visit(Visitor visitor, MessageType other)291   void visit(Visitor visitor, MessageType other) {
292     dynamicMethod(MethodToInvoke.VISIT, visitor, other);
293     unknownFields = visitor.visitUnknownFields(unknownFields, other.unknownFields);
294   }
295 
296   /**
297    * Merge some unknown fields into the {@link UnknownFieldSetLite} for this
298    * message.
299    *
300    * <p>For use by generated code only.
301    */
mergeUnknownFields(UnknownFieldSetLite unknownFields)302   protected final void mergeUnknownFields(UnknownFieldSetLite unknownFields) {
303     this.unknownFields = UnknownFieldSetLite.mutableCopyOf(this.unknownFields, unknownFields);
304   }
305 
306   @SuppressWarnings("unchecked")
307   public abstract static class Builder<
308       MessageType extends GeneratedMessageLite<MessageType, BuilderType>,
309       BuilderType extends Builder<MessageType, BuilderType>>
310           extends AbstractMessageLite.Builder<MessageType, BuilderType> {
311 
312     private final MessageType defaultInstance;
313     protected MessageType instance;
314     protected boolean isBuilt;
315 
Builder(MessageType defaultInstance)316     protected Builder(MessageType defaultInstance) {
317       this.defaultInstance = defaultInstance;
318       this.instance =
319           (MessageType) defaultInstance.dynamicMethod(MethodToInvoke.NEW_MUTABLE_INSTANCE);
320       isBuilt = false;
321     }
322 
323     /**
324      * Called before any method that would mutate the builder to ensure that it correctly copies
325      * any state before the write happens to preserve immutability guarantees.
326      */
copyOnWrite()327     protected void copyOnWrite() {
328       if (isBuilt) {
329         MessageType newInstance =
330             (MessageType) instance.dynamicMethod(MethodToInvoke.NEW_MUTABLE_INSTANCE);
331         newInstance.visit(MergeFromVisitor.INSTANCE, instance);
332         instance = newInstance;
333         isBuilt = false;
334       }
335     }
336 
337     @Override
isInitialized()338     public final boolean isInitialized() {
339       return GeneratedMessageLite.isInitialized(instance, false /* shouldMemoize */);
340     }
341 
342     @Override
clear()343     public final BuilderType clear() {
344       // No need to copy on write since we're dropping the instance anyways.
345       instance = (MessageType) instance.dynamicMethod(MethodToInvoke.NEW_MUTABLE_INSTANCE);
346       return (BuilderType) this;
347     }
348 
349     @Override
clone()350     public BuilderType clone() {
351       BuilderType builder =
352           (BuilderType) getDefaultInstanceForType().newBuilderForType();
353       builder.mergeFrom(buildPartial());
354       return builder;
355     }
356 
357     @Override
buildPartial()358     public MessageType buildPartial() {
359       if (isBuilt) {
360         return instance;
361       }
362 
363       instance.makeImmutable();
364 
365       isBuilt = true;
366       return instance;
367     }
368 
369     @Override
build()370     public final MessageType build() {
371       MessageType result = buildPartial();
372       if (!result.isInitialized()) {
373         throw newUninitializedMessageException(result);
374       }
375       return result;
376     }
377 
378     @Override
internalMergeFrom(MessageType message)379     protected BuilderType internalMergeFrom(MessageType message) {
380       return mergeFrom(message);
381     }
382 
383     /** All subclasses implement this. */
mergeFrom(MessageType message)384     public BuilderType mergeFrom(MessageType message) {
385       copyOnWrite();
386       instance.visit(MergeFromVisitor.INSTANCE, message);
387       return (BuilderType) this;
388     }
389 
390     @Override
getDefaultInstanceForType()391     public MessageType getDefaultInstanceForType() {
392       return defaultInstance;
393     }
394 
395     @Override
mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)396     public BuilderType mergeFrom(
397         com.google.protobuf.CodedInputStream input,
398         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
399         throws IOException {
400       copyOnWrite();
401       try {
402         instance.dynamicMethod(MethodToInvoke.MERGE_FROM_STREAM, input, extensionRegistry);
403       } catch (RuntimeException e) {
404         if (e.getCause() instanceof IOException) {
405           throw (IOException) e.getCause();
406         }
407         throw e;
408       }
409       return (BuilderType) this;
410     }
411   }
412 
413 
414   // =================================================================
415   // Extensions-related stuff
416 
417   /**
418    * Lite equivalent of {@link com.google.protobuf.GeneratedMessage.ExtendableMessageOrBuilder}.
419    */
420   public interface ExtendableMessageOrBuilder<
421       MessageType extends ExtendableMessage<MessageType, BuilderType>,
422       BuilderType extends ExtendableBuilder<MessageType, BuilderType>>
423           extends MessageLiteOrBuilder {
424 
425     /** Check if a singular extension is present. */
hasExtension( ExtensionLite<MessageType, Type> extension)426     <Type> boolean hasExtension(
427         ExtensionLite<MessageType, Type> extension);
428 
429     /** Get the number of elements in a repeated extension. */
getExtensionCount( ExtensionLite<MessageType, List<Type>> extension)430     <Type> int getExtensionCount(
431         ExtensionLite<MessageType, List<Type>> extension);
432 
433     /** Get the value of an extension. */
getExtension(ExtensionLite<MessageType, Type> extension)434     <Type> Type getExtension(ExtensionLite<MessageType, Type> extension);
435 
436     /** Get one element of a repeated extension. */
getExtension( ExtensionLite<MessageType, List<Type>> extension, int index)437     <Type> Type getExtension(
438         ExtensionLite<MessageType, List<Type>> extension,
439         int index);
440   }
441 
442   /**
443    * Lite equivalent of {@link GeneratedMessage.ExtendableMessage}.
444    */
445   public abstract static class ExtendableMessage<
446         MessageType extends ExtendableMessage<MessageType, BuilderType>,
447         BuilderType extends ExtendableBuilder<MessageType, BuilderType>>
448             extends GeneratedMessageLite<MessageType, BuilderType>
449             implements ExtendableMessageOrBuilder<MessageType, BuilderType> {
450 
451     /**
452      * Represents the set of extensions on this message. For use by generated
453      * code only.
454      */
455     protected FieldSet<ExtensionDescriptor> extensions = FieldSet.newFieldSet();
456 
mergeExtensionFields(final MessageType other)457     protected final void mergeExtensionFields(final MessageType other) {
458       if (extensions.isImmutable()) {
459         extensions = extensions.clone();
460       }
461       extensions.mergeFrom(((ExtendableMessage) other).extensions);
462     }
463 
464     @Override
visit(Visitor visitor, MessageType other)465     final void visit(Visitor visitor, MessageType other) {
466       super.visit(visitor, other);
467       extensions = visitor.visitExtensions(extensions, other.extensions);
468     }
469 
470     /**
471      * Parse an unknown field or an extension. For use by generated code only.
472      *
473      * <p>For use by generated code only.
474      *
475      * @return {@code true} unless the tag is an end-group tag.
476      */
parseUnknownField( MessageType defaultInstance, CodedInputStream input, ExtensionRegistryLite extensionRegistry, int tag)477     protected <MessageType extends MessageLite> boolean parseUnknownField(
478         MessageType defaultInstance,
479         CodedInputStream input,
480         ExtensionRegistryLite extensionRegistry,
481         int tag) throws IOException {
482       int wireType = WireFormat.getTagWireType(tag);
483       int fieldNumber = WireFormat.getTagFieldNumber(tag);
484 
485       // TODO(dweis): How much bytecode would be saved by not requiring the generated code to
486       //     provide the default instance?
487       GeneratedExtension<MessageType, ?> extension = extensionRegistry.findLiteExtensionByNumber(
488           defaultInstance, fieldNumber);
489 
490       boolean unknown = false;
491       boolean packed = false;
492       if (extension == null) {
493         unknown = true;  // Unknown field.
494       } else if (wireType == FieldSet.getWireFormatForFieldType(
495                    extension.descriptor.getLiteType(),
496                    false  /* isPacked */)) {
497         packed = false;  // Normal, unpacked value.
498       } else if (extension.descriptor.isRepeated &&
499                  extension.descriptor.type.isPackable() &&
500                  wireType == FieldSet.getWireFormatForFieldType(
501                    extension.descriptor.getLiteType(),
502                    true  /* isPacked */)) {
503         packed = true;  // Packed value.
504       } else {
505         unknown = true;  // Wrong wire type.
506       }
507 
508       if (unknown) {  // Unknown field or wrong wire type.  Skip.
509         return parseUnknownField(tag, input);
510       }
511 
512       if (packed) {
513         int length = input.readRawVarint32();
514         int limit = input.pushLimit(length);
515         if (extension.descriptor.getLiteType() == WireFormat.FieldType.ENUM) {
516           while (input.getBytesUntilLimit() > 0) {
517             int rawValue = input.readEnum();
518             Object value =
519                 extension.descriptor.getEnumType().findValueByNumber(rawValue);
520             if (value == null) {
521               // If the number isn't recognized as a valid value for this
522               // enum, drop it (don't even add it to unknownFields).
523               return true;
524             }
525             extensions.addRepeatedField(extension.descriptor,
526                                         extension.singularToFieldSetType(value));
527           }
528         } else {
529           while (input.getBytesUntilLimit() > 0) {
530             Object value =
531                 FieldSet.readPrimitiveField(input,
532                                             extension.descriptor.getLiteType(),
533                                             /*checkUtf8=*/ false);
534             extensions.addRepeatedField(extension.descriptor, value);
535           }
536         }
537         input.popLimit(limit);
538       } else {
539         Object value;
540         switch (extension.descriptor.getLiteJavaType()) {
541           case MESSAGE: {
542             MessageLite.Builder subBuilder = null;
543             if (!extension.descriptor.isRepeated()) {
544               MessageLite existingValue =
545                   (MessageLite) extensions.getField(extension.descriptor);
546               if (existingValue != null) {
547                 subBuilder = existingValue.toBuilder();
548               }
549             }
550             if (subBuilder == null) {
551               subBuilder = extension.getMessageDefaultInstance()
552                   .newBuilderForType();
553             }
554             if (extension.descriptor.getLiteType() ==
555                 WireFormat.FieldType.GROUP) {
556               input.readGroup(extension.getNumber(),
557                               subBuilder, extensionRegistry);
558             } else {
559               input.readMessage(subBuilder, extensionRegistry);
560             }
561             value = subBuilder.build();
562             break;
563           }
564           case ENUM:
565             int rawValue = input.readEnum();
566             value = extension.descriptor.getEnumType()
567                              .findValueByNumber(rawValue);
568             // If the number isn't recognized as a valid value for this enum,
569             // write it to unknown fields object.
570             if (value == null) {
571               mergeVarintField(fieldNumber, rawValue);
572               return true;
573             }
574             break;
575           default:
576             value = FieldSet.readPrimitiveField(input,
577                 extension.descriptor.getLiteType(),
578                 /*checkUtf8=*/ false);
579             break;
580         }
581 
582         if (extension.descriptor.isRepeated()) {
583           extensions.addRepeatedField(extension.descriptor,
584                                       extension.singularToFieldSetType(value));
585         } else {
586           extensions.setField(extension.descriptor,
587                               extension.singularToFieldSetType(value));
588         }
589       }
590 
591       return true;
592     }
593 
verifyExtensionContainingType( final GeneratedExtension<MessageType, ?> extension)594     private void verifyExtensionContainingType(
595         final GeneratedExtension<MessageType, ?> extension) {
596       if (extension.getContainingTypeDefaultInstance() !=
597           getDefaultInstanceForType()) {
598         // This can only happen if someone uses unchecked operations.
599         throw new IllegalArgumentException(
600           "This extension is for a different message type.  Please make " +
601           "sure that you are not suppressing any generics type warnings.");
602       }
603     }
604 
605     /** Check if a singular extension is present. */
606     @Override
hasExtension(final ExtensionLite<MessageType, Type> extension)607     public final <Type> boolean hasExtension(final ExtensionLite<MessageType, Type> extension) {
608       GeneratedExtension<MessageType, Type> extensionLite =
609           checkIsLite(extension);
610 
611       verifyExtensionContainingType(extensionLite);
612       return extensions.hasField(extensionLite.descriptor);
613     }
614 
615     /** Get the number of elements in a repeated extension. */
616     @Override
getExtensionCount( final ExtensionLite<MessageType, List<Type>> extension)617     public final <Type> int getExtensionCount(
618         final ExtensionLite<MessageType, List<Type>> extension) {
619       GeneratedExtension<MessageType, List<Type>> extensionLite =
620           checkIsLite(extension);
621 
622       verifyExtensionContainingType(extensionLite);
623       return extensions.getRepeatedFieldCount(extensionLite.descriptor);
624     }
625 
626     /** Get the value of an extension. */
627     @Override
628     @SuppressWarnings("unchecked")
getExtension(final ExtensionLite<MessageType, Type> extension)629     public final <Type> Type getExtension(final ExtensionLite<MessageType, Type> extension) {
630       GeneratedExtension<MessageType, Type> extensionLite =
631           checkIsLite(extension);
632 
633       verifyExtensionContainingType(extensionLite);
634       final Object value = extensions.getField(extensionLite.descriptor);
635       if (value == null) {
636         return extensionLite.defaultValue;
637       } else {
638         return (Type) extensionLite.fromFieldSetType(value);
639       }
640     }
641 
642     /** Get one element of a repeated extension. */
643     @Override
644     @SuppressWarnings("unchecked")
getExtension( final ExtensionLite<MessageType, List<Type>> extension, final int index)645     public final <Type> Type getExtension(
646         final ExtensionLite<MessageType, List<Type>> extension, final int index) {
647       GeneratedExtension<MessageType, List<Type>> extensionLite =
648           checkIsLite(extension);
649 
650       verifyExtensionContainingType(extensionLite);
651       return (Type) extensionLite.singularFromFieldSetType(
652           extensions.getRepeatedField(extensionLite.descriptor, index));
653     }
654 
655     /** Called by subclasses to check if all extensions are initialized. */
extensionsAreInitialized()656     protected boolean extensionsAreInitialized() {
657       return extensions.isInitialized();
658     }
659 
660     @Override
makeImmutable()661     protected final void makeImmutable() {
662       super.makeImmutable();
663 
664       extensions.makeImmutable();
665     }
666 
667     /**
668      * Used by subclasses to serialize extensions.  Extension ranges may be
669      * interleaved with field numbers, but we must write them in canonical
670      * (sorted by field number) order.  ExtensionWriter helps us write
671      * individual ranges of extensions at once.
672      */
673     protected class ExtensionWriter {
674       // Imagine how much simpler this code would be if Java iterators had
675       // a way to get the next element without advancing the iterator.
676 
677       private final Iterator<Map.Entry<ExtensionDescriptor, Object>> iter =
678             extensions.iterator();
679       private Map.Entry<ExtensionDescriptor, Object> next;
680       private final boolean messageSetWireFormat;
681 
ExtensionWriter(boolean messageSetWireFormat)682       private ExtensionWriter(boolean messageSetWireFormat) {
683         if (iter.hasNext()) {
684           next = iter.next();
685         }
686         this.messageSetWireFormat = messageSetWireFormat;
687       }
688 
writeUntil(final int end, final CodedOutputStream output)689       public void writeUntil(final int end, final CodedOutputStream output)
690                              throws IOException {
691         while (next != null && next.getKey().getNumber() < end) {
692           ExtensionDescriptor extension = next.getKey();
693           if (messageSetWireFormat && extension.getLiteJavaType() ==
694                   WireFormat.JavaType.MESSAGE &&
695               !extension.isRepeated()) {
696             output.writeMessageSetExtension(extension.getNumber(),
697                                             (MessageLite) next.getValue());
698           } else {
699             FieldSet.writeField(extension, next.getValue(), output);
700           }
701           if (iter.hasNext()) {
702             next = iter.next();
703           } else {
704             next = null;
705           }
706         }
707       }
708     }
709 
newExtensionWriter()710     protected ExtensionWriter newExtensionWriter() {
711       return new ExtensionWriter(false);
712     }
newMessageSetExtensionWriter()713     protected ExtensionWriter newMessageSetExtensionWriter() {
714       return new ExtensionWriter(true);
715     }
716 
717     /** Called by subclasses to compute the size of extensions. */
extensionsSerializedSize()718     protected int extensionsSerializedSize() {
719       return extensions.getSerializedSize();
720     }
extensionsSerializedSizeAsMessageSet()721     protected int extensionsSerializedSizeAsMessageSet() {
722       return extensions.getMessageSetSerializedSize();
723     }
724   }
725 
726   /**
727    * Lite equivalent of {@link GeneratedMessage.ExtendableBuilder}.
728    */
729   @SuppressWarnings("unchecked")
730   public abstract static class ExtendableBuilder<
731         MessageType extends ExtendableMessage<MessageType, BuilderType>,
732         BuilderType extends ExtendableBuilder<MessageType, BuilderType>>
733       extends Builder<MessageType, BuilderType>
734       implements ExtendableMessageOrBuilder<MessageType, BuilderType> {
ExtendableBuilder(MessageType defaultInstance)735     protected ExtendableBuilder(MessageType defaultInstance) {
736       super(defaultInstance);
737 
738       // TODO(dweis): This is kind of an unnecessary clone since we construct a
739       //     new instance in the parent constructor which makes the extensions
740       //     immutable. This extra allocation shouldn't matter in practice
741       //     though.
742       instance.extensions = instance.extensions.clone();
743     }
744 
745     // For immutable message conversion.
internalSetExtensionSet(FieldSet<ExtensionDescriptor> extensions)746     void internalSetExtensionSet(FieldSet<ExtensionDescriptor> extensions) {
747       copyOnWrite();
748       instance.extensions = extensions;
749     }
750 
751     @Override
copyOnWrite()752     protected void copyOnWrite() {
753       if (!isBuilt) {
754         return;
755       }
756 
757       super.copyOnWrite();
758       instance.extensions = instance.extensions.clone();
759     }
760 
761     @Override
buildPartial()762     public final MessageType buildPartial() {
763       if (isBuilt) {
764         return instance;
765       }
766 
767       instance.extensions.makeImmutable();
768       return super.buildPartial();
769     }
770 
verifyExtensionContainingType( final GeneratedExtension<MessageType, ?> extension)771     private void verifyExtensionContainingType(
772         final GeneratedExtension<MessageType, ?> extension) {
773       if (extension.getContainingTypeDefaultInstance() !=
774           getDefaultInstanceForType()) {
775         // This can only happen if someone uses unchecked operations.
776         throw new IllegalArgumentException(
777           "This extension is for a different message type.  Please make " +
778           "sure that you are not suppressing any generics type warnings.");
779       }
780     }
781 
782     /** Check if a singular extension is present. */
783     @Override
hasExtension(final ExtensionLite<MessageType, Type> extension)784     public final <Type> boolean hasExtension(final ExtensionLite<MessageType, Type> extension) {
785       return instance.hasExtension(extension);
786     }
787 
788     /** Get the number of elements in a repeated extension. */
789     @Override
getExtensionCount( final ExtensionLite<MessageType, List<Type>> extension)790     public final <Type> int getExtensionCount(
791         final ExtensionLite<MessageType, List<Type>> extension) {
792       return instance.getExtensionCount(extension);
793     }
794 
795     /** Get the value of an extension. */
796     @Override
797     @SuppressWarnings("unchecked")
getExtension(final ExtensionLite<MessageType, Type> extension)798     public final <Type> Type getExtension(final ExtensionLite<MessageType, Type> extension) {
799       return instance.getExtension(extension);
800     }
801 
802     /** Get one element of a repeated extension. */
803     @Override
804     @SuppressWarnings("unchecked")
getExtension( final ExtensionLite<MessageType, List<Type>> extension, final int index)805     public final <Type> Type getExtension(
806         final ExtensionLite<MessageType, List<Type>> extension, final int index) {
807       return instance.getExtension(extension, index);
808     }
809 
810     // This is implemented here only to work around an apparent bug in the
811     // Java compiler and/or build system.  See bug #1898463.  The mere presence
812     // of this dummy clone() implementation makes it go away.
813     @Override
clone()814     public BuilderType clone() {
815       return super.clone();
816     }
817 
818     /** Set the value of an extension. */
setExtension( final ExtensionLite<MessageType, Type> extension, final Type value)819     public final <Type> BuilderType setExtension(
820         final ExtensionLite<MessageType, Type> extension,
821         final Type value) {
822       GeneratedExtension<MessageType, Type> extensionLite =
823           checkIsLite(extension);
824 
825       verifyExtensionContainingType(extensionLite);
826       copyOnWrite();
827       instance.extensions.setField(extensionLite.descriptor, extensionLite.toFieldSetType(value));
828       return (BuilderType) this;
829     }
830 
831     /** Set the value of one element of a repeated extension. */
setExtension( final ExtensionLite<MessageType, List<Type>> extension, final int index, final Type value)832     public final <Type> BuilderType setExtension(
833         final ExtensionLite<MessageType, List<Type>> extension,
834         final int index, final Type value) {
835       GeneratedExtension<MessageType, List<Type>> extensionLite =
836           checkIsLite(extension);
837 
838       verifyExtensionContainingType(extensionLite);
839       copyOnWrite();
840       instance.extensions.setRepeatedField(
841           extensionLite.descriptor, index, extensionLite.singularToFieldSetType(value));
842       return (BuilderType) this;
843     }
844 
845     /** Append a value to a repeated extension. */
addExtension( final ExtensionLite<MessageType, List<Type>> extension, final Type value)846     public final <Type> BuilderType addExtension(
847         final ExtensionLite<MessageType, List<Type>> extension,
848         final Type value) {
849       GeneratedExtension<MessageType, List<Type>> extensionLite =
850           checkIsLite(extension);
851 
852       verifyExtensionContainingType(extensionLite);
853       copyOnWrite();
854       instance.extensions.addRepeatedField(
855           extensionLite.descriptor, extensionLite.singularToFieldSetType(value));
856       return (BuilderType) this;
857     }
858 
859     /** Clear an extension. */
clearExtension( final ExtensionLite<MessageType, ?> extension)860     public final <Type> BuilderType clearExtension(
861         final ExtensionLite<MessageType, ?> extension) {
862       GeneratedExtension<MessageType, ?> extensionLite = checkIsLite(extension);
863 
864       verifyExtensionContainingType(extensionLite);
865       copyOnWrite();
866       instance.extensions.clearField(extensionLite.descriptor);
867       return (BuilderType) this;
868     }
869   }
870 
871   // -----------------------------------------------------------------
872 
873   /** For use by generated code only. */
874   public static <ContainingType extends MessageLite, Type>
875       GeneratedExtension<ContainingType, Type>
newSingularGeneratedExtension( final ContainingType containingTypeDefaultInstance, final Type defaultValue, final MessageLite messageDefaultInstance, final Internal.EnumLiteMap<?> enumTypeMap, final int number, final WireFormat.FieldType type, final Class singularType)876           newSingularGeneratedExtension(
877               final ContainingType containingTypeDefaultInstance,
878               final Type defaultValue,
879               final MessageLite messageDefaultInstance,
880               final Internal.EnumLiteMap<?> enumTypeMap,
881               final int number,
882               final WireFormat.FieldType type,
883               final Class singularType) {
884     return new GeneratedExtension<ContainingType, Type>(
885         containingTypeDefaultInstance,
886         defaultValue,
887         messageDefaultInstance,
888         new ExtensionDescriptor(enumTypeMap, number, type,
889                                 false /* isRepeated */,
890                                 false /* isPacked */),
891         singularType);
892   }
893 
894   /** For use by generated code only. */
895   public static <ContainingType extends MessageLite, Type>
896       GeneratedExtension<ContainingType, Type>
newRepeatedGeneratedExtension( final ContainingType containingTypeDefaultInstance, final MessageLite messageDefaultInstance, final Internal.EnumLiteMap<?> enumTypeMap, final int number, final WireFormat.FieldType type, final boolean isPacked, final Class singularType)897           newRepeatedGeneratedExtension(
898               final ContainingType containingTypeDefaultInstance,
899               final MessageLite messageDefaultInstance,
900               final Internal.EnumLiteMap<?> enumTypeMap,
901               final int number,
902               final WireFormat.FieldType type,
903               final boolean isPacked,
904               final Class singularType) {
905     @SuppressWarnings("unchecked")  // Subclasses ensure Type is a List
906     Type emptyList = (Type) Collections.emptyList();
907     return new GeneratedExtension<ContainingType, Type>(
908         containingTypeDefaultInstance,
909         emptyList,
910         messageDefaultInstance,
911         new ExtensionDescriptor(
912             enumTypeMap, number, type, true /* isRepeated */, isPacked),
913         singularType);
914   }
915 
916   static final class ExtensionDescriptor
917       implements FieldSet.FieldDescriptorLite<
918         ExtensionDescriptor> {
ExtensionDescriptor( final Internal.EnumLiteMap<?> enumTypeMap, final int number, final WireFormat.FieldType type, final boolean isRepeated, final boolean isPacked)919     ExtensionDescriptor(
920         final Internal.EnumLiteMap<?> enumTypeMap,
921         final int number,
922         final WireFormat.FieldType type,
923         final boolean isRepeated,
924         final boolean isPacked) {
925       this.enumTypeMap = enumTypeMap;
926       this.number = number;
927       this.type = type;
928       this.isRepeated = isRepeated;
929       this.isPacked = isPacked;
930     }
931 
932     final Internal.EnumLiteMap<?> enumTypeMap;
933     final int number;
934     final WireFormat.FieldType type;
935     final boolean isRepeated;
936     final boolean isPacked;
937 
938     @Override
getNumber()939     public int getNumber() {
940       return number;
941     }
942 
943     @Override
getLiteType()944     public WireFormat.FieldType getLiteType() {
945       return type;
946     }
947 
948     @Override
getLiteJavaType()949     public WireFormat.JavaType getLiteJavaType() {
950       return type.getJavaType();
951     }
952 
953     @Override
isRepeated()954     public boolean isRepeated() {
955       return isRepeated;
956     }
957 
958     @Override
isPacked()959     public boolean isPacked() {
960       return isPacked;
961     }
962 
963     @Override
getEnumType()964     public Internal.EnumLiteMap<?> getEnumType() {
965       return enumTypeMap;
966     }
967 
968     @Override
969     @SuppressWarnings("unchecked")
internalMergeFrom(MessageLite.Builder to, MessageLite from)970     public MessageLite.Builder internalMergeFrom(MessageLite.Builder to, MessageLite from) {
971       return ((Builder) to).mergeFrom((GeneratedMessageLite) from);
972     }
973 
974 
975     @Override
compareTo(ExtensionDescriptor other)976     public int compareTo(ExtensionDescriptor other) {
977       return number - other.number;
978     }
979   }
980 
981   // =================================================================
982 
983   /** Calls Class.getMethod and throws a RuntimeException if it fails. */
984   @SuppressWarnings("unchecked")
getMethodOrDie(Class clazz, String name, Class... params)985   static Method getMethodOrDie(Class clazz, String name, Class... params) {
986     try {
987       return clazz.getMethod(name, params);
988     } catch (NoSuchMethodException e) {
989       throw new RuntimeException(
990         "Generated message class \"" + clazz.getName() +
991         "\" missing method \"" + name + "\".", e);
992     }
993   }
994 
995   /** Calls invoke and throws a RuntimeException if it fails. */
invokeOrDie(Method method, Object object, Object... params)996   static Object invokeOrDie(Method method, Object object, Object... params) {
997     try {
998       return method.invoke(object, params);
999     } catch (IllegalAccessException e) {
1000       throw new RuntimeException(
1001         "Couldn't use Java reflection to implement protocol message " +
1002         "reflection.", e);
1003     } catch (InvocationTargetException e) {
1004       final Throwable cause = e.getCause();
1005       if (cause instanceof RuntimeException) {
1006         throw (RuntimeException) cause;
1007       } else if (cause instanceof Error) {
1008         throw (Error) cause;
1009       } else {
1010         throw new RuntimeException(
1011           "Unexpected exception thrown by generated accessor method.", cause);
1012       }
1013     }
1014   }
1015 
1016   /**
1017    * Lite equivalent to {@link GeneratedMessage.GeneratedExtension}.
1018    *
1019    * Users should ignore the contents of this class and only use objects of
1020    * this type as parameters to extension accessors and ExtensionRegistry.add().
1021    */
1022   public static class GeneratedExtension<
1023       ContainingType extends MessageLite, Type>
1024           extends ExtensionLite<ContainingType, Type> {
1025 
1026     /**
1027      * Create a new instance with the given parameters.
1028      *
1029      * The last parameter {@code singularType} is only needed for enum types.
1030      * We store integer values for enum types in a {@link ExtendableMessage}
1031      * and use Java reflection to convert an integer value back into a concrete
1032      * enum object.
1033      */
GeneratedExtension( final ContainingType containingTypeDefaultInstance, final Type defaultValue, final MessageLite messageDefaultInstance, final ExtensionDescriptor descriptor, final Class singularType)1034     GeneratedExtension(
1035         final ContainingType containingTypeDefaultInstance,
1036         final Type defaultValue,
1037         final MessageLite messageDefaultInstance,
1038         final ExtensionDescriptor descriptor,
1039         final Class singularType) {
1040       // Defensive checks to verify the correct initialization order of
1041       // GeneratedExtensions and their related GeneratedMessages.
1042       if (containingTypeDefaultInstance == null) {
1043         throw new IllegalArgumentException(
1044             "Null containingTypeDefaultInstance");
1045       }
1046       if (descriptor.getLiteType() == WireFormat.FieldType.MESSAGE &&
1047           messageDefaultInstance == null) {
1048         throw new IllegalArgumentException(
1049             "Null messageDefaultInstance");
1050       }
1051       this.containingTypeDefaultInstance = containingTypeDefaultInstance;
1052       this.defaultValue = defaultValue;
1053       this.messageDefaultInstance = messageDefaultInstance;
1054       this.descriptor = descriptor;
1055     }
1056 
1057     final ContainingType containingTypeDefaultInstance;
1058     final Type defaultValue;
1059     final MessageLite messageDefaultInstance;
1060     final ExtensionDescriptor descriptor;
1061 
1062     /**
1063      * Default instance of the type being extended, used to identify that type.
1064      */
getContainingTypeDefaultInstance()1065     public ContainingType getContainingTypeDefaultInstance() {
1066       return containingTypeDefaultInstance;
1067     }
1068 
1069     /** Get the field number. */
1070     @Override
getNumber()1071     public int getNumber() {
1072       return descriptor.getNumber();
1073     }
1074 
1075 
1076     /**
1077      * If the extension is an embedded message or group, returns the default
1078      * instance of the message.
1079      */
1080     @Override
getMessageDefaultInstance()1081     public MessageLite getMessageDefaultInstance() {
1082       return messageDefaultInstance;
1083     }
1084 
1085     @SuppressWarnings("unchecked")
fromFieldSetType(final Object value)1086     Object fromFieldSetType(final Object value) {
1087       if (descriptor.isRepeated()) {
1088         if (descriptor.getLiteJavaType() == WireFormat.JavaType.ENUM) {
1089           final List result = new ArrayList();
1090           for (final Object element : (List) value) {
1091             result.add(singularFromFieldSetType(element));
1092           }
1093           return result;
1094         } else {
1095           return value;
1096         }
1097       } else {
1098         return singularFromFieldSetType(value);
1099       }
1100     }
1101 
singularFromFieldSetType(final Object value)1102     Object singularFromFieldSetType(final Object value) {
1103       if (descriptor.getLiteJavaType() == WireFormat.JavaType.ENUM) {
1104         return descriptor.enumTypeMap.findValueByNumber((Integer) value);
1105       } else {
1106         return value;
1107       }
1108     }
1109 
1110     @SuppressWarnings("unchecked")
toFieldSetType(final Object value)1111     Object toFieldSetType(final Object value) {
1112       if (descriptor.isRepeated()) {
1113         if (descriptor.getLiteJavaType() == WireFormat.JavaType.ENUM) {
1114           final List result = new ArrayList();
1115           for (final Object element : (List) value) {
1116             result.add(singularToFieldSetType(element));
1117           }
1118           return result;
1119         } else {
1120           return value;
1121         }
1122       } else {
1123         return singularToFieldSetType(value);
1124       }
1125     }
1126 
singularToFieldSetType(final Object value)1127     Object singularToFieldSetType(final Object value) {
1128       if (descriptor.getLiteJavaType() == WireFormat.JavaType.ENUM) {
1129         return ((Internal.EnumLite) value).getNumber();
1130       } else {
1131         return value;
1132       }
1133     }
1134 
1135     @Override
getLiteType()1136     public FieldType getLiteType() {
1137       return descriptor.getLiteType();
1138     }
1139 
1140     @Override
isRepeated()1141     public boolean isRepeated() {
1142       return descriptor.isRepeated;
1143     }
1144 
1145     @Override
getDefaultValue()1146     public Type getDefaultValue() {
1147       return defaultValue;
1148     }
1149   }
1150 
1151   /**
1152    * A serialized (serializable) form of the generated message.  Stores the
1153    * message as a class name and a byte array.
1154    */
1155   protected static final class SerializedForm implements Serializable {
1156 
of(MessageLite message)1157     public static SerializedForm of(MessageLite message) {
1158       return new SerializedForm(message);
1159     }
1160 
1161     private static final long serialVersionUID = 0L;
1162 
1163     private final String messageClassName;
1164     private final byte[] asBytes;
1165 
1166     /**
1167      * Creates the serialized form by calling {@link com.google.protobuf.MessageLite#toByteArray}.
1168      * @param regularForm the message to serialize
1169      */
SerializedForm(MessageLite regularForm)1170     SerializedForm(MessageLite regularForm) {
1171       messageClassName = regularForm.getClass().getName();
1172       asBytes = regularForm.toByteArray();
1173     }
1174 
1175     /**
1176      * When read from an ObjectInputStream, this method converts this object
1177      * back to the regular form.  Part of Java's serialization magic.
1178      * @return a GeneratedMessage of the type that was serialized
1179      */
1180     @SuppressWarnings("unchecked")
readResolve()1181     protected Object readResolve() throws ObjectStreamException {
1182       try {
1183         Class<?> messageClass = Class.forName(messageClassName);
1184         java.lang.reflect.Field defaultInstanceField =
1185             messageClass.getDeclaredField("DEFAULT_INSTANCE");
1186         defaultInstanceField.setAccessible(true);
1187         MessageLite defaultInstance = (MessageLite) defaultInstanceField.get(null);
1188         return defaultInstance.newBuilderForType()
1189             .mergeFrom(asBytes)
1190             .buildPartial();
1191       } catch (ClassNotFoundException e) {
1192         throw new RuntimeException("Unable to find proto buffer class: " + messageClassName, e);
1193       } catch (NoSuchFieldException e) {
1194         return readResolveFallback();
1195       } catch (SecurityException e) {
1196         throw new RuntimeException("Unable to call DEFAULT_INSTANCE in " + messageClassName, e);
1197       } catch (IllegalAccessException e) {
1198         throw new RuntimeException("Unable to call parsePartialFrom", e);
1199       } catch (InvalidProtocolBufferException e) {
1200         throw new RuntimeException("Unable to understand proto buffer", e);
1201       }
1202     }
1203 
1204     /**
1205      * @deprecated from v3.0.0-beta-3+, for compatibility with v2.5.0 and v2.6.1 generated code.
1206      */
1207     @Deprecated
readResolveFallback()1208     private Object readResolveFallback() throws ObjectStreamException {
1209       try {
1210         Class<?> messageClass = Class.forName(messageClassName);
1211         java.lang.reflect.Field defaultInstanceField =
1212             messageClass.getDeclaredField("defaultInstance");
1213         defaultInstanceField.setAccessible(true);
1214         MessageLite defaultInstance = (MessageLite) defaultInstanceField.get(null);
1215         return defaultInstance.newBuilderForType()
1216             .mergeFrom(asBytes)
1217             .buildPartial();
1218       } catch (ClassNotFoundException e) {
1219         throw new RuntimeException("Unable to find proto buffer class: " + messageClassName, e);
1220       } catch (NoSuchFieldException e) {
1221         throw new RuntimeException("Unable to find defaultInstance in " + messageClassName, e);
1222       } catch (SecurityException e) {
1223         throw new RuntimeException("Unable to call defaultInstance in " + messageClassName, e);
1224       } catch (IllegalAccessException e) {
1225         throw new RuntimeException("Unable to call parsePartialFrom", e);
1226       } catch (InvalidProtocolBufferException e) {
1227         throw new RuntimeException("Unable to understand proto buffer", e);
1228       }
1229     }
1230   }
1231 
1232   /**
1233    * Checks that the {@link Extension} is Lite and returns it as a
1234    * {@link GeneratedExtension}.
1235    */
1236   private static <
1237       MessageType extends ExtendableMessage<MessageType, BuilderType>,
1238       BuilderType extends ExtendableBuilder<MessageType, BuilderType>,
1239       T>
checkIsLite( ExtensionLite<MessageType, T> extension)1240     GeneratedExtension<MessageType, T> checkIsLite(
1241         ExtensionLite<MessageType, T> extension) {
1242     if (!extension.isLite()) {
1243       throw new IllegalArgumentException("Expected a lite extension.");
1244     }
1245 
1246     return (GeneratedExtension<MessageType, T>) extension;
1247   }
1248 
1249   /**
1250    * A static helper method for checking if a message is initialized, optionally memoizing.
1251    * <p>
1252    * For use by generated code only.
1253    */
isInitialized( T message, boolean shouldMemoize)1254   protected static final <T extends GeneratedMessageLite<T, ?>> boolean isInitialized(
1255       T message, boolean shouldMemoize) {
1256     return message.dynamicMethod(MethodToInvoke.IS_INITIALIZED, shouldMemoize) != null;
1257   }
1258 
makeImmutable(T message)1259   protected static final <T extends GeneratedMessageLite<T, ?>> void makeImmutable(T message) {
1260     message.dynamicMethod(MethodToInvoke.MAKE_IMMUTABLE);
1261   }
1262 
emptyIntList()1263   protected static IntList emptyIntList() {
1264     return IntArrayList.emptyList();
1265   }
1266 
mutableCopy(IntList list)1267   protected static IntList mutableCopy(IntList list) {
1268     int size = list.size();
1269     return list.mutableCopyWithCapacity(
1270         size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2);
1271   }
1272 
emptyLongList()1273   protected static LongList emptyLongList() {
1274     return LongArrayList.emptyList();
1275   }
1276 
mutableCopy(LongList list)1277   protected static LongList mutableCopy(LongList list) {
1278     int size = list.size();
1279     return list.mutableCopyWithCapacity(
1280         size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2);
1281   }
1282 
emptyFloatList()1283   protected static FloatList emptyFloatList() {
1284     return FloatArrayList.emptyList();
1285   }
1286 
mutableCopy(FloatList list)1287   protected static FloatList mutableCopy(FloatList list) {
1288     int size = list.size();
1289     return list.mutableCopyWithCapacity(
1290         size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2);
1291   }
1292 
emptyDoubleList()1293   protected static DoubleList emptyDoubleList() {
1294     return DoubleArrayList.emptyList();
1295   }
1296 
mutableCopy(DoubleList list)1297   protected static DoubleList mutableCopy(DoubleList list) {
1298     int size = list.size();
1299     return list.mutableCopyWithCapacity(
1300         size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2);
1301   }
1302 
emptyBooleanList()1303   protected static BooleanList emptyBooleanList() {
1304     return BooleanArrayList.emptyList();
1305   }
1306 
mutableCopy(BooleanList list)1307   protected static BooleanList mutableCopy(BooleanList list) {
1308     int size = list.size();
1309     return list.mutableCopyWithCapacity(
1310         size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2);
1311   }
1312 
emptyProtobufList()1313   protected static <E> ProtobufList<E> emptyProtobufList() {
1314     return ProtobufArrayList.emptyList();
1315   }
1316 
mutableCopy(ProtobufList<E> list)1317   protected static <E> ProtobufList<E> mutableCopy(ProtobufList<E> list) {
1318     int size = list.size();
1319     return list.mutableCopyWithCapacity(
1320         size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2);
1321   }
1322 
1323   /**
1324    * A {@link Parser} implementation that delegates to the default instance.
1325    * <p>
1326    * For use by generated code only.
1327    */
1328   protected static class DefaultInstanceBasedParser<T extends GeneratedMessageLite<T, ?>>
1329       extends AbstractParser<T> {
1330 
1331     private T defaultInstance;
1332 
DefaultInstanceBasedParser(T defaultInstance)1333     public DefaultInstanceBasedParser(T defaultInstance) {
1334       this.defaultInstance = defaultInstance;
1335     }
1336 
1337     @Override
parsePartialFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry)1338     public T parsePartialFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry)
1339         throws InvalidProtocolBufferException {
1340       return GeneratedMessageLite.parsePartialFrom(defaultInstance, input, extensionRegistry);
1341     }
1342   }
1343 
1344   /**
1345    * A static helper method for parsing a partial from input using the extension registry and the
1346    * instance.
1347    */
1348   // TODO(dweis): Should this verify that the last tag was 0?
parsePartialFrom( T instance, CodedInputStream input, ExtensionRegistryLite extensionRegistry)1349   static <T extends GeneratedMessageLite<T, ?>> T parsePartialFrom(
1350       T instance, CodedInputStream input, ExtensionRegistryLite extensionRegistry)
1351           throws InvalidProtocolBufferException {
1352     @SuppressWarnings("unchecked") // Guaranteed by protoc
1353     T result = (T) instance.dynamicMethod(MethodToInvoke.NEW_MUTABLE_INSTANCE);
1354     try {
1355       result.dynamicMethod(MethodToInvoke.MERGE_FROM_STREAM, input, extensionRegistry);
1356       result.makeImmutable();
1357     } catch (RuntimeException e) {
1358       if (e.getCause() instanceof InvalidProtocolBufferException) {
1359         throw (InvalidProtocolBufferException) e.getCause();
1360       }
1361       throw e;
1362     }
1363     return result;
1364   }
1365 
parsePartialFrom( T defaultInstance, CodedInputStream input)1366   protected static <T extends GeneratedMessageLite<T, ?>> T parsePartialFrom(
1367       T defaultInstance,
1368       CodedInputStream input)
1369       throws InvalidProtocolBufferException {
1370     return parsePartialFrom(defaultInstance, input, ExtensionRegistryLite.getEmptyRegistry());
1371   }
1372 
1373   /**
1374    * Helper method to check if message is initialized.
1375    *
1376    * @throws InvalidProtocolBufferException if it is not initialized.
1377    * @return The message to check.
1378    */
checkMessageInitialized(T message)1379   private static <T extends GeneratedMessageLite<T, ?>> T checkMessageInitialized(T message)
1380       throws InvalidProtocolBufferException {
1381     if (message != null && !message.isInitialized()) {
1382       throw message.newUninitializedMessageException()
1383           .asInvalidProtocolBufferException()
1384           .setUnfinishedMessage(message);
1385     }
1386     return message;
1387   }
1388 
1389   // Validates last tag.
parseFrom( T defaultInstance, ByteString data)1390   protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
1391       T defaultInstance, ByteString data)
1392       throws InvalidProtocolBufferException {
1393     return checkMessageInitialized(
1394         parseFrom(defaultInstance, data, ExtensionRegistryLite.getEmptyRegistry()));
1395   }
1396 
1397   // Validates last tag.
parseFrom( T defaultInstance, ByteString data, ExtensionRegistryLite extensionRegistry)1398   protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
1399       T defaultInstance, ByteString data, ExtensionRegistryLite extensionRegistry)
1400       throws InvalidProtocolBufferException {
1401     return checkMessageInitialized(parsePartialFrom(defaultInstance, data, extensionRegistry));
1402   }
1403 
1404   // This is a special case since we want to verify that the last tag is 0. We assume we exhaust the
1405   // ByteString.
parsePartialFrom( T defaultInstance, ByteString data, ExtensionRegistryLite extensionRegistry)1406   private static <T extends GeneratedMessageLite<T, ?>> T parsePartialFrom(
1407       T defaultInstance, ByteString data, ExtensionRegistryLite extensionRegistry)
1408       throws InvalidProtocolBufferException {
1409     T message;
1410     try {
1411       CodedInputStream input = data.newCodedInput();
1412       message = parsePartialFrom(defaultInstance, input, extensionRegistry);
1413       try {
1414         input.checkLastTagWas(0);
1415       } catch (InvalidProtocolBufferException e) {
1416         throw e.setUnfinishedMessage(message);
1417       }
1418       return message;
1419     } catch (InvalidProtocolBufferException e) {
1420       throw e;
1421     }
1422   }
1423 
1424   // This is a special case since we want to verify that the last tag is 0. We assume we exhaust the
1425   // ByteString.
parsePartialFrom( T defaultInstance, byte[] data, ExtensionRegistryLite extensionRegistry)1426   private static <T extends GeneratedMessageLite<T, ?>> T parsePartialFrom(
1427       T defaultInstance, byte[] data, ExtensionRegistryLite extensionRegistry)
1428       throws InvalidProtocolBufferException {
1429     T message;
1430     try {
1431       CodedInputStream input = CodedInputStream.newInstance(data);
1432       message = parsePartialFrom(defaultInstance, input, extensionRegistry);
1433       try {
1434         input.checkLastTagWas(0);
1435       } catch (InvalidProtocolBufferException e) {
1436         throw e.setUnfinishedMessage(message);
1437       }
1438       return message;
1439     } catch (InvalidProtocolBufferException e) {
1440       throw e;
1441     }
1442   }
1443 
1444   // Validates last tag.
parseFrom( T defaultInstance, byte[] data)1445   protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
1446       T defaultInstance, byte[] data)
1447       throws InvalidProtocolBufferException {
1448     return checkMessageInitialized(
1449         parsePartialFrom(defaultInstance, data, ExtensionRegistryLite.getEmptyRegistry()));
1450   }
1451 
1452   // Validates last tag.
parseFrom( T defaultInstance, byte[] data, ExtensionRegistryLite extensionRegistry)1453   protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
1454       T defaultInstance, byte[] data, ExtensionRegistryLite extensionRegistry)
1455       throws InvalidProtocolBufferException {
1456     return checkMessageInitialized(parsePartialFrom(defaultInstance, data, extensionRegistry));
1457   }
1458 
1459   // Does not validate last tag.
parseFrom( T defaultInstance, InputStream input)1460   protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
1461       T defaultInstance, InputStream input)
1462       throws InvalidProtocolBufferException {
1463     return checkMessageInitialized(
1464         parsePartialFrom(defaultInstance, CodedInputStream.newInstance(input),
1465             ExtensionRegistryLite.getEmptyRegistry()));
1466   }
1467 
1468   // Does not validate last tag.
parseFrom( T defaultInstance, InputStream input, ExtensionRegistryLite extensionRegistry)1469   protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
1470       T defaultInstance, InputStream input, ExtensionRegistryLite extensionRegistry)
1471       throws InvalidProtocolBufferException {
1472     return checkMessageInitialized(
1473         parsePartialFrom(defaultInstance, CodedInputStream.newInstance(input), extensionRegistry));
1474   }
1475 
1476   // Does not validate last tag.
parseFrom( T defaultInstance, CodedInputStream input)1477   protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
1478       T defaultInstance, CodedInputStream input)
1479       throws InvalidProtocolBufferException {
1480     return parseFrom(defaultInstance, input, ExtensionRegistryLite.getEmptyRegistry());
1481   }
1482 
1483   // Does not validate last tag.
parseFrom( T defaultInstance, CodedInputStream input, ExtensionRegistryLite extensionRegistry)1484   protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
1485       T defaultInstance, CodedInputStream input, ExtensionRegistryLite extensionRegistry)
1486       throws InvalidProtocolBufferException {
1487     return checkMessageInitialized(
1488         parsePartialFrom(defaultInstance, input, extensionRegistry));
1489   }
1490 
1491   // Validates last tag.
parseDelimitedFrom( T defaultInstance, InputStream input)1492   protected static <T extends GeneratedMessageLite<T, ?>> T parseDelimitedFrom(
1493       T defaultInstance, InputStream input)
1494       throws InvalidProtocolBufferException {
1495     return checkMessageInitialized(
1496         parsePartialDelimitedFrom(defaultInstance, input,
1497             ExtensionRegistryLite.getEmptyRegistry()));
1498   }
1499 
1500   // Validates last tag.
parseDelimitedFrom( T defaultInstance, InputStream input, ExtensionRegistryLite extensionRegistry)1501   protected static <T extends GeneratedMessageLite<T, ?>> T parseDelimitedFrom(
1502       T defaultInstance, InputStream input, ExtensionRegistryLite extensionRegistry)
1503       throws InvalidProtocolBufferException {
1504     return checkMessageInitialized(
1505         parsePartialDelimitedFrom(defaultInstance, input, extensionRegistry));
1506   }
1507 
parsePartialDelimitedFrom( T defaultInstance, InputStream input, ExtensionRegistryLite extensionRegistry)1508   private static <T extends GeneratedMessageLite<T, ?>> T parsePartialDelimitedFrom(
1509       T defaultInstance,
1510       InputStream input,
1511       ExtensionRegistryLite extensionRegistry)
1512       throws InvalidProtocolBufferException {
1513     int size;
1514     try {
1515       int firstByte = input.read();
1516       if (firstByte == -1) {
1517         return null;
1518       }
1519       size = CodedInputStream.readRawVarint32(firstByte, input);
1520     } catch (IOException e) {
1521       throw new InvalidProtocolBufferException(e.getMessage());
1522     }
1523     InputStream limitedInput = new LimitedInputStream(input, size);
1524     CodedInputStream codedInput = CodedInputStream.newInstance(limitedInput);
1525     T message = parsePartialFrom(defaultInstance, codedInput, extensionRegistry);
1526     try {
1527       codedInput.checkLastTagWas(0);
1528     } catch (InvalidProtocolBufferException e) {
1529       throw e.setUnfinishedMessage(message);
1530     }
1531     return message;
1532   }
1533 
1534   /**
1535    * An abstract visitor that the generated code calls into that we use to implement various
1536    * features. Fields that are not members of oneofs are always visited. Members of a oneof are only
1537    * visited when they are the set oneof case value on the "other" proto. The visitOneofNotSet
1538    * method is invoked if other's oneof case is not set.
1539    */
1540   protected interface Visitor {
visitBoolean(boolean minePresent, boolean mine, boolean otherPresent, boolean other)1541     boolean visitBoolean(boolean minePresent, boolean mine, boolean otherPresent, boolean other);
visitInt(boolean minePresent, int mine, boolean otherPresent, int other)1542     int visitInt(boolean minePresent, int mine, boolean otherPresent, int other);
visitDouble(boolean minePresent, double mine, boolean otherPresent, double other)1543     double visitDouble(boolean minePresent, double mine, boolean otherPresent, double other);
visitFloat(boolean minePresent, float mine, boolean otherPresent, float other)1544     float visitFloat(boolean minePresent, float mine, boolean otherPresent, float other);
visitLong(boolean minePresent, long mine, boolean otherPresent, long other)1545     long visitLong(boolean minePresent, long mine, boolean otherPresent, long other);
visitString(boolean minePresent, String mine, boolean otherPresent, String other)1546     String visitString(boolean minePresent, String mine, boolean otherPresent, String other);
visitByteString( boolean minePresent, ByteString mine, boolean otherPresent, ByteString other)1547     ByteString visitByteString(
1548         boolean minePresent, ByteString mine, boolean otherPresent, ByteString other);
1549 
visitOneofBoolean(boolean minePresent, Object mine, Object other)1550     Object visitOneofBoolean(boolean minePresent, Object mine, Object other);
visitOneofInt(boolean minePresent, Object mine, Object other)1551     Object visitOneofInt(boolean minePresent, Object mine, Object other);
visitOneofDouble(boolean minePresent, Object mine, Object other)1552     Object visitOneofDouble(boolean minePresent, Object mine, Object other);
visitOneofFloat(boolean minePresent, Object mine, Object other)1553     Object visitOneofFloat(boolean minePresent, Object mine, Object other);
visitOneofLong(boolean minePresent, Object mine, Object other)1554     Object visitOneofLong(boolean minePresent, Object mine, Object other);
visitOneofString(boolean minePresent, Object mine, Object other)1555     Object visitOneofString(boolean minePresent, Object mine, Object other);
visitOneofByteString(boolean minePresent, Object mine, Object other)1556     Object visitOneofByteString(boolean minePresent, Object mine, Object other);
visitOneofLazyMessage(boolean minePresent, Object mine, Object other)1557     Object visitOneofLazyMessage(boolean minePresent, Object mine, Object other);
visitOneofMessage(boolean minePresent, Object mine, Object other)1558     Object visitOneofMessage(boolean minePresent, Object mine, Object other);
visitOneofNotSet(boolean minePresent)1559     void visitOneofNotSet(boolean minePresent);
1560 
1561     /**
1562      * Message fields use null sentinals.
1563      */
visitMessage(T mine, T other)1564     <T extends MessageLite> T visitMessage(T mine, T other);
visitLazyMessage(LazyFieldLite mine, LazyFieldLite other)1565     LazyFieldLite visitLazyMessage(LazyFieldLite mine, LazyFieldLite other);
1566 
visitList(ProtobufList<T> mine, ProtobufList<T> other)1567     <T> ProtobufList<T> visitList(ProtobufList<T> mine, ProtobufList<T> other);
visitBooleanList(BooleanList mine, BooleanList other)1568     BooleanList visitBooleanList(BooleanList mine, BooleanList other);
visitIntList(IntList mine, IntList other)1569     IntList visitIntList(IntList mine, IntList other);
visitDoubleList(DoubleList mine, DoubleList other)1570     DoubleList visitDoubleList(DoubleList mine, DoubleList other);
visitFloatList(FloatList mine, FloatList other)1571     FloatList visitFloatList(FloatList mine, FloatList other);
visitLongList(LongList mine, LongList other)1572     LongList visitLongList(LongList mine, LongList other);
visitExtensions( FieldSet<ExtensionDescriptor> mine, FieldSet<ExtensionDescriptor> other)1573     FieldSet<ExtensionDescriptor> visitExtensions(
1574         FieldSet<ExtensionDescriptor> mine, FieldSet<ExtensionDescriptor> other);
visitUnknownFields(UnknownFieldSetLite mine, UnknownFieldSetLite other)1575     UnknownFieldSetLite visitUnknownFields(UnknownFieldSetLite mine, UnknownFieldSetLite other);
visitMap(MapFieldLite<K, V> mine, MapFieldLite<K, V> other)1576     <K, V> MapFieldLite<K, V> visitMap(MapFieldLite<K, V> mine, MapFieldLite<K, V> other);
1577   }
1578 
1579   /**
1580    * Implements equals. Throws a {@link NotEqualsException} when not equal.
1581    */
1582   static class EqualsVisitor implements Visitor {
1583 
1584     static final class NotEqualsException extends RuntimeException {}
1585 
1586     static final EqualsVisitor INSTANCE = new EqualsVisitor();
1587 
1588     static final NotEqualsException NOT_EQUALS = new NotEqualsException();
1589 
EqualsVisitor()1590     private EqualsVisitor() {}
1591 
1592     @Override
visitBoolean( boolean minePresent, boolean mine, boolean otherPresent, boolean other)1593     public boolean visitBoolean(
1594         boolean minePresent, boolean mine, boolean otherPresent, boolean other) {
1595       if (minePresent != otherPresent || mine != other) {
1596         throw NOT_EQUALS;
1597       }
1598       return mine;
1599     }
1600 
1601     @Override
visitInt(boolean minePresent, int mine, boolean otherPresent, int other)1602     public int visitInt(boolean minePresent, int mine, boolean otherPresent, int other) {
1603       if (minePresent != otherPresent || mine != other) {
1604         throw NOT_EQUALS;
1605       }
1606       return mine;
1607     }
1608 
1609     @Override
visitDouble( boolean minePresent, double mine, boolean otherPresent, double other)1610     public double visitDouble(
1611         boolean minePresent, double mine, boolean otherPresent, double other) {
1612       if (minePresent != otherPresent || mine != other) {
1613         throw NOT_EQUALS;
1614       }
1615       return mine;
1616     }
1617 
1618     @Override
visitFloat(boolean minePresent, float mine, boolean otherPresent, float other)1619     public float visitFloat(boolean minePresent, float mine, boolean otherPresent, float other) {
1620       if (minePresent != otherPresent || mine != other) {
1621         throw NOT_EQUALS;
1622       }
1623       return mine;
1624     }
1625 
1626     @Override
visitLong(boolean minePresent, long mine, boolean otherPresent, long other)1627     public long visitLong(boolean minePresent, long mine, boolean otherPresent, long other) {
1628       if (minePresent != otherPresent || mine != other) {
1629         throw NOT_EQUALS;
1630       }
1631       return mine;
1632     }
1633 
1634     @Override
visitString( boolean minePresent, String mine, boolean otherPresent, String other)1635     public String visitString(
1636         boolean minePresent, String mine, boolean otherPresent, String other) {
1637       if (minePresent != otherPresent || !mine.equals(other)) {
1638         throw NOT_EQUALS;
1639       }
1640       return mine;
1641     }
1642 
1643     @Override
visitByteString( boolean minePresent, ByteString mine, boolean otherPresent, ByteString other)1644     public ByteString visitByteString(
1645         boolean minePresent, ByteString mine, boolean otherPresent, ByteString other) {
1646       if (minePresent != otherPresent || !mine.equals(other)) {
1647         throw NOT_EQUALS;
1648       }
1649       return mine;
1650     }
1651 
1652     @Override
visitOneofBoolean(boolean minePresent, Object mine, Object other)1653     public Object visitOneofBoolean(boolean minePresent, Object mine, Object other) {
1654       if (minePresent && mine.equals(other)) {
1655         return mine;
1656       }
1657       throw NOT_EQUALS;
1658     }
1659 
1660     @Override
visitOneofInt(boolean minePresent, Object mine, Object other)1661     public Object visitOneofInt(boolean minePresent, Object mine, Object other) {
1662       if (minePresent && mine.equals(other)) {
1663         return mine;
1664       }
1665       throw NOT_EQUALS;
1666     }
1667 
1668     @Override
visitOneofDouble(boolean minePresent, Object mine, Object other)1669     public Object visitOneofDouble(boolean minePresent, Object mine, Object other) {
1670       if (minePresent && mine.equals(other)) {
1671         return mine;
1672       }
1673       throw NOT_EQUALS;
1674     }
1675 
1676     @Override
visitOneofFloat(boolean minePresent, Object mine, Object other)1677     public Object visitOneofFloat(boolean minePresent, Object mine, Object other) {
1678       if (minePresent && mine.equals(other)) {
1679         return mine;
1680       }
1681       throw NOT_EQUALS;
1682     }
1683 
1684     @Override
visitOneofLong(boolean minePresent, Object mine, Object other)1685     public Object visitOneofLong(boolean minePresent, Object mine, Object other) {
1686       if (minePresent && mine.equals(other)) {
1687         return mine;
1688       }
1689       throw NOT_EQUALS;
1690     }
1691 
1692     @Override
visitOneofString(boolean minePresent, Object mine, Object other)1693     public Object visitOneofString(boolean minePresent, Object mine, Object other) {
1694       if (minePresent && mine.equals(other)) {
1695         return mine;
1696       }
1697       throw NOT_EQUALS;
1698     }
1699 
1700     @Override
visitOneofByteString(boolean minePresent, Object mine, Object other)1701     public Object visitOneofByteString(boolean minePresent, Object mine, Object other) {
1702       if (minePresent && mine.equals(other)) {
1703         return mine;
1704       }
1705       throw NOT_EQUALS;
1706     }
1707 
1708     @Override
visitOneofLazyMessage(boolean minePresent, Object mine, Object other)1709     public Object visitOneofLazyMessage(boolean minePresent, Object mine, Object other) {
1710       if (minePresent && mine.equals(other)) {
1711         return mine;
1712       }
1713       throw NOT_EQUALS;
1714     }
1715 
1716     @Override
visitOneofMessage(boolean minePresent, Object mine, Object other)1717     public Object visitOneofMessage(boolean minePresent, Object mine, Object other) {
1718       if (minePresent && ((GeneratedMessageLite<?, ?>) mine).equals(this, (MessageLite) other)) {
1719         return mine;
1720       }
1721       throw NOT_EQUALS;
1722     }
1723 
1724     @Override
visitOneofNotSet(boolean minePresent)1725     public void visitOneofNotSet(boolean minePresent) {
1726       if (minePresent) {
1727         throw NOT_EQUALS;
1728       }
1729     }
1730 
1731     @Override
visitMessage(T mine, T other)1732     public <T extends MessageLite> T visitMessage(T mine, T other) {
1733       if (mine == null && other == null) {
1734         return null;
1735       }
1736 
1737       if (mine == null || other == null) {
1738         throw NOT_EQUALS;
1739       }
1740 
1741       ((GeneratedMessageLite<?, ?>) mine).equals(this, other);
1742 
1743       return mine;
1744     }
1745 
1746     @Override
visitLazyMessage( LazyFieldLite mine, LazyFieldLite other)1747     public LazyFieldLite visitLazyMessage(
1748         LazyFieldLite mine, LazyFieldLite other) {
1749       if (mine == null && other == null) {
1750         return null;
1751       }
1752       if (mine == null || other == null) {
1753         throw NOT_EQUALS;
1754       }
1755       if (mine.equals(other)) {
1756         return mine;
1757       }
1758       throw NOT_EQUALS;
1759     }
1760 
1761     @Override
visitList(ProtobufList<T> mine, ProtobufList<T> other)1762     public <T> ProtobufList<T> visitList(ProtobufList<T> mine, ProtobufList<T> other) {
1763       if (!mine.equals(other)) {
1764         throw NOT_EQUALS;
1765       }
1766       return mine;
1767     }
1768 
1769     @Override
visitBooleanList(BooleanList mine, BooleanList other)1770     public BooleanList visitBooleanList(BooleanList mine, BooleanList other) {
1771       if (!mine.equals(other)) {
1772         throw NOT_EQUALS;
1773       }
1774       return mine;
1775     }
1776 
1777     @Override
visitIntList(IntList mine, IntList other)1778     public IntList visitIntList(IntList mine, IntList other) {
1779       if (!mine.equals(other)) {
1780         throw NOT_EQUALS;
1781       }
1782       return mine;
1783     }
1784 
1785     @Override
visitDoubleList(DoubleList mine, DoubleList other)1786     public DoubleList visitDoubleList(DoubleList mine, DoubleList other) {
1787       if (!mine.equals(other)) {
1788         throw NOT_EQUALS;
1789       }
1790       return mine;
1791     }
1792 
1793     @Override
visitFloatList(FloatList mine, FloatList other)1794     public FloatList visitFloatList(FloatList mine, FloatList other) {
1795       if (!mine.equals(other)) {
1796         throw NOT_EQUALS;
1797       }
1798       return mine;
1799     }
1800 
1801     @Override
visitLongList(LongList mine, LongList other)1802     public LongList visitLongList(LongList mine, LongList other) {
1803       if (!mine.equals(other)) {
1804         throw NOT_EQUALS;
1805       }
1806       return mine;
1807     }
1808 
1809     @Override
visitExtensions( FieldSet<ExtensionDescriptor> mine, FieldSet<ExtensionDescriptor> other)1810     public FieldSet<ExtensionDescriptor> visitExtensions(
1811         FieldSet<ExtensionDescriptor> mine,
1812         FieldSet<ExtensionDescriptor> other) {
1813       if (!mine.equals(other)) {
1814         throw NOT_EQUALS;
1815       }
1816       return mine;
1817     }
1818 
1819     @Override
visitUnknownFields( UnknownFieldSetLite mine, UnknownFieldSetLite other)1820     public UnknownFieldSetLite visitUnknownFields(
1821         UnknownFieldSetLite mine,
1822         UnknownFieldSetLite other) {
1823       if (!mine.equals(other)) {
1824         throw NOT_EQUALS;
1825       }
1826       return mine;
1827     }
1828 
1829     @Override
visitMap(MapFieldLite<K, V> mine, MapFieldLite<K, V> other)1830     public <K, V> MapFieldLite<K, V> visitMap(MapFieldLite<K, V> mine, MapFieldLite<K, V> other) {
1831       if (!mine.equals(other)) {
1832         throw NOT_EQUALS;
1833       }
1834       return mine;
1835     }
1836   }
1837 
1838   /**
1839    * Implements hashCode by accumulating state.
1840    */
1841   private static class HashCodeVisitor implements Visitor {
1842 
1843     // The caller must ensure that the visitor is invoked parameterized with this and this such that
1844     // other is this. This is required due to how oneof cases are handled. See the class comment
1845     // on Visitor for more information.
1846 
1847     private int hashCode = 0;
1848 
1849     @Override
visitBoolean( boolean minePresent, boolean mine, boolean otherPresent, boolean other)1850     public boolean visitBoolean(
1851         boolean minePresent, boolean mine, boolean otherPresent, boolean other) {
1852       hashCode = (53 * hashCode) + Internal.hashBoolean(mine);
1853       return mine;
1854     }
1855 
1856     @Override
visitInt(boolean minePresent, int mine, boolean otherPresent, int other)1857     public int visitInt(boolean minePresent, int mine, boolean otherPresent, int other) {
1858       hashCode = (53 * hashCode) + mine;
1859       return mine;
1860     }
1861 
1862     @Override
visitDouble( boolean minePresent, double mine, boolean otherPresent, double other)1863     public double visitDouble(
1864         boolean minePresent, double mine, boolean otherPresent, double other) {
1865       hashCode = (53 * hashCode) + Internal.hashLong(Double.doubleToLongBits(mine));
1866       return mine;
1867     }
1868 
1869     @Override
visitFloat(boolean minePresent, float mine, boolean otherPresent, float other)1870     public float visitFloat(boolean minePresent, float mine, boolean otherPresent, float other) {
1871       hashCode = (53 * hashCode) + Float.floatToIntBits(mine);
1872       return mine;
1873     }
1874 
1875     @Override
visitLong(boolean minePresent, long mine, boolean otherPresent, long other)1876     public long visitLong(boolean minePresent, long mine, boolean otherPresent, long other) {
1877       hashCode = (53 * hashCode) + Internal.hashLong(mine);
1878       return mine;
1879     }
1880 
1881     @Override
visitString( boolean minePresent, String mine, boolean otherPresent, String other)1882     public String visitString(
1883         boolean minePresent, String mine, boolean otherPresent, String other) {
1884       hashCode = (53 * hashCode) + mine.hashCode();
1885       return mine;
1886     }
1887 
1888     @Override
visitByteString( boolean minePresent, ByteString mine, boolean otherPresent, ByteString other)1889     public ByteString visitByteString(
1890         boolean minePresent, ByteString mine, boolean otherPresent, ByteString other) {
1891       hashCode = (53 * hashCode) + mine.hashCode();
1892       return mine;
1893     }
1894 
1895     @Override
visitOneofBoolean(boolean minePresent, Object mine, Object other)1896     public Object visitOneofBoolean(boolean minePresent, Object mine, Object other) {
1897       hashCode = (53 * hashCode) + Internal.hashBoolean(((Boolean) mine));
1898       return mine;
1899     }
1900 
1901     @Override
visitOneofInt(boolean minePresent, Object mine, Object other)1902     public Object visitOneofInt(boolean minePresent, Object mine, Object other) {
1903       hashCode = (53 * hashCode) + (Integer) mine;
1904       return mine;
1905     }
1906 
1907     @Override
visitOneofDouble(boolean minePresent, Object mine, Object other)1908     public Object visitOneofDouble(boolean minePresent, Object mine, Object other) {
1909       hashCode = (53 * hashCode) + Internal.hashLong(Double.doubleToLongBits((Double) mine));
1910       return mine;
1911     }
1912 
1913     @Override
visitOneofFloat(boolean minePresent, Object mine, Object other)1914     public Object visitOneofFloat(boolean minePresent, Object mine, Object other) {
1915       hashCode = (53 * hashCode) + Float.floatToIntBits((Float) mine);
1916       return mine;
1917     }
1918 
1919     @Override
visitOneofLong(boolean minePresent, Object mine, Object other)1920     public Object visitOneofLong(boolean minePresent, Object mine, Object other) {
1921       hashCode = (53 * hashCode) + Internal.hashLong((Long) mine);
1922       return mine;
1923     }
1924 
1925     @Override
visitOneofString(boolean minePresent, Object mine, Object other)1926     public Object visitOneofString(boolean minePresent, Object mine, Object other) {
1927       hashCode = (53 * hashCode) + mine.hashCode();
1928       return mine;
1929     }
1930 
1931     @Override
visitOneofByteString(boolean minePresent, Object mine, Object other)1932     public Object visitOneofByteString(boolean minePresent, Object mine, Object other) {
1933       hashCode = (53 * hashCode) + mine.hashCode();
1934       return mine;
1935     }
1936 
1937     @Override
visitOneofLazyMessage(boolean minePresent, Object mine, Object other)1938     public Object visitOneofLazyMessage(boolean minePresent, Object mine, Object other) {
1939       hashCode = (53 * hashCode) + mine.hashCode();
1940       return mine;
1941     }
1942 
1943     @Override
visitOneofMessage(boolean minePresent, Object mine, Object other)1944     public Object visitOneofMessage(boolean minePresent, Object mine, Object other) {
1945       return visitMessage((MessageLite) mine, (MessageLite) other);
1946     }
1947 
1948     @Override
visitOneofNotSet(boolean minePresent)1949     public void visitOneofNotSet(boolean minePresent) {
1950       if (minePresent) {
1951         throw new IllegalStateException(); // Can't happen if other == this.
1952       }
1953     }
1954 
1955     @Override
visitMessage(T mine, T other)1956     public <T extends MessageLite> T visitMessage(T mine, T other) {
1957       final int protoHash;
1958       if (mine != null) {
1959         if (mine instanceof GeneratedMessageLite) {
1960           protoHash = ((GeneratedMessageLite) mine).hashCode(this);
1961         } else {
1962           protoHash = mine.hashCode();
1963         }
1964       } else {
1965         protoHash = 37;
1966       }
1967       hashCode = (53 * hashCode) + protoHash;
1968       return mine;
1969     }
1970 
1971     @Override
visitLazyMessage(LazyFieldLite mine, LazyFieldLite other)1972     public LazyFieldLite visitLazyMessage(LazyFieldLite mine, LazyFieldLite other) {
1973       final int protoHash;
1974       if (mine != null) {
1975         protoHash = mine.hashCode();
1976       } else {
1977         protoHash = 37;
1978       }
1979       hashCode = (53 * hashCode) + protoHash;
1980       return mine;
1981     }
1982 
1983     @Override
visitList(ProtobufList<T> mine, ProtobufList<T> other)1984     public <T> ProtobufList<T> visitList(ProtobufList<T> mine, ProtobufList<T> other) {
1985       hashCode = (53 * hashCode) + mine.hashCode();
1986       return mine;
1987     }
1988 
1989     @Override
visitBooleanList(BooleanList mine, BooleanList other)1990     public BooleanList visitBooleanList(BooleanList mine, BooleanList other) {
1991       hashCode = (53 * hashCode) + mine.hashCode();
1992       return mine;
1993     }
1994 
1995     @Override
visitIntList(IntList mine, IntList other)1996     public IntList visitIntList(IntList mine, IntList other) {
1997       hashCode = (53 * hashCode) + mine.hashCode();
1998       return mine;
1999     }
2000 
2001     @Override
visitDoubleList(DoubleList mine, DoubleList other)2002     public DoubleList visitDoubleList(DoubleList mine, DoubleList other) {
2003       hashCode = (53 * hashCode) + mine.hashCode();
2004       return mine;
2005     }
2006 
2007     @Override
visitFloatList(FloatList mine, FloatList other)2008     public FloatList visitFloatList(FloatList mine, FloatList other) {
2009       hashCode = (53 * hashCode) + mine.hashCode();
2010       return mine;
2011     }
2012 
2013     @Override
visitLongList(LongList mine, LongList other)2014     public LongList visitLongList(LongList mine, LongList other) {
2015       hashCode = (53 * hashCode) + mine.hashCode();
2016       return mine;
2017     }
2018 
2019     @Override
visitExtensions( FieldSet<ExtensionDescriptor> mine, FieldSet<ExtensionDescriptor> other)2020     public FieldSet<ExtensionDescriptor> visitExtensions(
2021         FieldSet<ExtensionDescriptor> mine,
2022         FieldSet<ExtensionDescriptor> other) {
2023       hashCode = (53 * hashCode) + mine.hashCode();
2024       return mine;
2025     }
2026 
2027     @Override
visitUnknownFields( UnknownFieldSetLite mine, UnknownFieldSetLite other)2028     public UnknownFieldSetLite visitUnknownFields(
2029         UnknownFieldSetLite mine,
2030         UnknownFieldSetLite other) {
2031       hashCode = (53 * hashCode) + mine.hashCode();
2032       return mine;
2033     }
2034 
2035     @Override
visitMap(MapFieldLite<K, V> mine, MapFieldLite<K, V> other)2036     public <K, V> MapFieldLite<K, V> visitMap(MapFieldLite<K, V> mine, MapFieldLite<K, V> other) {
2037       hashCode = (53 * hashCode) + mine.hashCode();
2038       return mine;
2039     }
2040   }
2041 
2042   /**
2043    * Implements field merging semantics over the visitor interface.
2044    */
2045   protected static class MergeFromVisitor implements Visitor {
2046 
2047     public static final MergeFromVisitor INSTANCE = new MergeFromVisitor();
2048 
MergeFromVisitor()2049     private MergeFromVisitor() {}
2050 
2051     @Override
visitBoolean( boolean minePresent, boolean mine, boolean otherPresent, boolean other)2052     public boolean visitBoolean(
2053         boolean minePresent, boolean mine, boolean otherPresent, boolean other) {
2054       return otherPresent ? other : mine;
2055     }
2056 
2057     @Override
visitInt(boolean minePresent, int mine, boolean otherPresent, int other)2058     public int visitInt(boolean minePresent, int mine, boolean otherPresent, int other) {
2059       return otherPresent ? other : mine;
2060     }
2061 
2062     @Override
visitDouble( boolean minePresent, double mine, boolean otherPresent, double other)2063     public double visitDouble(
2064         boolean minePresent, double mine, boolean otherPresent, double other) {
2065       return otherPresent ? other : mine;
2066     }
2067 
2068     @Override
visitFloat(boolean minePresent, float mine, boolean otherPresent, float other)2069     public float visitFloat(boolean minePresent, float mine, boolean otherPresent, float other) {
2070       return otherPresent ? other : mine;
2071     }
2072 
2073     @Override
visitLong(boolean minePresent, long mine, boolean otherPresent, long other)2074     public long visitLong(boolean minePresent, long mine, boolean otherPresent, long other) {
2075       return otherPresent ? other : mine;
2076     }
2077 
2078     @Override
visitString( boolean minePresent, String mine, boolean otherPresent, String other)2079     public String visitString(
2080         boolean minePresent, String mine, boolean otherPresent, String other) {
2081       return otherPresent ? other : mine;
2082     }
2083 
2084     @Override
visitByteString( boolean minePresent, ByteString mine, boolean otherPresent, ByteString other)2085     public ByteString visitByteString(
2086         boolean minePresent, ByteString mine, boolean otherPresent, ByteString other) {
2087       return otherPresent ? other : mine;
2088     }
2089 
2090     @Override
visitOneofBoolean(boolean minePresent, Object mine, Object other)2091     public Object visitOneofBoolean(boolean minePresent, Object mine, Object other) {
2092       return other;
2093     }
2094 
2095     @Override
visitOneofInt(boolean minePresent, Object mine, Object other)2096     public Object visitOneofInt(boolean minePresent, Object mine, Object other) {
2097       return other;
2098     }
2099 
2100     @Override
visitOneofDouble(boolean minePresent, Object mine, Object other)2101     public Object visitOneofDouble(boolean minePresent, Object mine, Object other) {
2102       return other;
2103     }
2104 
2105     @Override
visitOneofFloat(boolean minePresent, Object mine, Object other)2106     public Object visitOneofFloat(boolean minePresent, Object mine, Object other) {
2107       return other;
2108     }
2109 
2110     @Override
visitOneofLong(boolean minePresent, Object mine, Object other)2111     public Object visitOneofLong(boolean minePresent, Object mine, Object other) {
2112       return other;
2113     }
2114 
2115     @Override
visitOneofString(boolean minePresent, Object mine, Object other)2116     public Object visitOneofString(boolean minePresent, Object mine, Object other) {
2117       return other;
2118     }
2119 
2120     @Override
visitOneofByteString(boolean minePresent, Object mine, Object other)2121     public Object visitOneofByteString(boolean minePresent, Object mine, Object other) {
2122       return other;
2123     }
2124 
2125     @Override
visitOneofLazyMessage(boolean minePresent, Object mine, Object other)2126     public Object visitOneofLazyMessage(boolean minePresent, Object mine, Object other) {
2127       LazyFieldLite lazy = minePresent ? (LazyFieldLite) mine : new LazyFieldLite();
2128       lazy.merge((LazyFieldLite) other);
2129       return lazy;
2130     }
2131 
2132     @Override
visitOneofMessage(boolean minePresent, Object mine, Object other)2133     public Object visitOneofMessage(boolean minePresent, Object mine, Object other) {
2134       if (minePresent) {
2135         return visitMessage((MessageLite) mine, (MessageLite) other);
2136       }
2137       return other;
2138     }
2139 
2140     @Override
visitOneofNotSet(boolean minePresent)2141     public void visitOneofNotSet(boolean minePresent) {
2142       return;
2143     }
2144 
2145     @SuppressWarnings("unchecked") // Guaranteed by runtime.
2146     @Override
visitMessage(T mine, T other)2147     public <T extends MessageLite> T visitMessage(T mine, T other) {
2148       if (mine != null && other != null) {
2149         return (T) mine.toBuilder().mergeFrom(other).build();
2150       }
2151 
2152       return mine != null ? mine : other;
2153     }
2154 
2155     @Override
visitLazyMessage(LazyFieldLite mine, LazyFieldLite other)2156     public LazyFieldLite visitLazyMessage(LazyFieldLite mine, LazyFieldLite other) {
2157       if (other != null) {
2158         if (mine == null) {
2159           mine = new LazyFieldLite();
2160         }
2161         mine.merge(other);
2162       }
2163       return mine;
2164     }
2165 
2166     @Override
visitList(ProtobufList<T> mine, ProtobufList<T> other)2167     public <T> ProtobufList<T> visitList(ProtobufList<T> mine, ProtobufList<T> other) {
2168       int size = mine.size();
2169       int otherSize = other.size();
2170       if (size > 0 && otherSize > 0) {
2171         if (!mine.isModifiable()) {
2172           mine = mine.mutableCopyWithCapacity(size + otherSize);
2173         }
2174         mine.addAll(other);
2175       }
2176 
2177       return size > 0 ? mine : other;
2178     }
2179 
2180     @Override
visitBooleanList(BooleanList mine, BooleanList other)2181     public BooleanList visitBooleanList(BooleanList mine, BooleanList other) {
2182       int size = mine.size();
2183       int otherSize = other.size();
2184       if (size > 0 && otherSize > 0) {
2185         if (!mine.isModifiable()) {
2186           mine = mine.mutableCopyWithCapacity(size + otherSize);
2187         }
2188         mine.addAll(other);
2189       }
2190 
2191       return size > 0 ? mine : other;
2192     }
2193 
2194     @Override
visitIntList(IntList mine, IntList other)2195     public IntList visitIntList(IntList mine, IntList other) {
2196       int size = mine.size();
2197       int otherSize = other.size();
2198       if (size > 0 && otherSize > 0) {
2199         if (!mine.isModifiable()) {
2200           mine = mine.mutableCopyWithCapacity(size + otherSize);
2201         }
2202         mine.addAll(other);
2203       }
2204 
2205       return size > 0 ? mine : other;
2206     }
2207 
2208     @Override
visitDoubleList(DoubleList mine, DoubleList other)2209     public DoubleList visitDoubleList(DoubleList mine, DoubleList other) {
2210       int size = mine.size();
2211       int otherSize = other.size();
2212       if (size > 0 && otherSize > 0) {
2213         if (!mine.isModifiable()) {
2214           mine = mine.mutableCopyWithCapacity(size + otherSize);
2215         }
2216         mine.addAll(other);
2217       }
2218 
2219       return size > 0 ? mine : other;
2220     }
2221 
2222     @Override
visitFloatList(FloatList mine, FloatList other)2223     public FloatList visitFloatList(FloatList mine, FloatList other) {
2224       int size = mine.size();
2225       int otherSize = other.size();
2226       if (size > 0 && otherSize > 0) {
2227         if (!mine.isModifiable()) {
2228           mine = mine.mutableCopyWithCapacity(size + otherSize);
2229         }
2230         mine.addAll(other);
2231       }
2232 
2233       return size > 0 ? mine : other;
2234     }
2235 
2236     @Override
visitLongList(LongList mine, LongList other)2237     public LongList visitLongList(LongList mine, LongList other) {
2238       int size = mine.size();
2239       int otherSize = other.size();
2240       if (size > 0 && otherSize > 0) {
2241         if (!mine.isModifiable()) {
2242           mine = mine.mutableCopyWithCapacity(size + otherSize);
2243         }
2244         mine.addAll(other);
2245       }
2246 
2247       return size > 0 ? mine : other;
2248     }
2249 
2250     @Override
visitExtensions( FieldSet<ExtensionDescriptor> mine, FieldSet<ExtensionDescriptor> other)2251     public FieldSet<ExtensionDescriptor> visitExtensions(
2252         FieldSet<ExtensionDescriptor> mine,
2253         FieldSet<ExtensionDescriptor> other) {
2254       if (mine.isImmutable()) {
2255         mine = mine.clone();
2256       }
2257       mine.mergeFrom(other);
2258       return mine;
2259     }
2260 
2261     @Override
visitUnknownFields( UnknownFieldSetLite mine, UnknownFieldSetLite other)2262     public UnknownFieldSetLite visitUnknownFields(
2263         UnknownFieldSetLite mine,
2264         UnknownFieldSetLite other) {
2265       return other == UnknownFieldSetLite.getDefaultInstance()
2266           ? mine : UnknownFieldSetLite.mutableCopyOf(mine, other);
2267     }
2268 
2269     @Override
visitMap(MapFieldLite<K, V> mine, MapFieldLite<K, V> other)2270     public <K, V> MapFieldLite<K, V> visitMap(MapFieldLite<K, V> mine, MapFieldLite<K, V> other) {
2271       if (!other.isEmpty()) {
2272         if (!mine.isMutable()) {
2273           mine = mine.mutableCopy();
2274         }
2275         mine.mergeFrom(other);
2276       }
2277       return mine;
2278     }
2279   }
2280 }
2281